r.js 1.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420
  1. #!/usr/bin/env node
  2. /**
  3. * @license r.js 2.3.5 Copyright jQuery Foundation and other contributors.
  4. * Released under MIT license, http://github.com/requirejs/r.js/LICENSE
  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.3.5',
  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/requirejs/r.js for usage.');
  31. }
  32. if (typeof process !== 'undefined' && process.versions && !!process.versions.node) {
  33. env = 'node';
  34. //Get the fs module via Node's require before it
  35. //gets replaced. Used in require/node.js
  36. fs = require('fs');
  37. vm = require('vm');
  38. path = require('path');
  39. //In Node 0.7+ existsSync is on fs.
  40. existsForNode = fs.existsSync || path.existsSync;
  41. nodeRequire = require;
  42. nodeDefine = define;
  43. reqMain = require.main;
  44. //Temporarily hide require and define to allow require.js to define
  45. //them.
  46. require = undefined;
  47. define = undefined;
  48. readFile = function (path) {
  49. return fs.readFileSync(path, 'utf8');
  50. };
  51. exec = function (string, name) {
  52. return vm.runInThisContext(this.requirejsVars.require.makeNodeWrapper(string),
  53. name ? fs.realpathSync(name) : '');
  54. };
  55. exists = function (fileName) {
  56. return existsForNode(fileName);
  57. };
  58. fileName = process.argv[2];
  59. if (fileName && fileName.indexOf('-') === 0) {
  60. commandOption = fileName.substring(1);
  61. fileName = process.argv[3];
  62. }
  63. } else if (typeof Packages !== 'undefined') {
  64. env = 'rhino';
  65. fileName = args[0];
  66. if (fileName && fileName.indexOf('-') === 0) {
  67. commandOption = fileName.substring(1);
  68. fileName = args[1];
  69. }
  70. //Exec/readFile differs between Rhino and Nashorn. Rhino has an
  71. //importPackage where Nashorn does not, so branch on that. This is a
  72. //coarser check -- detecting readFile existence might also be enough for
  73. //this spot. However, sticking with importPackage to keep it the same
  74. //as other Rhino/Nashorn detection branches.
  75. if (typeof importPackage !== 'undefined') {
  76. rhinoContext = Packages.org.mozilla.javascript.ContextFactory.getGlobal().enterContext();
  77. exec = function (string, name) {
  78. return rhinoContext.evaluateString(this, string, name, 0, null);
  79. };
  80. } else {
  81. exec = function (string, name) {
  82. load({ script: string, name: name});
  83. };
  84. readFile = readFully;
  85. }
  86. exists = function (fileName) {
  87. return (new java.io.File(fileName)).exists();
  88. };
  89. //Define a console.log for easier logging. Don't
  90. //get fancy though.
  91. if (typeof console === 'undefined') {
  92. console = {
  93. log: function () {
  94. print.apply(undefined, arguments);
  95. }
  96. };
  97. }
  98. } else if ((typeof navigator !== 'undefined' && typeof document !== 'undefined') ||
  99. (typeof importScripts !== 'undefined' && typeof self !== 'undefined')) {
  100. env = 'browser';
  101. readFile = function (path) {
  102. return fs.readFileSync(path, 'utf8');
  103. };
  104. exec = function (string) {
  105. return eval(string);
  106. };
  107. exists = function () {
  108. console.log('x.js exists not applicable in browser env');
  109. return false;
  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.3.5 Copyright jQuery Foundation and other contributors.
  210. * Released under MIT license, https://github.com/requirejs/requirejs/blob/master/LICENSE
  211. */
  212. //Not using strict: uneven strict support in browsers, #392, and causes
  213. //problems with requirejs.exec()/transpiler plugins that may not be strict.
  214. /*jslint regexp: true, nomen: true, sloppy: true */
  215. /*global window, navigator, document, importScripts, setTimeout, opera */
  216. (function (global, setTimeout) {
  217. var req, s, head, baseElement, dataMain, src,
  218. interactiveScript, currentlyAddingScript, mainScript, subPath,
  219. version = '2.3.5',
  220. commentRegExp = /\/\*[\s\S]*?\*\/|([^:"'=]|^)\/\/.*$/mg,
  221. cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,
  222. jsSuffixRegExp = /\.js$/,
  223. currDirRegExp = /^\.\//,
  224. op = Object.prototype,
  225. ostring = op.toString,
  226. hasOwn = op.hasOwnProperty,
  227. isBrowser = !!(typeof window !== 'undefined' && typeof navigator !== 'undefined' && window.document),
  228. isWebWorker = !isBrowser && typeof importScripts !== 'undefined',
  229. //PS3 indicates loaded and complete, but need to wait for complete
  230. //specifically. Sequence is 'loading', 'loaded', execution,
  231. // then 'complete'. The UA check is unfortunate, but not sure how
  232. //to feature test w/o causing perf issues.
  233. readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ?
  234. /^complete$/ : /^(complete|loaded)$/,
  235. defContextName = '_',
  236. //Oh the tragedy, detecting opera. See the usage of isOpera for reason.
  237. isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]',
  238. contexts = {},
  239. cfg = {},
  240. globalDefQueue = [],
  241. useInteractive = false;
  242. //Could match something like ')//comment', do not lose the prefix to comment.
  243. function commentReplace(match, singlePrefix) {
  244. return singlePrefix || '';
  245. }
  246. function isFunction(it) {
  247. return ostring.call(it) === '[object Function]';
  248. }
  249. function isArray(it) {
  250. return ostring.call(it) === '[object Array]';
  251. }
  252. /**
  253. * Helper function for iterating over an array. If the func returns
  254. * a true value, it will break out of the loop.
  255. */
  256. function each(ary, func) {
  257. if (ary) {
  258. var i;
  259. for (i = 0; i < ary.length; i += 1) {
  260. if (ary[i] && func(ary[i], i, ary)) {
  261. break;
  262. }
  263. }
  264. }
  265. }
  266. /**
  267. * Helper function for iterating over an array backwards. If the func
  268. * returns a true value, it will break out of the loop.
  269. */
  270. function eachReverse(ary, func) {
  271. if (ary) {
  272. var i;
  273. for (i = ary.length - 1; i > -1; i -= 1) {
  274. if (ary[i] && func(ary[i], i, ary)) {
  275. break;
  276. }
  277. }
  278. }
  279. }
  280. function hasProp(obj, prop) {
  281. return hasOwn.call(obj, prop);
  282. }
  283. function getOwn(obj, prop) {
  284. return hasProp(obj, prop) && obj[prop];
  285. }
  286. /**
  287. * Cycles over properties in an object and calls a function for each
  288. * property value. If the function returns a truthy value, then the
  289. * iteration is stopped.
  290. */
  291. function eachProp(obj, func) {
  292. var prop;
  293. for (prop in obj) {
  294. if (hasProp(obj, prop)) {
  295. if (func(obj[prop], prop)) {
  296. break;
  297. }
  298. }
  299. }
  300. }
  301. /**
  302. * Simple function to mix in properties from source into target,
  303. * but only if target does not already have a property of the same name.
  304. */
  305. function mixin(target, source, force, deepStringMixin) {
  306. if (source) {
  307. eachProp(source, function (value, prop) {
  308. if (force || !hasProp(target, prop)) {
  309. if (deepStringMixin && typeof value === 'object' && value &&
  310. !isArray(value) && !isFunction(value) &&
  311. !(value instanceof RegExp)) {
  312. if (!target[prop]) {
  313. target[prop] = {};
  314. }
  315. mixin(target[prop], value, force, deepStringMixin);
  316. } else {
  317. target[prop] = value;
  318. }
  319. }
  320. });
  321. }
  322. return target;
  323. }
  324. //Similar to Function.prototype.bind, but the 'this' object is specified
  325. //first, since it is easier to read/figure out what 'this' will be.
  326. function bind(obj, fn) {
  327. return function () {
  328. return fn.apply(obj, arguments);
  329. };
  330. }
  331. function scripts() {
  332. return document.getElementsByTagName('script');
  333. }
  334. function defaultOnError(err) {
  335. throw err;
  336. }
  337. //Allow getting a global that is expressed in
  338. //dot notation, like 'a.b.c'.
  339. function getGlobal(value) {
  340. if (!value) {
  341. return value;
  342. }
  343. var g = global;
  344. each(value.split('.'), function (part) {
  345. g = g[part];
  346. });
  347. return g;
  348. }
  349. /**
  350. * Constructs an error with a pointer to an URL with more information.
  351. * @param {String} id the error ID that maps to an ID on a web page.
  352. * @param {String} message human readable error.
  353. * @param {Error} [err] the original error, if there is one.
  354. *
  355. * @returns {Error}
  356. */
  357. function makeError(id, msg, err, requireModules) {
  358. var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html#' + id);
  359. e.requireType = id;
  360. e.requireModules = requireModules;
  361. if (err) {
  362. e.originalError = err;
  363. }
  364. return e;
  365. }
  366. if (typeof define !== 'undefined') {
  367. //If a define is already in play via another AMD loader,
  368. //do not overwrite.
  369. return;
  370. }
  371. if (typeof requirejs !== 'undefined') {
  372. if (isFunction(requirejs)) {
  373. //Do not overwrite an existing requirejs instance.
  374. return;
  375. }
  376. cfg = requirejs;
  377. requirejs = undefined;
  378. }
  379. //Allow for a require config object
  380. if (typeof require !== 'undefined' && !isFunction(require)) {
  381. //assume it is a config object.
  382. cfg = require;
  383. require = undefined;
  384. }
  385. function newContext(contextName) {
  386. var inCheckLoaded, Module, context, handlers,
  387. checkLoadedTimeoutId,
  388. config = {
  389. //Defaults. Do not set a default for map
  390. //config to speed up normalize(), which
  391. //will run faster if there is no default.
  392. waitSeconds: 7,
  393. baseUrl: './',
  394. paths: {},
  395. bundles: {},
  396. pkgs: {},
  397. shim: {},
  398. config: {}
  399. },
  400. registry = {},
  401. //registry of just enabled modules, to speed
  402. //cycle breaking code when lots of modules
  403. //are registered, but not activated.
  404. enabledRegistry = {},
  405. undefEvents = {},
  406. defQueue = [],
  407. defined = {},
  408. urlFetched = {},
  409. bundlesMap = {},
  410. requireCounter = 1,
  411. unnormalizedCounter = 1;
  412. /**
  413. * Trims the . and .. from an array of path segments.
  414. * It will keep a leading path segment if a .. will become
  415. * the first path segment, to help with module name lookups,
  416. * which act like paths, but can be remapped. But the end result,
  417. * all paths that use this function should look normalized.
  418. * NOTE: this method MODIFIES the input array.
  419. * @param {Array} ary the array of path segments.
  420. */
  421. function trimDots(ary) {
  422. var i, part;
  423. for (i = 0; i < ary.length; i++) {
  424. part = ary[i];
  425. if (part === '.') {
  426. ary.splice(i, 1);
  427. i -= 1;
  428. } else if (part === '..') {
  429. // If at the start, or previous value is still ..,
  430. // keep them so that when converted to a path it may
  431. // still work when converted to a path, even though
  432. // as an ID it is less than ideal. In larger point
  433. // releases, may be better to just kick out an error.
  434. if (i === 0 || (i === 1 && ary[2] === '..') || ary[i - 1] === '..') {
  435. continue;
  436. } else if (i > 0) {
  437. ary.splice(i - 1, 2);
  438. i -= 2;
  439. }
  440. }
  441. }
  442. }
  443. /**
  444. * Given a relative module name, like ./something, normalize it to
  445. * a real name that can be mapped to a path.
  446. * @param {String} name the relative name
  447. * @param {String} baseName a real name that the name arg is relative
  448. * to.
  449. * @param {Boolean} applyMap apply the map config to the value. Should
  450. * only be done if this normalization is for a dependency ID.
  451. * @returns {String} normalized name
  452. */
  453. function normalize(name, baseName, applyMap) {
  454. var pkgMain, mapValue, nameParts, i, j, nameSegment, lastIndex,
  455. foundMap, foundI, foundStarMap, starI, normalizedBaseParts,
  456. baseParts = (baseName && baseName.split('/')),
  457. map = config.map,
  458. starMap = map && map['*'];
  459. //Adjust any relative paths.
  460. if (name) {
  461. name = name.split('/');
  462. lastIndex = name.length - 1;
  463. // If wanting node ID compatibility, strip .js from end
  464. // of IDs. Have to do this here, and not in nameToUrl
  465. // because node allows either .js or non .js to map
  466. // to same file.
  467. if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) {
  468. name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, '');
  469. }
  470. // Starts with a '.' so need the baseName
  471. if (name[0].charAt(0) === '.' && baseParts) {
  472. //Convert baseName to array, and lop off the last part,
  473. //so that . matches that 'directory' and not name of the baseName's
  474. //module. For instance, baseName of 'one/two/three', maps to
  475. //'one/two/three.js', but we want the directory, 'one/two' for
  476. //this normalization.
  477. normalizedBaseParts = baseParts.slice(0, baseParts.length - 1);
  478. name = normalizedBaseParts.concat(name);
  479. }
  480. trimDots(name);
  481. name = name.join('/');
  482. }
  483. //Apply map config if available.
  484. if (applyMap && map && (baseParts || starMap)) {
  485. nameParts = name.split('/');
  486. outerLoop: for (i = nameParts.length; i > 0; i -= 1) {
  487. nameSegment = nameParts.slice(0, i).join('/');
  488. if (baseParts) {
  489. //Find the longest baseName segment match in the config.
  490. //So, do joins on the biggest to smallest lengths of baseParts.
  491. for (j = baseParts.length; j > 0; j -= 1) {
  492. mapValue = getOwn(map, baseParts.slice(0, j).join('/'));
  493. //baseName segment has config, find if it has one for
  494. //this name.
  495. if (mapValue) {
  496. mapValue = getOwn(mapValue, nameSegment);
  497. if (mapValue) {
  498. //Match, update name to the new value.
  499. foundMap = mapValue;
  500. foundI = i;
  501. break outerLoop;
  502. }
  503. }
  504. }
  505. }
  506. //Check for a star map match, but just hold on to it,
  507. //if there is a shorter segment match later in a matching
  508. //config, then favor over this star map.
  509. if (!foundStarMap && starMap && getOwn(starMap, nameSegment)) {
  510. foundStarMap = getOwn(starMap, nameSegment);
  511. starI = i;
  512. }
  513. }
  514. if (!foundMap && foundStarMap) {
  515. foundMap = foundStarMap;
  516. foundI = starI;
  517. }
  518. if (foundMap) {
  519. nameParts.splice(0, foundI, foundMap);
  520. name = nameParts.join('/');
  521. }
  522. }
  523. // If the name points to a package's name, use
  524. // the package main instead.
  525. pkgMain = getOwn(config.pkgs, name);
  526. return pkgMain ? pkgMain : name;
  527. }
  528. function removeScript(name) {
  529. if (isBrowser) {
  530. each(scripts(), function (scriptNode) {
  531. if (scriptNode.getAttribute('data-requiremodule') === name &&
  532. scriptNode.getAttribute('data-requirecontext') === context.contextName) {
  533. scriptNode.parentNode.removeChild(scriptNode);
  534. return true;
  535. }
  536. });
  537. }
  538. }
  539. function hasPathFallback(id) {
  540. var pathConfig = getOwn(config.paths, id);
  541. if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) {
  542. //Pop off the first array value, since it failed, and
  543. //retry
  544. pathConfig.shift();
  545. context.require.undef(id);
  546. //Custom require that does not do map translation, since
  547. //ID is "absolute", already mapped/resolved.
  548. context.makeRequire(null, {
  549. skipMap: true
  550. })([id]);
  551. return true;
  552. }
  553. }
  554. //Turns a plugin!resource to [plugin, resource]
  555. //with the plugin being undefined if the name
  556. //did not have a plugin prefix.
  557. function splitPrefix(name) {
  558. var prefix,
  559. index = name ? name.indexOf('!') : -1;
  560. if (index > -1) {
  561. prefix = name.substring(0, index);
  562. name = name.substring(index + 1, name.length);
  563. }
  564. return [prefix, name];
  565. }
  566. /**
  567. * Creates a module mapping that includes plugin prefix, module
  568. * name, and path. If parentModuleMap is provided it will
  569. * also normalize the name via require.normalize()
  570. *
  571. * @param {String} name the module name
  572. * @param {String} [parentModuleMap] parent module map
  573. * for the module name, used to resolve relative names.
  574. * @param {Boolean} isNormalized: is the ID already normalized.
  575. * This is true if this call is done for a define() module ID.
  576. * @param {Boolean} applyMap: apply the map config to the ID.
  577. * Should only be true if this map is for a dependency.
  578. *
  579. * @returns {Object}
  580. */
  581. function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) {
  582. var url, pluginModule, suffix, nameParts,
  583. prefix = null,
  584. parentName = parentModuleMap ? parentModuleMap.name : null,
  585. originalName = name,
  586. isDefine = true,
  587. normalizedName = '';
  588. //If no name, then it means it is a require call, generate an
  589. //internal name.
  590. if (!name) {
  591. isDefine = false;
  592. name = '_@r' + (requireCounter += 1);
  593. }
  594. nameParts = splitPrefix(name);
  595. prefix = nameParts[0];
  596. name = nameParts[1];
  597. if (prefix) {
  598. prefix = normalize(prefix, parentName, applyMap);
  599. pluginModule = getOwn(defined, prefix);
  600. }
  601. //Account for relative paths if there is a base name.
  602. if (name) {
  603. if (prefix) {
  604. if (isNormalized) {
  605. normalizedName = name;
  606. } else if (pluginModule && pluginModule.normalize) {
  607. //Plugin is loaded, use its normalize method.
  608. normalizedName = pluginModule.normalize(name, function (name) {
  609. return normalize(name, parentName, applyMap);
  610. });
  611. } else {
  612. // If nested plugin references, then do not try to
  613. // normalize, as it will not normalize correctly. This
  614. // places a restriction on resourceIds, and the longer
  615. // term solution is not to normalize until plugins are
  616. // loaded and all normalizations to allow for async
  617. // loading of a loader plugin. But for now, fixes the
  618. // common uses. Details in #1131
  619. normalizedName = name.indexOf('!') === -1 ?
  620. normalize(name, parentName, applyMap) :
  621. name;
  622. }
  623. } else {
  624. //A regular module.
  625. normalizedName = normalize(name, parentName, applyMap);
  626. //Normalized name may be a plugin ID due to map config
  627. //application in normalize. The map config values must
  628. //already be normalized, so do not need to redo that part.
  629. nameParts = splitPrefix(normalizedName);
  630. prefix = nameParts[0];
  631. normalizedName = nameParts[1];
  632. isNormalized = true;
  633. url = context.nameToUrl(normalizedName);
  634. }
  635. }
  636. //If the id is a plugin id that cannot be determined if it needs
  637. //normalization, stamp it with a unique ID so two matching relative
  638. //ids that may conflict can be separate.
  639. suffix = prefix && !pluginModule && !isNormalized ?
  640. '_unnormalized' + (unnormalizedCounter += 1) :
  641. '';
  642. return {
  643. prefix: prefix,
  644. name: normalizedName,
  645. parentMap: parentModuleMap,
  646. unnormalized: !!suffix,
  647. url: url,
  648. originalName: originalName,
  649. isDefine: isDefine,
  650. id: (prefix ?
  651. prefix + '!' + normalizedName :
  652. normalizedName) + suffix
  653. };
  654. }
  655. function getModule(depMap) {
  656. var id = depMap.id,
  657. mod = getOwn(registry, id);
  658. if (!mod) {
  659. mod = registry[id] = new context.Module(depMap);
  660. }
  661. return mod;
  662. }
  663. function on(depMap, name, fn) {
  664. var id = depMap.id,
  665. mod = getOwn(registry, id);
  666. if (hasProp(defined, id) &&
  667. (!mod || mod.defineEmitComplete)) {
  668. if (name === 'defined') {
  669. fn(defined[id]);
  670. }
  671. } else {
  672. mod = getModule(depMap);
  673. if (mod.error && name === 'error') {
  674. fn(mod.error);
  675. } else {
  676. mod.on(name, fn);
  677. }
  678. }
  679. }
  680. function onError(err, errback) {
  681. var ids = err.requireModules,
  682. notified = false;
  683. if (errback) {
  684. errback(err);
  685. } else {
  686. each(ids, function (id) {
  687. var mod = getOwn(registry, id);
  688. if (mod) {
  689. //Set error on module, so it skips timeout checks.
  690. mod.error = err;
  691. if (mod.events.error) {
  692. notified = true;
  693. mod.emit('error', err);
  694. }
  695. }
  696. });
  697. if (!notified) {
  698. req.onError(err);
  699. }
  700. }
  701. }
  702. /**
  703. * Internal method to transfer globalQueue items to this context's
  704. * defQueue.
  705. */
  706. function takeGlobalQueue() {
  707. //Push all the globalDefQueue items into the context's defQueue
  708. if (globalDefQueue.length) {
  709. each(globalDefQueue, function(queueItem) {
  710. var id = queueItem[0];
  711. if (typeof id === 'string') {
  712. context.defQueueMap[id] = true;
  713. }
  714. defQueue.push(queueItem);
  715. });
  716. globalDefQueue = [];
  717. }
  718. }
  719. handlers = {
  720. 'require': function (mod) {
  721. if (mod.require) {
  722. return mod.require;
  723. } else {
  724. return (mod.require = context.makeRequire(mod.map));
  725. }
  726. },
  727. 'exports': function (mod) {
  728. mod.usingExports = true;
  729. if (mod.map.isDefine) {
  730. if (mod.exports) {
  731. return (defined[mod.map.id] = mod.exports);
  732. } else {
  733. return (mod.exports = defined[mod.map.id] = {});
  734. }
  735. }
  736. },
  737. 'module': function (mod) {
  738. if (mod.module) {
  739. return mod.module;
  740. } else {
  741. return (mod.module = {
  742. id: mod.map.id,
  743. uri: mod.map.url,
  744. config: function () {
  745. return getOwn(config.config, mod.map.id) || {};
  746. },
  747. exports: mod.exports || (mod.exports = {})
  748. });
  749. }
  750. }
  751. };
  752. function cleanRegistry(id) {
  753. //Clean up machinery used for waiting modules.
  754. delete registry[id];
  755. delete enabledRegistry[id];
  756. }
  757. function breakCycle(mod, traced, processed) {
  758. var id = mod.map.id;
  759. if (mod.error) {
  760. mod.emit('error', mod.error);
  761. } else {
  762. traced[id] = true;
  763. each(mod.depMaps, function (depMap, i) {
  764. var depId = depMap.id,
  765. dep = getOwn(registry, depId);
  766. //Only force things that have not completed
  767. //being defined, so still in the registry,
  768. //and only if it has not been matched up
  769. //in the module already.
  770. if (dep && !mod.depMatched[i] && !processed[depId]) {
  771. if (getOwn(traced, depId)) {
  772. mod.defineDep(i, defined[depId]);
  773. mod.check(); //pass false?
  774. } else {
  775. breakCycle(dep, traced, processed);
  776. }
  777. }
  778. });
  779. processed[id] = true;
  780. }
  781. }
  782. function checkLoaded() {
  783. var err, usingPathFallback,
  784. waitInterval = config.waitSeconds * 1000,
  785. //It is possible to disable the wait interval by using waitSeconds of 0.
  786. expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(),
  787. noLoads = [],
  788. reqCalls = [],
  789. stillLoading = false,
  790. needCycleCheck = true;
  791. //Do not bother if this call was a result of a cycle break.
  792. if (inCheckLoaded) {
  793. return;
  794. }
  795. inCheckLoaded = true;
  796. //Figure out the state of all the modules.
  797. eachProp(enabledRegistry, function (mod) {
  798. var map = mod.map,
  799. modId = map.id;
  800. //Skip things that are not enabled or in error state.
  801. if (!mod.enabled) {
  802. return;
  803. }
  804. if (!map.isDefine) {
  805. reqCalls.push(mod);
  806. }
  807. if (!mod.error) {
  808. //If the module should be executed, and it has not
  809. //been inited and time is up, remember it.
  810. if (!mod.inited && expired) {
  811. if (hasPathFallback(modId)) {
  812. usingPathFallback = true;
  813. stillLoading = true;
  814. } else {
  815. noLoads.push(modId);
  816. removeScript(modId);
  817. }
  818. } else if (!mod.inited && mod.fetched && map.isDefine) {
  819. stillLoading = true;
  820. if (!map.prefix) {
  821. //No reason to keep looking for unfinished
  822. //loading. If the only stillLoading is a
  823. //plugin resource though, keep going,
  824. //because it may be that a plugin resource
  825. //is waiting on a non-plugin cycle.
  826. return (needCycleCheck = false);
  827. }
  828. }
  829. }
  830. });
  831. if (expired && noLoads.length) {
  832. //If wait time expired, throw error of unloaded modules.
  833. err = makeError('timeout', 'Load timeout for modules: ' + noLoads, null, noLoads);
  834. err.contextName = context.contextName;
  835. return onError(err);
  836. }
  837. //Not expired, check for a cycle.
  838. if (needCycleCheck) {
  839. each(reqCalls, function (mod) {
  840. breakCycle(mod, {}, {});
  841. });
  842. }
  843. //If still waiting on loads, and the waiting load is something
  844. //other than a plugin resource, or there are still outstanding
  845. //scripts, then just try back later.
  846. if ((!expired || usingPathFallback) && stillLoading) {
  847. //Something is still waiting to load. Wait for it, but only
  848. //if a timeout is not already in effect.
  849. if ((isBrowser || isWebWorker) && !checkLoadedTimeoutId) {
  850. checkLoadedTimeoutId = setTimeout(function () {
  851. checkLoadedTimeoutId = 0;
  852. checkLoaded();
  853. }, 50);
  854. }
  855. }
  856. inCheckLoaded = false;
  857. }
  858. Module = function (map) {
  859. this.events = getOwn(undefEvents, map.id) || {};
  860. this.map = map;
  861. this.shim = getOwn(config.shim, map.id);
  862. this.depExports = [];
  863. this.depMaps = [];
  864. this.depMatched = [];
  865. this.pluginMaps = {};
  866. this.depCount = 0;
  867. /* this.exports this.factory
  868. this.depMaps = [],
  869. this.enabled, this.fetched
  870. */
  871. };
  872. Module.prototype = {
  873. init: function (depMaps, factory, errback, options) {
  874. options = options || {};
  875. //Do not do more inits if already done. Can happen if there
  876. //are multiple define calls for the same module. That is not
  877. //a normal, common case, but it is also not unexpected.
  878. if (this.inited) {
  879. return;
  880. }
  881. this.factory = factory;
  882. if (errback) {
  883. //Register for errors on this module.
  884. this.on('error', errback);
  885. } else if (this.events.error) {
  886. //If no errback already, but there are error listeners
  887. //on this module, set up an errback to pass to the deps.
  888. errback = bind(this, function (err) {
  889. this.emit('error', err);
  890. });
  891. }
  892. //Do a copy of the dependency array, so that
  893. //source inputs are not modified. For example
  894. //"shim" deps are passed in here directly, and
  895. //doing a direct modification of the depMaps array
  896. //would affect that config.
  897. this.depMaps = depMaps && depMaps.slice(0);
  898. this.errback = errback;
  899. //Indicate this module has be initialized
  900. this.inited = true;
  901. this.ignore = options.ignore;
  902. //Could have option to init this module in enabled mode,
  903. //or could have been previously marked as enabled. However,
  904. //the dependencies are not known until init is called. So
  905. //if enabled previously, now trigger dependencies as enabled.
  906. if (options.enabled || this.enabled) {
  907. //Enable this module and dependencies.
  908. //Will call this.check()
  909. this.enable();
  910. } else {
  911. this.check();
  912. }
  913. },
  914. defineDep: function (i, depExports) {
  915. //Because of cycles, defined callback for a given
  916. //export can be called more than once.
  917. if (!this.depMatched[i]) {
  918. this.depMatched[i] = true;
  919. this.depCount -= 1;
  920. this.depExports[i] = depExports;
  921. }
  922. },
  923. fetch: function () {
  924. if (this.fetched) {
  925. return;
  926. }
  927. this.fetched = true;
  928. context.startTime = (new Date()).getTime();
  929. var map = this.map;
  930. //If the manager is for a plugin managed resource,
  931. //ask the plugin to load it now.
  932. if (this.shim) {
  933. context.makeRequire(this.map, {
  934. enableBuildCallback: true
  935. })(this.shim.deps || [], bind(this, function () {
  936. return map.prefix ? this.callPlugin() : this.load();
  937. }));
  938. } else {
  939. //Regular dependency.
  940. return map.prefix ? this.callPlugin() : this.load();
  941. }
  942. },
  943. load: function () {
  944. var url = this.map.url;
  945. //Regular dependency.
  946. if (!urlFetched[url]) {
  947. urlFetched[url] = true;
  948. context.load(this.map.id, url);
  949. }
  950. },
  951. /**
  952. * Checks if the module is ready to define itself, and if so,
  953. * define it.
  954. */
  955. check: function () {
  956. if (!this.enabled || this.enabling) {
  957. return;
  958. }
  959. var err, cjsModule,
  960. id = this.map.id,
  961. depExports = this.depExports,
  962. exports = this.exports,
  963. factory = this.factory;
  964. if (!this.inited) {
  965. // Only fetch if not already in the defQueue.
  966. if (!hasProp(context.defQueueMap, id)) {
  967. this.fetch();
  968. }
  969. } else if (this.error) {
  970. this.emit('error', this.error);
  971. } else if (!this.defining) {
  972. //The factory could trigger another require call
  973. //that would result in checking this module to
  974. //define itself again. If already in the process
  975. //of doing that, skip this work.
  976. this.defining = true;
  977. if (this.depCount < 1 && !this.defined) {
  978. if (isFunction(factory)) {
  979. //If there is an error listener, favor passing
  980. //to that instead of throwing an error. However,
  981. //only do it for define()'d modules. require
  982. //errbacks should not be called for failures in
  983. //their callbacks (#699). However if a global
  984. //onError is set, use that.
  985. if ((this.events.error && this.map.isDefine) ||
  986. req.onError !== defaultOnError) {
  987. try {
  988. exports = context.execCb(id, factory, depExports, exports);
  989. } catch (e) {
  990. err = e;
  991. }
  992. } else {
  993. exports = context.execCb(id, factory, depExports, exports);
  994. }
  995. // Favor return value over exports. If node/cjs in play,
  996. // then will not have a return value anyway. Favor
  997. // module.exports assignment over exports object.
  998. if (this.map.isDefine && exports === undefined) {
  999. cjsModule = this.module;
  1000. if (cjsModule) {
  1001. exports = cjsModule.exports;
  1002. } else if (this.usingExports) {
  1003. //exports already set the defined value.
  1004. exports = this.exports;
  1005. }
  1006. }
  1007. if (err) {
  1008. err.requireMap = this.map;
  1009. err.requireModules = this.map.isDefine ? [this.map.id] : null;
  1010. err.requireType = this.map.isDefine ? 'define' : 'require';
  1011. return onError((this.error = err));
  1012. }
  1013. } else {
  1014. //Just a literal value
  1015. exports = factory;
  1016. }
  1017. this.exports = exports;
  1018. if (this.map.isDefine && !this.ignore) {
  1019. defined[id] = exports;
  1020. if (req.onResourceLoad) {
  1021. var resLoadMaps = [];
  1022. each(this.depMaps, function (depMap) {
  1023. resLoadMaps.push(depMap.normalizedMap || depMap);
  1024. });
  1025. req.onResourceLoad(context, this.map, resLoadMaps);
  1026. }
  1027. }
  1028. //Clean up
  1029. cleanRegistry(id);
  1030. this.defined = true;
  1031. }
  1032. //Finished the define stage. Allow calling check again
  1033. //to allow define notifications below in the case of a
  1034. //cycle.
  1035. this.defining = false;
  1036. if (this.defined && !this.defineEmitted) {
  1037. this.defineEmitted = true;
  1038. this.emit('defined', this.exports);
  1039. this.defineEmitComplete = true;
  1040. }
  1041. }
  1042. },
  1043. callPlugin: function () {
  1044. var map = this.map,
  1045. id = map.id,
  1046. //Map already normalized the prefix.
  1047. pluginMap = makeModuleMap(map.prefix);
  1048. //Mark this as a dependency for this plugin, so it
  1049. //can be traced for cycles.
  1050. this.depMaps.push(pluginMap);
  1051. on(pluginMap, 'defined', bind(this, function (plugin) {
  1052. var load, normalizedMap, normalizedMod,
  1053. bundleId = getOwn(bundlesMap, this.map.id),
  1054. name = this.map.name,
  1055. parentName = this.map.parentMap ? this.map.parentMap.name : null,
  1056. localRequire = context.makeRequire(map.parentMap, {
  1057. enableBuildCallback: true
  1058. });
  1059. //If current map is not normalized, wait for that
  1060. //normalized name to load instead of continuing.
  1061. if (this.map.unnormalized) {
  1062. //Normalize the ID if the plugin allows it.
  1063. if (plugin.normalize) {
  1064. name = plugin.normalize(name, function (name) {
  1065. return normalize(name, parentName, true);
  1066. }) || '';
  1067. }
  1068. //prefix and name should already be normalized, no need
  1069. //for applying map config again either.
  1070. normalizedMap = makeModuleMap(map.prefix + '!' + name,
  1071. this.map.parentMap,
  1072. true);
  1073. on(normalizedMap,
  1074. 'defined', bind(this, function (value) {
  1075. this.map.normalizedMap = normalizedMap;
  1076. this.init([], function () { return value; }, null, {
  1077. enabled: true,
  1078. ignore: true
  1079. });
  1080. }));
  1081. normalizedMod = getOwn(registry, normalizedMap.id);
  1082. if (normalizedMod) {
  1083. //Mark this as a dependency for this plugin, so it
  1084. //can be traced for cycles.
  1085. this.depMaps.push(normalizedMap);
  1086. if (this.events.error) {
  1087. normalizedMod.on('error', bind(this, function (err) {
  1088. this.emit('error', err);
  1089. }));
  1090. }
  1091. normalizedMod.enable();
  1092. }
  1093. return;
  1094. }
  1095. //If a paths config, then just load that file instead to
  1096. //resolve the plugin, as it is built into that paths layer.
  1097. if (bundleId) {
  1098. this.map.url = context.nameToUrl(bundleId);
  1099. this.load();
  1100. return;
  1101. }
  1102. load = bind(this, function (value) {
  1103. this.init([], function () { return value; }, null, {
  1104. enabled: true
  1105. });
  1106. });
  1107. load.error = bind(this, function (err) {
  1108. this.inited = true;
  1109. this.error = err;
  1110. err.requireModules = [id];
  1111. //Remove temp unnormalized modules for this module,
  1112. //since they will never be resolved otherwise now.
  1113. eachProp(registry, function (mod) {
  1114. if (mod.map.id.indexOf(id + '_unnormalized') === 0) {
  1115. cleanRegistry(mod.map.id);
  1116. }
  1117. });
  1118. onError(err);
  1119. });
  1120. //Allow plugins to load other code without having to know the
  1121. //context or how to 'complete' the load.
  1122. load.fromText = bind(this, function (text, textAlt) {
  1123. /*jslint evil: true */
  1124. var moduleName = map.name,
  1125. moduleMap = makeModuleMap(moduleName),
  1126. hasInteractive = useInteractive;
  1127. //As of 2.1.0, support just passing the text, to reinforce
  1128. //fromText only being called once per resource. Still
  1129. //support old style of passing moduleName but discard
  1130. //that moduleName in favor of the internal ref.
  1131. if (textAlt) {
  1132. text = textAlt;
  1133. }
  1134. //Turn off interactive script matching for IE for any define
  1135. //calls in the text, then turn it back on at the end.
  1136. if (hasInteractive) {
  1137. useInteractive = false;
  1138. }
  1139. //Prime the system by creating a module instance for
  1140. //it.
  1141. getModule(moduleMap);
  1142. //Transfer any config to this other module.
  1143. if (hasProp(config.config, id)) {
  1144. config.config[moduleName] = config.config[id];
  1145. }
  1146. try {
  1147. req.exec(text);
  1148. } catch (e) {
  1149. return onError(makeError('fromtexteval',
  1150. 'fromText eval for ' + id +
  1151. ' failed: ' + e,
  1152. e,
  1153. [id]));
  1154. }
  1155. if (hasInteractive) {
  1156. useInteractive = true;
  1157. }
  1158. //Mark this as a dependency for the plugin
  1159. //resource
  1160. this.depMaps.push(moduleMap);
  1161. //Support anonymous modules.
  1162. context.completeLoad(moduleName);
  1163. //Bind the value of that module to the value for this
  1164. //resource ID.
  1165. localRequire([moduleName], load);
  1166. });
  1167. //Use parentName here since the plugin's name is not reliable,
  1168. //could be some weird string with no path that actually wants to
  1169. //reference the parentName's path.
  1170. plugin.load(map.name, localRequire, load, config);
  1171. }));
  1172. context.enable(pluginMap, this);
  1173. this.pluginMaps[pluginMap.id] = pluginMap;
  1174. },
  1175. enable: function () {
  1176. enabledRegistry[this.map.id] = this;
  1177. this.enabled = true;
  1178. //Set flag mentioning that the module is enabling,
  1179. //so that immediate calls to the defined callbacks
  1180. //for dependencies do not trigger inadvertent load
  1181. //with the depCount still being zero.
  1182. this.enabling = true;
  1183. //Enable each dependency
  1184. each(this.depMaps, bind(this, function (depMap, i) {
  1185. var id, mod, handler;
  1186. if (typeof depMap === 'string') {
  1187. //Dependency needs to be converted to a depMap
  1188. //and wired up to this module.
  1189. depMap = makeModuleMap(depMap,
  1190. (this.map.isDefine ? this.map : this.map.parentMap),
  1191. false,
  1192. !this.skipMap);
  1193. this.depMaps[i] = depMap;
  1194. handler = getOwn(handlers, depMap.id);
  1195. if (handler) {
  1196. this.depExports[i] = handler(this);
  1197. return;
  1198. }
  1199. this.depCount += 1;
  1200. on(depMap, 'defined', bind(this, function (depExports) {
  1201. if (this.undefed) {
  1202. return;
  1203. }
  1204. this.defineDep(i, depExports);
  1205. this.check();
  1206. }));
  1207. if (this.errback) {
  1208. on(depMap, 'error', bind(this, this.errback));
  1209. } else if (this.events.error) {
  1210. // No direct errback on this module, but something
  1211. // else is listening for errors, so be sure to
  1212. // propagate the error correctly.
  1213. on(depMap, 'error', bind(this, function(err) {
  1214. this.emit('error', err);
  1215. }));
  1216. }
  1217. }
  1218. id = depMap.id;
  1219. mod = registry[id];
  1220. //Skip special modules like 'require', 'exports', 'module'
  1221. //Also, don't call enable if it is already enabled,
  1222. //important in circular dependency cases.
  1223. if (!hasProp(handlers, id) && mod && !mod.enabled) {
  1224. context.enable(depMap, this);
  1225. }
  1226. }));
  1227. //Enable each plugin that is used in
  1228. //a dependency
  1229. eachProp(this.pluginMaps, bind(this, function (pluginMap) {
  1230. var mod = getOwn(registry, pluginMap.id);
  1231. if (mod && !mod.enabled) {
  1232. context.enable(pluginMap, this);
  1233. }
  1234. }));
  1235. this.enabling = false;
  1236. this.check();
  1237. },
  1238. on: function (name, cb) {
  1239. var cbs = this.events[name];
  1240. if (!cbs) {
  1241. cbs = this.events[name] = [];
  1242. }
  1243. cbs.push(cb);
  1244. },
  1245. emit: function (name, evt) {
  1246. each(this.events[name], function (cb) {
  1247. cb(evt);
  1248. });
  1249. if (name === 'error') {
  1250. //Now that the error handler was triggered, remove
  1251. //the listeners, since this broken Module instance
  1252. //can stay around for a while in the registry.
  1253. delete this.events[name];
  1254. }
  1255. }
  1256. };
  1257. function callGetModule(args) {
  1258. //Skip modules already defined.
  1259. if (!hasProp(defined, args[0])) {
  1260. getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2]);
  1261. }
  1262. }
  1263. function removeListener(node, func, name, ieName) {
  1264. //Favor detachEvent because of IE9
  1265. //issue, see attachEvent/addEventListener comment elsewhere
  1266. //in this file.
  1267. if (node.detachEvent && !isOpera) {
  1268. //Probably IE. If not it will throw an error, which will be
  1269. //useful to know.
  1270. if (ieName) {
  1271. node.detachEvent(ieName, func);
  1272. }
  1273. } else {
  1274. node.removeEventListener(name, func, false);
  1275. }
  1276. }
  1277. /**
  1278. * Given an event from a script node, get the requirejs info from it,
  1279. * and then removes the event listeners on the node.
  1280. * @param {Event} evt
  1281. * @returns {Object}
  1282. */
  1283. function getScriptData(evt) {
  1284. //Using currentTarget instead of target for Firefox 2.0's sake. Not
  1285. //all old browsers will be supported, but this one was easy enough
  1286. //to support and still makes sense.
  1287. var node = evt.currentTarget || evt.srcElement;
  1288. //Remove the listeners once here.
  1289. removeListener(node, context.onScriptLoad, 'load', 'onreadystatechange');
  1290. removeListener(node, context.onScriptError, 'error');
  1291. return {
  1292. node: node,
  1293. id: node && node.getAttribute('data-requiremodule')
  1294. };
  1295. }
  1296. function intakeDefines() {
  1297. var args;
  1298. //Any defined modules in the global queue, intake them now.
  1299. takeGlobalQueue();
  1300. //Make sure any remaining defQueue items get properly processed.
  1301. while (defQueue.length) {
  1302. args = defQueue.shift();
  1303. if (args[0] === null) {
  1304. return onError(makeError('mismatch', 'Mismatched anonymous define() module: ' +
  1305. args[args.length - 1]));
  1306. } else {
  1307. //args are id, deps, factory. Should be normalized by the
  1308. //define() function.
  1309. callGetModule(args);
  1310. }
  1311. }
  1312. context.defQueueMap = {};
  1313. }
  1314. context = {
  1315. config: config,
  1316. contextName: contextName,
  1317. registry: registry,
  1318. defined: defined,
  1319. urlFetched: urlFetched,
  1320. defQueue: defQueue,
  1321. defQueueMap: {},
  1322. Module: Module,
  1323. makeModuleMap: makeModuleMap,
  1324. nextTick: req.nextTick,
  1325. onError: onError,
  1326. /**
  1327. * Set a configuration for the context.
  1328. * @param {Object} cfg config object to integrate.
  1329. */
  1330. configure: function (cfg) {
  1331. //Make sure the baseUrl ends in a slash.
  1332. if (cfg.baseUrl) {
  1333. if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') {
  1334. cfg.baseUrl += '/';
  1335. }
  1336. }
  1337. // Convert old style urlArgs string to a function.
  1338. if (typeof cfg.urlArgs === 'string') {
  1339. var urlArgs = cfg.urlArgs;
  1340. cfg.urlArgs = function(id, url) {
  1341. return (url.indexOf('?') === -1 ? '?' : '&') + urlArgs;
  1342. };
  1343. }
  1344. //Save off the paths since they require special processing,
  1345. //they are additive.
  1346. var shim = config.shim,
  1347. objs = {
  1348. paths: true,
  1349. bundles: true,
  1350. config: true,
  1351. map: true
  1352. };
  1353. eachProp(cfg, function (value, prop) {
  1354. if (objs[prop]) {
  1355. if (!config[prop]) {
  1356. config[prop] = {};
  1357. }
  1358. mixin(config[prop], value, true, true);
  1359. } else {
  1360. config[prop] = value;
  1361. }
  1362. });
  1363. //Reverse map the bundles
  1364. if (cfg.bundles) {
  1365. eachProp(cfg.bundles, function (value, prop) {
  1366. each(value, function (v) {
  1367. if (v !== prop) {
  1368. bundlesMap[v] = prop;
  1369. }
  1370. });
  1371. });
  1372. }
  1373. //Merge shim
  1374. if (cfg.shim) {
  1375. eachProp(cfg.shim, function (value, id) {
  1376. //Normalize the structure
  1377. if (isArray(value)) {
  1378. value = {
  1379. deps: value
  1380. };
  1381. }
  1382. if ((value.exports || value.init) && !value.exportsFn) {
  1383. value.exportsFn = context.makeShimExports(value);
  1384. }
  1385. shim[id] = value;
  1386. });
  1387. config.shim = shim;
  1388. }
  1389. //Adjust packages if necessary.
  1390. if (cfg.packages) {
  1391. each(cfg.packages, function (pkgObj) {
  1392. var location, name;
  1393. pkgObj = typeof pkgObj === 'string' ? {name: pkgObj} : pkgObj;
  1394. name = pkgObj.name;
  1395. location = pkgObj.location;
  1396. if (location) {
  1397. config.paths[name] = pkgObj.location;
  1398. }
  1399. //Save pointer to main module ID for pkg name.
  1400. //Remove leading dot in main, so main paths are normalized,
  1401. //and remove any trailing .js, since different package
  1402. //envs have different conventions: some use a module name,
  1403. //some use a file name.
  1404. config.pkgs[name] = pkgObj.name + '/' + (pkgObj.main || 'main')
  1405. .replace(currDirRegExp, '')
  1406. .replace(jsSuffixRegExp, '');
  1407. });
  1408. }
  1409. //If there are any "waiting to execute" modules in the registry,
  1410. //update the maps for them, since their info, like URLs to load,
  1411. //may have changed.
  1412. eachProp(registry, function (mod, id) {
  1413. //If module already has init called, since it is too
  1414. //late to modify them, and ignore unnormalized ones
  1415. //since they are transient.
  1416. if (!mod.inited && !mod.map.unnormalized) {
  1417. mod.map = makeModuleMap(id, null, true);
  1418. }
  1419. });
  1420. //If a deps array or a config callback is specified, then call
  1421. //require with those args. This is useful when require is defined as a
  1422. //config object before require.js is loaded.
  1423. if (cfg.deps || cfg.callback) {
  1424. context.require(cfg.deps || [], cfg.callback);
  1425. }
  1426. },
  1427. makeShimExports: function (value) {
  1428. function fn() {
  1429. var ret;
  1430. if (value.init) {
  1431. ret = value.init.apply(global, arguments);
  1432. }
  1433. return ret || (value.exports && getGlobal(value.exports));
  1434. }
  1435. return fn;
  1436. },
  1437. makeRequire: function (relMap, options) {
  1438. options = options || {};
  1439. function localRequire(deps, callback, errback) {
  1440. var id, map, requireMod;
  1441. if (options.enableBuildCallback && callback && isFunction(callback)) {
  1442. callback.__requireJsBuild = true;
  1443. }
  1444. if (typeof deps === 'string') {
  1445. if (isFunction(callback)) {
  1446. //Invalid call
  1447. return onError(makeError('requireargs', 'Invalid require call'), errback);
  1448. }
  1449. //If require|exports|module are requested, get the
  1450. //value for them from the special handlers. Caveat:
  1451. //this only works while module is being defined.
  1452. if (relMap && hasProp(handlers, deps)) {
  1453. return handlers[deps](registry[relMap.id]);
  1454. }
  1455. //Synchronous access to one module. If require.get is
  1456. //available (as in the Node adapter), prefer that.
  1457. if (req.get) {
  1458. return req.get(context, deps, relMap, localRequire);
  1459. }
  1460. //Normalize module name, if it contains . or ..
  1461. map = makeModuleMap(deps, relMap, false, true);
  1462. id = map.id;
  1463. if (!hasProp(defined, id)) {
  1464. return onError(makeError('notloaded', 'Module name "' +
  1465. id +
  1466. '" has not been loaded yet for context: ' +
  1467. contextName +
  1468. (relMap ? '' : '. Use require([])')));
  1469. }
  1470. return defined[id];
  1471. }
  1472. //Grab defines waiting in the global queue.
  1473. intakeDefines();
  1474. //Mark all the dependencies as needing to be loaded.
  1475. context.nextTick(function () {
  1476. //Some defines could have been added since the
  1477. //require call, collect them.
  1478. intakeDefines();
  1479. requireMod = getModule(makeModuleMap(null, relMap));
  1480. //Store if map config should be applied to this require
  1481. //call for dependencies.
  1482. requireMod.skipMap = options.skipMap;
  1483. requireMod.init(deps, callback, errback, {
  1484. enabled: true
  1485. });
  1486. checkLoaded();
  1487. });
  1488. return localRequire;
  1489. }
  1490. mixin(localRequire, {
  1491. isBrowser: isBrowser,
  1492. /**
  1493. * Converts a module name + .extension into an URL path.
  1494. * *Requires* the use of a module name. It does not support using
  1495. * plain URLs like nameToUrl.
  1496. */
  1497. toUrl: function (moduleNamePlusExt) {
  1498. var ext,
  1499. index = moduleNamePlusExt.lastIndexOf('.'),
  1500. segment = moduleNamePlusExt.split('/')[0],
  1501. isRelative = segment === '.' || segment === '..';
  1502. //Have a file extension alias, and it is not the
  1503. //dots from a relative path.
  1504. if (index !== -1 && (!isRelative || index > 1)) {
  1505. ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length);
  1506. moduleNamePlusExt = moduleNamePlusExt.substring(0, index);
  1507. }
  1508. return context.nameToUrl(normalize(moduleNamePlusExt,
  1509. relMap && relMap.id, true), ext, true);
  1510. },
  1511. defined: function (id) {
  1512. return hasProp(defined, makeModuleMap(id, relMap, false, true).id);
  1513. },
  1514. specified: function (id) {
  1515. id = makeModuleMap(id, relMap, false, true).id;
  1516. return hasProp(defined, id) || hasProp(registry, id);
  1517. }
  1518. });
  1519. //Only allow undef on top level require calls
  1520. if (!relMap) {
  1521. localRequire.undef = function (id) {
  1522. //Bind any waiting define() calls to this context,
  1523. //fix for #408
  1524. takeGlobalQueue();
  1525. var map = makeModuleMap(id, relMap, true),
  1526. mod = getOwn(registry, id);
  1527. mod.undefed = true;
  1528. removeScript(id);
  1529. delete defined[id];
  1530. delete urlFetched[map.url];
  1531. delete undefEvents[id];
  1532. //Clean queued defines too. Go backwards
  1533. //in array so that the splices do not
  1534. //mess up the iteration.
  1535. eachReverse(defQueue, function(args, i) {
  1536. if (args[0] === id) {
  1537. defQueue.splice(i, 1);
  1538. }
  1539. });
  1540. delete context.defQueueMap[id];
  1541. if (mod) {
  1542. //Hold on to listeners in case the
  1543. //module will be attempted to be reloaded
  1544. //using a different config.
  1545. if (mod.events.defined) {
  1546. undefEvents[id] = mod.events;
  1547. }
  1548. cleanRegistry(id);
  1549. }
  1550. };
  1551. }
  1552. return localRequire;
  1553. },
  1554. /**
  1555. * Called to enable a module if it is still in the registry
  1556. * awaiting enablement. A second arg, parent, the parent module,
  1557. * is passed in for context, when this method is overridden by
  1558. * the optimizer. Not shown here to keep code compact.
  1559. */
  1560. enable: function (depMap) {
  1561. var mod = getOwn(registry, depMap.id);
  1562. if (mod) {
  1563. getModule(depMap).enable();
  1564. }
  1565. },
  1566. /**
  1567. * Internal method used by environment adapters to complete a load event.
  1568. * A load event could be a script load or just a load pass from a synchronous
  1569. * load call.
  1570. * @param {String} moduleName the name of the module to potentially complete.
  1571. */
  1572. completeLoad: function (moduleName) {
  1573. var found, args, mod,
  1574. shim = getOwn(config.shim, moduleName) || {},
  1575. shExports = shim.exports;
  1576. takeGlobalQueue();
  1577. while (defQueue.length) {
  1578. args = defQueue.shift();
  1579. if (args[0] === null) {
  1580. args[0] = moduleName;
  1581. //If already found an anonymous module and bound it
  1582. //to this name, then this is some other anon module
  1583. //waiting for its completeLoad to fire.
  1584. if (found) {
  1585. break;
  1586. }
  1587. found = true;
  1588. } else if (args[0] === moduleName) {
  1589. //Found matching define call for this script!
  1590. found = true;
  1591. }
  1592. callGetModule(args);
  1593. }
  1594. context.defQueueMap = {};
  1595. //Do this after the cycle of callGetModule in case the result
  1596. //of those calls/init calls changes the registry.
  1597. mod = getOwn(registry, moduleName);
  1598. if (!found && !hasProp(defined, moduleName) && mod && !mod.inited) {
  1599. if (config.enforceDefine && (!shExports || !getGlobal(shExports))) {
  1600. if (hasPathFallback(moduleName)) {
  1601. return;
  1602. } else {
  1603. return onError(makeError('nodefine',
  1604. 'No define call for ' + moduleName,
  1605. null,
  1606. [moduleName]));
  1607. }
  1608. } else {
  1609. //A script that does not call define(), so just simulate
  1610. //the call for it.
  1611. callGetModule([moduleName, (shim.deps || []), shim.exportsFn]);
  1612. }
  1613. }
  1614. checkLoaded();
  1615. },
  1616. /**
  1617. * Converts a module name to a file path. Supports cases where
  1618. * moduleName may actually be just an URL.
  1619. * Note that it **does not** call normalize on the moduleName,
  1620. * it is assumed to have already been normalized. This is an
  1621. * internal API, not a public one. Use toUrl for the public API.
  1622. */
  1623. nameToUrl: function (moduleName, ext, skipExt) {
  1624. var paths, syms, i, parentModule, url,
  1625. parentPath, bundleId,
  1626. pkgMain = getOwn(config.pkgs, moduleName);
  1627. if (pkgMain) {
  1628. moduleName = pkgMain;
  1629. }
  1630. bundleId = getOwn(bundlesMap, moduleName);
  1631. if (bundleId) {
  1632. return context.nameToUrl(bundleId, ext, skipExt);
  1633. }
  1634. //If a colon is in the URL, it indicates a protocol is used and it is just
  1635. //an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?)
  1636. //or ends with .js, then assume the user meant to use an url and not a module id.
  1637. //The slash is important for protocol-less URLs as well as full paths.
  1638. if (req.jsExtRegExp.test(moduleName)) {
  1639. //Just a plain path, not module name lookup, so just return it.
  1640. //Add extension if it is included. This is a bit wonky, only non-.js things pass
  1641. //an extension, this method probably needs to be reworked.
  1642. url = moduleName + (ext || '');
  1643. } else {
  1644. //A module that needs to be converted to a path.
  1645. paths = config.paths;
  1646. syms = moduleName.split('/');
  1647. //For each module name segment, see if there is a path
  1648. //registered for it. Start with most specific name
  1649. //and work up from it.
  1650. for (i = syms.length; i > 0; i -= 1) {
  1651. parentModule = syms.slice(0, i).join('/');
  1652. parentPath = getOwn(paths, parentModule);
  1653. if (parentPath) {
  1654. //If an array, it means there are a few choices,
  1655. //Choose the one that is desired
  1656. if (isArray(parentPath)) {
  1657. parentPath = parentPath[0];
  1658. }
  1659. syms.splice(0, i, parentPath);
  1660. break;
  1661. }
  1662. }
  1663. //Join the path parts together, then figure out if baseUrl is needed.
  1664. url = syms.join('/');
  1665. url += (ext || (/^data\:|^blob\:|\?/.test(url) || skipExt ? '' : '.js'));
  1666. url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url;
  1667. }
  1668. return config.urlArgs && !/^blob\:/.test(url) ?
  1669. url + config.urlArgs(moduleName, url) : url;
  1670. },
  1671. //Delegates to req.load. Broken out as a separate function to
  1672. //allow overriding in the optimizer.
  1673. load: function (id, url) {
  1674. req.load(context, id, url);
  1675. },
  1676. /**
  1677. * Executes a module callback function. Broken out as a separate function
  1678. * solely to allow the build system to sequence the files in the built
  1679. * layer in the right sequence.
  1680. *
  1681. * @private
  1682. */
  1683. execCb: function (name, callback, args, exports) {
  1684. return callback.apply(exports, args);
  1685. },
  1686. /**
  1687. * callback for script loads, used to check status of loading.
  1688. *
  1689. * @param {Event} evt the event from the browser for the script
  1690. * that was loaded.
  1691. */
  1692. onScriptLoad: function (evt) {
  1693. //Using currentTarget instead of target for Firefox 2.0's sake. Not
  1694. //all old browsers will be supported, but this one was easy enough
  1695. //to support and still makes sense.
  1696. if (evt.type === 'load' ||
  1697. (readyRegExp.test((evt.currentTarget || evt.srcElement).readyState))) {
  1698. //Reset interactive script so a script node is not held onto for
  1699. //to long.
  1700. interactiveScript = null;
  1701. //Pull out the name of the module and the context.
  1702. var data = getScriptData(evt);
  1703. context.completeLoad(data.id);
  1704. }
  1705. },
  1706. /**
  1707. * Callback for script errors.
  1708. */
  1709. onScriptError: function (evt) {
  1710. var data = getScriptData(evt);
  1711. if (!hasPathFallback(data.id)) {
  1712. var parents = [];
  1713. eachProp(registry, function(value, key) {
  1714. if (key.indexOf('_@r') !== 0) {
  1715. each(value.depMaps, function(depMap) {
  1716. if (depMap.id === data.id) {
  1717. parents.push(key);
  1718. return true;
  1719. }
  1720. });
  1721. }
  1722. });
  1723. return onError(makeError('scripterror', 'Script error for "' + data.id +
  1724. (parents.length ?
  1725. '", needed by: ' + parents.join(', ') :
  1726. '"'), evt, [data.id]));
  1727. }
  1728. }
  1729. };
  1730. context.require = context.makeRequire();
  1731. return context;
  1732. }
  1733. /**
  1734. * Main entry point.
  1735. *
  1736. * If the only argument to require is a string, then the module that
  1737. * is represented by that string is fetched for the appropriate context.
  1738. *
  1739. * If the first argument is an array, then it will be treated as an array
  1740. * of dependency string names to fetch. An optional function callback can
  1741. * be specified to execute when all of those dependencies are available.
  1742. *
  1743. * Make a local req variable to help Caja compliance (it assumes things
  1744. * on a require that are not standardized), and to give a short
  1745. * name for minification/local scope use.
  1746. */
  1747. req = requirejs = function (deps, callback, errback, optional) {
  1748. //Find the right context, use default
  1749. var context, config,
  1750. contextName = defContextName;
  1751. // Determine if have config object in the call.
  1752. if (!isArray(deps) && typeof deps !== 'string') {
  1753. // deps is a config object
  1754. config = deps;
  1755. if (isArray(callback)) {
  1756. // Adjust args if there are dependencies
  1757. deps = callback;
  1758. callback = errback;
  1759. errback = optional;
  1760. } else {
  1761. deps = [];
  1762. }
  1763. }
  1764. if (config && config.context) {
  1765. contextName = config.context;
  1766. }
  1767. context = getOwn(contexts, contextName);
  1768. if (!context) {
  1769. context = contexts[contextName] = req.s.newContext(contextName);
  1770. }
  1771. if (config) {
  1772. context.configure(config);
  1773. }
  1774. return context.require(deps, callback, errback);
  1775. };
  1776. /**
  1777. * Support require.config() to make it easier to cooperate with other
  1778. * AMD loaders on globally agreed names.
  1779. */
  1780. req.config = function (config) {
  1781. return req(config);
  1782. };
  1783. /**
  1784. * Execute something after the current tick
  1785. * of the event loop. Override for other envs
  1786. * that have a better solution than setTimeout.
  1787. * @param {Function} fn function to execute later.
  1788. */
  1789. req.nextTick = typeof setTimeout !== 'undefined' ? function (fn) {
  1790. setTimeout(fn, 4);
  1791. } : function (fn) { fn(); };
  1792. /**
  1793. * Export require as a global, but only if it does not already exist.
  1794. */
  1795. if (!require) {
  1796. require = req;
  1797. }
  1798. req.version = version;
  1799. //Used to filter out dependencies that are already paths.
  1800. req.jsExtRegExp = /^\/|:|\?|\.js$/;
  1801. req.isBrowser = isBrowser;
  1802. s = req.s = {
  1803. contexts: contexts,
  1804. newContext: newContext
  1805. };
  1806. //Create default context.
  1807. req({});
  1808. //Exports some context-sensitive methods on global require.
  1809. each([
  1810. 'toUrl',
  1811. 'undef',
  1812. 'defined',
  1813. 'specified'
  1814. ], function (prop) {
  1815. //Reference from contexts instead of early binding to default context,
  1816. //so that during builds, the latest instance of the default context
  1817. //with its config gets used.
  1818. req[prop] = function () {
  1819. var ctx = contexts[defContextName];
  1820. return ctx.require[prop].apply(ctx, arguments);
  1821. };
  1822. });
  1823. if (isBrowser) {
  1824. head = s.head = document.getElementsByTagName('head')[0];
  1825. //If BASE tag is in play, using appendChild is a problem for IE6.
  1826. //When that browser dies, this can be removed. Details in this jQuery bug:
  1827. //http://dev.jquery.com/ticket/2709
  1828. baseElement = document.getElementsByTagName('base')[0];
  1829. if (baseElement) {
  1830. head = s.head = baseElement.parentNode;
  1831. }
  1832. }
  1833. /**
  1834. * Any errors that require explicitly generates will be passed to this
  1835. * function. Intercept/override it if you want custom error handling.
  1836. * @param {Error} err the error object.
  1837. */
  1838. req.onError = defaultOnError;
  1839. /**
  1840. * Creates the node for the load command. Only used in browser envs.
  1841. */
  1842. req.createNode = function (config, moduleName, url) {
  1843. var node = config.xhtml ?
  1844. document.createElementNS('http://www.w3.org/1999/xhtml', 'html:script') :
  1845. document.createElement('script');
  1846. node.type = config.scriptType || 'text/javascript';
  1847. node.charset = 'utf-8';
  1848. node.async = true;
  1849. return node;
  1850. };
  1851. /**
  1852. * Does the request to load a module for the browser case.
  1853. * Make this a separate function to allow other environments
  1854. * to override it.
  1855. *
  1856. * @param {Object} context the require context to find state.
  1857. * @param {String} moduleName the name of the module.
  1858. * @param {Object} url the URL to the module.
  1859. */
  1860. req.load = function (context, moduleName, url) {
  1861. var config = (context && context.config) || {},
  1862. node;
  1863. if (isBrowser) {
  1864. //In the browser so use a script tag
  1865. node = req.createNode(config, moduleName, url);
  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/requirejs/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/requirejs/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. //Calling onNodeCreated after all properties on the node have been
  1910. //set, but before it is placed in the DOM.
  1911. if (config.onNodeCreated) {
  1912. config.onNodeCreated(node, config, moduleName, url);
  1913. }
  1914. //For some cache cases in IE 6-8, the script executes before the end
  1915. //of the appendChild execution, so to tie an anonymous define
  1916. //call to the module name (which is stored on the node), hold on
  1917. //to a reference to this node, but clear after the DOM insertion.
  1918. currentlyAddingScript = node;
  1919. if (baseElement) {
  1920. head.insertBefore(node, baseElement);
  1921. } else {
  1922. head.appendChild(node);
  1923. }
  1924. currentlyAddingScript = null;
  1925. return node;
  1926. } else if (isWebWorker) {
  1927. try {
  1928. //In a web worker, use importScripts. This is not a very
  1929. //efficient use of importScripts, importScripts will block until
  1930. //its script is downloaded and evaluated. However, if web workers
  1931. //are in play, the expectation is that a build has been done so
  1932. //that only one script needs to be loaded anyway. This may need
  1933. //to be reevaluated if other use cases become common.
  1934. // Post a task to the event loop to work around a bug in WebKit
  1935. // where the worker gets garbage-collected after calling
  1936. // importScripts(): https://webkit.org/b/153317
  1937. setTimeout(function() {}, 0);
  1938. importScripts(url);
  1939. //Account for anonymous modules
  1940. context.completeLoad(moduleName);
  1941. } catch (e) {
  1942. context.onError(makeError('importscripts',
  1943. 'importScripts failed for ' +
  1944. moduleName + ' at ' + url,
  1945. e,
  1946. [moduleName]));
  1947. }
  1948. }
  1949. };
  1950. function getInteractiveScript() {
  1951. if (interactiveScript && interactiveScript.readyState === 'interactive') {
  1952. return interactiveScript;
  1953. }
  1954. eachReverse(scripts(), function (script) {
  1955. if (script.readyState === 'interactive') {
  1956. return (interactiveScript = script);
  1957. }
  1958. });
  1959. return interactiveScript;
  1960. }
  1961. //Look for a data-main script attribute, which could also adjust the baseUrl.
  1962. if (isBrowser && !cfg.skipDataMain) {
  1963. //Figure out baseUrl. Get it from the script tag with require.js in it.
  1964. eachReverse(scripts(), function (script) {
  1965. //Set the 'head' where we can append children by
  1966. //using the script's parent.
  1967. if (!head) {
  1968. head = script.parentNode;
  1969. }
  1970. //Look for a data-main attribute to set main script for the page
  1971. //to load. If it is there, the path to data main becomes the
  1972. //baseUrl, if it is not already set.
  1973. dataMain = script.getAttribute('data-main');
  1974. if (dataMain) {
  1975. //Preserve dataMain in case it is a path (i.e. contains '?')
  1976. mainScript = dataMain;
  1977. //Set final baseUrl if there is not already an explicit one,
  1978. //but only do so if the data-main value is not a loader plugin
  1979. //module ID.
  1980. if (!cfg.baseUrl && mainScript.indexOf('!') === -1) {
  1981. //Pull off the directory of data-main for use as the
  1982. //baseUrl.
  1983. src = mainScript.split('/');
  1984. mainScript = src.pop();
  1985. subPath = src.length ? src.join('/') + '/' : './';
  1986. cfg.baseUrl = subPath;
  1987. }
  1988. //Strip off any trailing .js since mainScript is now
  1989. //like a module name.
  1990. mainScript = mainScript.replace(jsSuffixRegExp, '');
  1991. //If mainScript is still a path, fall back to dataMain
  1992. if (req.jsExtRegExp.test(mainScript)) {
  1993. mainScript = dataMain;
  1994. }
  1995. //Put the data-main script in the files to load.
  1996. cfg.deps = cfg.deps ? cfg.deps.concat(mainScript) : [mainScript];
  1997. return true;
  1998. }
  1999. });
  2000. }
  2001. /**
  2002. * The function that handles definitions of modules. Differs from
  2003. * require() in that a string for the module should be the first argument,
  2004. * and the function to execute after dependencies are loaded should
  2005. * return a value to define the module corresponding to the first argument's
  2006. * name.
  2007. */
  2008. define = function (name, deps, callback) {
  2009. var node, context;
  2010. //Allow for anonymous modules
  2011. if (typeof name !== 'string') {
  2012. //Adjust args appropriately
  2013. callback = deps;
  2014. deps = name;
  2015. name = null;
  2016. }
  2017. //This module may not have dependencies
  2018. if (!isArray(deps)) {
  2019. callback = deps;
  2020. deps = null;
  2021. }
  2022. //If no name, and callback is a function, then figure out if it a
  2023. //CommonJS thing with dependencies.
  2024. if (!deps && isFunction(callback)) {
  2025. deps = [];
  2026. //Remove comments from the callback string,
  2027. //look for require calls, and pull them into the dependencies,
  2028. //but only if there are function args.
  2029. if (callback.length) {
  2030. callback
  2031. .toString()
  2032. .replace(commentRegExp, commentReplace)
  2033. .replace(cjsRequireRegExp, function (match, dep) {
  2034. deps.push(dep);
  2035. });
  2036. //May be a CommonJS thing even without require calls, but still
  2037. //could use exports, and module. Avoid doing exports and module
  2038. //work though if it just needs require.
  2039. //REQUIRES the function to expect the CommonJS variables in the
  2040. //order listed below.
  2041. deps = (callback.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps);
  2042. }
  2043. }
  2044. //If in IE 6-8 and hit an anonymous define() call, do the interactive
  2045. //work.
  2046. if (useInteractive) {
  2047. node = currentlyAddingScript || getInteractiveScript();
  2048. if (node) {
  2049. if (!name) {
  2050. name = node.getAttribute('data-requiremodule');
  2051. }
  2052. context = contexts[node.getAttribute('data-requirecontext')];
  2053. }
  2054. }
  2055. //Always save off evaluating the def call until the script onload handler.
  2056. //This allows multiple modules to be in a file without prematurely
  2057. //tracing dependencies, and allows for anonymous module support,
  2058. //where the module name is not known until the script onload event
  2059. //occurs. If no context, use the global queue, and get it processed
  2060. //in the onscript load callback.
  2061. if (context) {
  2062. context.defQueue.push([name, deps, callback]);
  2063. context.defQueueMap[name] = true;
  2064. } else {
  2065. globalDefQueue.push([name, deps, callback]);
  2066. }
  2067. };
  2068. define.amd = {
  2069. jQuery: true
  2070. };
  2071. /**
  2072. * Executes the text. Normally just uses eval, but can be modified
  2073. * to use a better, environment-specific call. Only used for transpiling
  2074. * loader plugins, not for plain JS modules.
  2075. * @param {String} text the text to execute/evaluate.
  2076. */
  2077. req.exec = function (text) {
  2078. /*jslint evil: true */
  2079. return eval(text);
  2080. };
  2081. //Set up with config info.
  2082. req(cfg);
  2083. }(this, (typeof setTimeout === 'undefined' ? undefined : setTimeout)));
  2084. this.requirejsVars = {
  2085. require: require,
  2086. requirejs: require,
  2087. define: define
  2088. };
  2089. if (env === 'browser') {
  2090. //sloppy since eval enclosed with use strict causes problems if the source
  2091. //text is not strict-compliant.
  2092. /*jslint sloppy: true, evil: true */
  2093. /*global require, XMLHttpRequest */
  2094. (function () {
  2095. // Separate function to avoid eval pollution, same with arguments use.
  2096. function exec() {
  2097. eval(arguments[0]);
  2098. }
  2099. require.load = function (context, moduleName, url) {
  2100. var xhr = new XMLHttpRequest();
  2101. xhr.open('GET', url, true);
  2102. xhr.send();
  2103. xhr.onreadystatechange = function () {
  2104. if (xhr.readyState === 4) {
  2105. exec(xhr.responseText);
  2106. //Support anonymous modules.
  2107. context.completeLoad(moduleName);
  2108. }
  2109. };
  2110. };
  2111. }());
  2112. } else if (env === 'rhino') {
  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. //Explicity not strict since this file contains an eval call, and do not want
  2126. //to enforce strict on code evaluated that way. See
  2127. //https://github.com/requirejs/r.js/issues/774
  2128. /*jslint regexp: false, sloppy: true*/
  2129. /*global require: false, define: false, requirejsVars: false, process: false */
  2130. /**
  2131. * This adapter assumes that x.js has loaded it and set up
  2132. * some variables. This adapter just allows limited RequireJS
  2133. * usage from within the requirejs directory. The general
  2134. * node adapater is r.js.
  2135. */
  2136. (function () {
  2137. var nodeReq = requirejsVars.nodeRequire,
  2138. req = requirejsVars.require,
  2139. def = requirejsVars.define,
  2140. fs = nodeReq('fs'),
  2141. path = nodeReq('path'),
  2142. vm = nodeReq('vm'),
  2143. //In Node 0.7+ existsSync is on fs.
  2144. exists = fs.existsSync || path.existsSync,
  2145. hasOwn = Object.prototype.hasOwnProperty;
  2146. function hasProp(obj, prop) {
  2147. return hasOwn.call(obj, prop);
  2148. }
  2149. function syncTick(fn) {
  2150. fn();
  2151. }
  2152. function makeError(message, moduleName) {
  2153. var err = new Error(message);
  2154. err.requireModules = [moduleName];
  2155. return err;
  2156. }
  2157. //Supply an implementation that allows synchronous get of a module.
  2158. req.get = function (context, moduleName, relModuleMap, localRequire) {
  2159. if (moduleName === "require" || moduleName === "exports" || moduleName === "module") {
  2160. context.onError(makeError("Explicit require of " + moduleName + " is not allowed.", moduleName));
  2161. }
  2162. var ret, oldTick,
  2163. moduleMap = context.makeModuleMap(moduleName, relModuleMap, false, true);
  2164. //Normalize module name, if it contains . or ..
  2165. moduleName = moduleMap.id;
  2166. if (hasProp(context.defined, moduleName)) {
  2167. ret = context.defined[moduleName];
  2168. } else {
  2169. if (ret === undefined) {
  2170. //Make sure nextTick for this type of call is sync-based.
  2171. oldTick = context.nextTick;
  2172. context.nextTick = syncTick;
  2173. try {
  2174. if (moduleMap.prefix) {
  2175. //A plugin, call requirejs to handle it. Now that
  2176. //nextTick is syncTick, the require will complete
  2177. //synchronously.
  2178. localRequire([moduleMap.originalName]);
  2179. //Now that plugin is loaded, can regenerate the moduleMap
  2180. //to get the final, normalized ID.
  2181. moduleMap = context.makeModuleMap(moduleMap.originalName, relModuleMap, false, true);
  2182. moduleName = moduleMap.id;
  2183. } else {
  2184. //Try to dynamically fetch it.
  2185. req.load(context, moduleName, moduleMap.url);
  2186. //Enable the module
  2187. context.enable(moduleMap, relModuleMap);
  2188. }
  2189. //Break any cycles by requiring it normally, but this will
  2190. //finish synchronously
  2191. context.require([moduleName]);
  2192. //The above calls are sync, so can do the next thing safely.
  2193. ret = context.defined[moduleName];
  2194. } finally {
  2195. context.nextTick = oldTick;
  2196. }
  2197. }
  2198. }
  2199. return ret;
  2200. };
  2201. req.nextTick = function (fn) {
  2202. process.nextTick(fn);
  2203. };
  2204. //Add wrapper around the code so that it gets the requirejs
  2205. //API instead of the Node API, and it is done lexically so
  2206. //that it survives later execution.
  2207. req.makeNodeWrapper = function (contents) {
  2208. return '(function (require, requirejs, define) { ' +
  2209. contents +
  2210. '\n}(requirejsVars.require, requirejsVars.requirejs, requirejsVars.define));';
  2211. };
  2212. req.load = function (context, moduleName, url) {
  2213. var contents, err,
  2214. config = context.config;
  2215. if (config.shim[moduleName] && (!config.suppress || !config.suppress.nodeShim)) {
  2216. console.warn('Shim config not supported in Node, may or may not work. Detected ' +
  2217. 'for module: ' + moduleName);
  2218. }
  2219. if (exists(url)) {
  2220. contents = fs.readFileSync(url, 'utf8');
  2221. contents = req.makeNodeWrapper(contents);
  2222. try {
  2223. vm.runInThisContext(contents, fs.realpathSync(url));
  2224. } catch (e) {
  2225. err = new Error('Evaluating ' + url + ' as module "' +
  2226. moduleName + '" failed with error: ' + e);
  2227. err.originalError = e;
  2228. err.moduleName = moduleName;
  2229. err.requireModules = [moduleName];
  2230. err.fileName = url;
  2231. return context.onError(err);
  2232. }
  2233. } else {
  2234. def(moduleName, function () {
  2235. //Get the original name, since relative requires may be
  2236. //resolved differently in node (issue #202). Also, if relative,
  2237. //make it relative to the URL of the item requesting it
  2238. //(issue #393)
  2239. var dirName,
  2240. map = hasProp(context.registry, moduleName) &&
  2241. context.registry[moduleName].map,
  2242. parentMap = map && map.parentMap,
  2243. originalName = map && map.originalName;
  2244. if (originalName.charAt(0) === '.' && parentMap) {
  2245. dirName = parentMap.url.split('/');
  2246. dirName.pop();
  2247. originalName = dirName.join('/') + '/' + originalName;
  2248. }
  2249. try {
  2250. return (context.config.nodeRequire || req.nodeRequire)(originalName);
  2251. } catch (e) {
  2252. err = new Error('Tried loading "' + moduleName + '" at ' +
  2253. url + ' then tried node\'s require("' +
  2254. originalName + '") and it failed ' +
  2255. 'with error: ' + e);
  2256. err.originalError = e;
  2257. err.moduleName = originalName;
  2258. err.requireModules = [moduleName];
  2259. throw err;
  2260. }
  2261. });
  2262. }
  2263. //Support anonymous modules.
  2264. context.completeLoad(moduleName);
  2265. };
  2266. //Override to provide the function wrapper for define/require.
  2267. req.exec = function (text) {
  2268. /*jslint evil: true */
  2269. text = req.makeNodeWrapper(text);
  2270. return eval(text);
  2271. };
  2272. }());
  2273. } else if (env === 'xpconnect') {
  2274. /*jslint */
  2275. /*global require, load */
  2276. (function () {
  2277. 'use strict';
  2278. require.load = function (context, moduleName, url) {
  2279. load(url);
  2280. //Support anonymous modules.
  2281. context.completeLoad(moduleName);
  2282. };
  2283. }());
  2284. }
  2285. //Support a default file name to execute. Useful for hosted envs
  2286. //like Joyent where it defaults to a server.js as the only executed
  2287. //script. But only do it if this is not an optimization run.
  2288. if (commandOption !== 'o' && (!fileName || !jsSuffixRegExp.test(fileName))) {
  2289. fileName = 'main.js';
  2290. }
  2291. /**
  2292. * Loads the library files that can be used for the optimizer, or for other
  2293. * tasks.
  2294. */
  2295. function loadLib() {
  2296. /*jslint strict: false */
  2297. /*global Packages: false, process: false, window: false, navigator: false,
  2298. document: false, define: false */
  2299. /**
  2300. * A plugin that modifies any /env/ path to be the right path based on
  2301. * the host environment. Right now only works for Node, Rhino and browser.
  2302. */
  2303. (function () {
  2304. var pathRegExp = /(\/|^)env\/|\{env\}/,
  2305. env = 'unknown';
  2306. if (typeof process !== 'undefined' && process.versions && !!process.versions.node) {
  2307. env = 'node';
  2308. } else if (typeof Packages !== 'undefined') {
  2309. env = 'rhino';
  2310. } else if ((typeof navigator !== 'undefined' && typeof document !== 'undefined') ||
  2311. (typeof importScripts !== 'undefined' && typeof self !== 'undefined')) {
  2312. env = 'browser';
  2313. } else if (typeof Components !== 'undefined' && Components.classes && Components.interfaces) {
  2314. env = 'xpconnect';
  2315. }
  2316. define('env', {
  2317. get: function () {
  2318. return env;
  2319. },
  2320. load: function (name, req, load, config) {
  2321. //Allow override in the config.
  2322. if (config.env) {
  2323. env = config.env;
  2324. }
  2325. name = name.replace(pathRegExp, function (match, prefix) {
  2326. if (match.indexOf('{') === -1) {
  2327. return prefix + env + '/';
  2328. } else {
  2329. return env;
  2330. }
  2331. });
  2332. req([name], function (mod) {
  2333. load(mod);
  2334. });
  2335. }
  2336. });
  2337. }());
  2338. /*jslint plusplus: true */
  2339. /*global define, java */
  2340. define('lang', function () {
  2341. 'use strict';
  2342. var lang, isJavaObj,
  2343. hasOwn = Object.prototype.hasOwnProperty;
  2344. function hasProp(obj, prop) {
  2345. return hasOwn.call(obj, prop);
  2346. }
  2347. isJavaObj = function () {
  2348. return false;
  2349. };
  2350. //Rhino, but not Nashorn (detected by importPackage not existing)
  2351. //Can have some strange foreign objects.
  2352. if (typeof java !== 'undefined' && java.lang && java.lang.Object && typeof importPackage !== 'undefined') {
  2353. isJavaObj = function (obj) {
  2354. return obj instanceof java.lang.Object;
  2355. };
  2356. }
  2357. lang = {
  2358. backSlashRegExp: /\\/g,
  2359. ostring: Object.prototype.toString,
  2360. isArray: Array.isArray || function (it) {
  2361. return lang.ostring.call(it) === "[object Array]";
  2362. },
  2363. isFunction: function(it) {
  2364. return lang.ostring.call(it) === "[object Function]";
  2365. },
  2366. isRegExp: function(it) {
  2367. return it && it instanceof RegExp;
  2368. },
  2369. hasProp: hasProp,
  2370. //returns true if the object does not have an own property prop,
  2371. //or if it does, it is a falsy value.
  2372. falseProp: function (obj, prop) {
  2373. return !hasProp(obj, prop) || !obj[prop];
  2374. },
  2375. //gets own property value for given prop on object
  2376. getOwn: function (obj, prop) {
  2377. return hasProp(obj, prop) && obj[prop];
  2378. },
  2379. _mixin: function(dest, source, override){
  2380. var name;
  2381. for (name in source) {
  2382. if(source.hasOwnProperty(name) &&
  2383. (override || !dest.hasOwnProperty(name))) {
  2384. dest[name] = source[name];
  2385. }
  2386. }
  2387. return dest; // Object
  2388. },
  2389. /**
  2390. * mixin({}, obj1, obj2) is allowed. If the last argument is a boolean,
  2391. * then the source objects properties are force copied over to dest.
  2392. */
  2393. mixin: function(dest){
  2394. var parameters = Array.prototype.slice.call(arguments),
  2395. override, i, l;
  2396. if (!dest) { dest = {}; }
  2397. if (parameters.length > 2 && typeof arguments[parameters.length-1] === 'boolean') {
  2398. override = parameters.pop();
  2399. }
  2400. for (i = 1, l = parameters.length; i < l; i++) {
  2401. lang._mixin(dest, parameters[i], override);
  2402. }
  2403. return dest; // Object
  2404. },
  2405. /**
  2406. * Does a deep mix of source into dest, where source values override
  2407. * dest values if a winner is needed.
  2408. * @param {Object} dest destination object that receives the mixed
  2409. * values.
  2410. * @param {Object} source source object contributing properties to mix
  2411. * in.
  2412. * @return {[Object]} returns dest object with the modification.
  2413. */
  2414. deepMix: function(dest, source) {
  2415. lang.eachProp(source, function (value, prop) {
  2416. if (typeof value === 'object' && value &&
  2417. !lang.isArray(value) && !lang.isFunction(value) &&
  2418. !(value instanceof RegExp)) {
  2419. if (!dest[prop]) {
  2420. dest[prop] = {};
  2421. }
  2422. lang.deepMix(dest[prop], value);
  2423. } else {
  2424. dest[prop] = value;
  2425. }
  2426. });
  2427. return dest;
  2428. },
  2429. /**
  2430. * Does a type of deep copy. Do not give it anything fancy, best
  2431. * for basic object copies of objects that also work well as
  2432. * JSON-serialized things, or has properties pointing to functions.
  2433. * For non-array/object values, just returns the same object.
  2434. * @param {Object} obj copy properties from this object
  2435. * @param {Object} [ignoredProps] optional object whose own properties
  2436. * are keys that should be ignored.
  2437. * @return {Object}
  2438. */
  2439. deeplikeCopy: function (obj, ignoredProps) {
  2440. var type, result;
  2441. if (lang.isArray(obj)) {
  2442. result = [];
  2443. obj.forEach(function(value) {
  2444. result.push(lang.deeplikeCopy(value, ignoredProps));
  2445. });
  2446. return result;
  2447. }
  2448. type = typeof obj;
  2449. if (obj === null || obj === undefined || type === 'boolean' ||
  2450. type === 'string' || type === 'number' || lang.isFunction(obj) ||
  2451. lang.isRegExp(obj)|| isJavaObj(obj)) {
  2452. return obj;
  2453. }
  2454. //Anything else is an object, hopefully.
  2455. result = {};
  2456. lang.eachProp(obj, function(value, key) {
  2457. if (!ignoredProps || !hasProp(ignoredProps, key)) {
  2458. result[key] = lang.deeplikeCopy(value, ignoredProps);
  2459. }
  2460. });
  2461. return result;
  2462. },
  2463. delegate: (function () {
  2464. // boodman/crockford delegation w/ cornford optimization
  2465. function TMP() {}
  2466. return function (obj, props) {
  2467. TMP.prototype = obj;
  2468. var tmp = new TMP();
  2469. TMP.prototype = null;
  2470. if (props) {
  2471. lang.mixin(tmp, props);
  2472. }
  2473. return tmp; // Object
  2474. };
  2475. }()),
  2476. /**
  2477. * Helper function for iterating over an array. If the func returns
  2478. * a true value, it will break out of the loop.
  2479. */
  2480. each: function each(ary, func) {
  2481. if (ary) {
  2482. var i;
  2483. for (i = 0; i < ary.length; i += 1) {
  2484. if (func(ary[i], i, ary)) {
  2485. break;
  2486. }
  2487. }
  2488. }
  2489. },
  2490. /**
  2491. * Cycles over properties in an object and calls a function for each
  2492. * property value. If the function returns a truthy value, then the
  2493. * iteration is stopped.
  2494. */
  2495. eachProp: function eachProp(obj, func) {
  2496. var prop;
  2497. for (prop in obj) {
  2498. if (hasProp(obj, prop)) {
  2499. if (func(obj[prop], prop)) {
  2500. break;
  2501. }
  2502. }
  2503. }
  2504. },
  2505. //Similar to Function.prototype.bind, but the "this" object is specified
  2506. //first, since it is easier to read/figure out what "this" will be.
  2507. bind: function bind(obj, fn) {
  2508. return function () {
  2509. return fn.apply(obj, arguments);
  2510. };
  2511. },
  2512. //Escapes a content string to be be a string that has characters escaped
  2513. //for inclusion as part of a JS string.
  2514. jsEscape: function (content) {
  2515. return content.replace(/(["'\\])/g, '\\$1')
  2516. .replace(/[\f]/g, "\\f")
  2517. .replace(/[\b]/g, "\\b")
  2518. .replace(/[\n]/g, "\\n")
  2519. .replace(/[\t]/g, "\\t")
  2520. .replace(/[\r]/g, "\\r");
  2521. }
  2522. };
  2523. return lang;
  2524. });
  2525. /**
  2526. * prim 0.0.1 Copyright (c) 2012-2014, The Dojo Foundation All Rights Reserved.
  2527. * Available via the MIT or new BSD license.
  2528. * see: http://github.com/requirejs/prim for details
  2529. */
  2530. /*global setImmediate, process, setTimeout, define, module */
  2531. //Set prime.hideResolutionConflict = true to allow "resolution-races"
  2532. //in promise-tests to pass.
  2533. //Since the goal of prim is to be a small impl for trusted code, it is
  2534. //more important to normally throw in this case so that we can find
  2535. //logic errors quicker.
  2536. var prim;
  2537. (function () {
  2538. 'use strict';
  2539. var op = Object.prototype,
  2540. hasOwn = op.hasOwnProperty;
  2541. function hasProp(obj, prop) {
  2542. return hasOwn.call(obj, prop);
  2543. }
  2544. /**
  2545. * Helper function for iterating over an array. If the func returns
  2546. * a true value, it will break out of the loop.
  2547. */
  2548. function each(ary, func) {
  2549. if (ary) {
  2550. var i;
  2551. for (i = 0; i < ary.length; i += 1) {
  2552. if (ary[i]) {
  2553. func(ary[i], i, ary);
  2554. }
  2555. }
  2556. }
  2557. }
  2558. function check(p) {
  2559. if (hasProp(p, 'e') || hasProp(p, 'v')) {
  2560. if (!prim.hideResolutionConflict) {
  2561. throw new Error('Prim promise already resolved: ' +
  2562. JSON.stringify(p));
  2563. }
  2564. return false;
  2565. }
  2566. return true;
  2567. }
  2568. function notify(ary, value) {
  2569. prim.nextTick(function () {
  2570. each(ary, function (item) {
  2571. item(value);
  2572. });
  2573. });
  2574. }
  2575. prim = function prim() {
  2576. var p,
  2577. ok = [],
  2578. fail = [];
  2579. return (p = {
  2580. callback: function (yes, no) {
  2581. if (no) {
  2582. p.errback(no);
  2583. }
  2584. if (hasProp(p, 'v')) {
  2585. prim.nextTick(function () {
  2586. yes(p.v);
  2587. });
  2588. } else {
  2589. ok.push(yes);
  2590. }
  2591. },
  2592. errback: function (no) {
  2593. if (hasProp(p, 'e')) {
  2594. prim.nextTick(function () {
  2595. no(p.e);
  2596. });
  2597. } else {
  2598. fail.push(no);
  2599. }
  2600. },
  2601. finished: function () {
  2602. return hasProp(p, 'e') || hasProp(p, 'v');
  2603. },
  2604. rejected: function () {
  2605. return hasProp(p, 'e');
  2606. },
  2607. resolve: function (v) {
  2608. if (check(p)) {
  2609. p.v = v;
  2610. notify(ok, v);
  2611. }
  2612. return p;
  2613. },
  2614. reject: function (e) {
  2615. if (check(p)) {
  2616. p.e = e;
  2617. notify(fail, e);
  2618. }
  2619. return p;
  2620. },
  2621. start: function (fn) {
  2622. p.resolve();
  2623. return p.promise.then(fn);
  2624. },
  2625. promise: {
  2626. then: function (yes, no) {
  2627. var next = prim();
  2628. p.callback(function (v) {
  2629. try {
  2630. if (yes && typeof yes === 'function') {
  2631. v = yes(v);
  2632. }
  2633. if (v && v.then) {
  2634. v.then(next.resolve, next.reject);
  2635. } else {
  2636. next.resolve(v);
  2637. }
  2638. } catch (e) {
  2639. next.reject(e);
  2640. }
  2641. }, function (e) {
  2642. var err;
  2643. try {
  2644. if (!no || typeof no !== 'function') {
  2645. next.reject(e);
  2646. } else {
  2647. err = no(e);
  2648. if (err && err.then) {
  2649. err.then(next.resolve, next.reject);
  2650. } else {
  2651. next.resolve(err);
  2652. }
  2653. }
  2654. } catch (e2) {
  2655. next.reject(e2);
  2656. }
  2657. });
  2658. return next.promise;
  2659. },
  2660. fail: function (no) {
  2661. return p.promise.then(null, no);
  2662. },
  2663. end: function () {
  2664. p.errback(function (e) {
  2665. throw e;
  2666. });
  2667. }
  2668. }
  2669. });
  2670. };
  2671. prim.serial = function (ary) {
  2672. var result = prim().resolve().promise;
  2673. each(ary, function (item) {
  2674. result = result.then(function () {
  2675. return item();
  2676. });
  2677. });
  2678. return result;
  2679. };
  2680. prim.nextTick = typeof setImmediate === 'function' ? setImmediate :
  2681. (typeof process !== 'undefined' && process.nextTick ?
  2682. process.nextTick : (typeof setTimeout !== 'undefined' ?
  2683. function (fn) {
  2684. setTimeout(fn, 0);
  2685. } : function (fn) {
  2686. fn();
  2687. }));
  2688. if (typeof define === 'function' && define.amd) {
  2689. define('prim', function () { return prim; });
  2690. } else if (typeof module !== 'undefined' && module.exports) {
  2691. module.exports = prim;
  2692. }
  2693. }());
  2694. if(env === 'browser') {
  2695. /*jslint strict: false */
  2696. /*global define: false, load: false */
  2697. //Just a stub for use with uglify's consolidator.js
  2698. define('browser/assert', function () {
  2699. return {};
  2700. });
  2701. }
  2702. if(env === 'node') {
  2703. /*jslint strict: false */
  2704. /*global define: false, load: false */
  2705. //Needed so that rhino/assert can return a stub for uglify's consolidator.js
  2706. define('node/assert', ['assert'], function (assert) {
  2707. return assert;
  2708. });
  2709. }
  2710. if(env === 'rhino') {
  2711. /*jslint strict: false */
  2712. /*global define: false, load: false */
  2713. //Just a stub for use with uglify's consolidator.js
  2714. define('rhino/assert', function () {
  2715. return {};
  2716. });
  2717. }
  2718. if(env === 'xpconnect') {
  2719. /*jslint strict: false */
  2720. /*global define: false, load: false */
  2721. //Just a stub for use with uglify's consolidator.js
  2722. define('xpconnect/assert', function () {
  2723. return {};
  2724. });
  2725. }
  2726. if(env === 'browser') {
  2727. /*jslint strict: false */
  2728. /*global define: false, process: false */
  2729. define('browser/args', function () {
  2730. //Always expect config via an API call
  2731. return [];
  2732. });
  2733. }
  2734. if(env === 'node') {
  2735. /*jslint strict: false */
  2736. /*global define: false, process: false */
  2737. define('node/args', function () {
  2738. //Do not return the "node" or "r.js" arguments
  2739. var args = process.argv.slice(2);
  2740. //Ignore any command option used for main x.js branching
  2741. if (args[0] && args[0].indexOf('-') === 0) {
  2742. args = args.slice(1);
  2743. }
  2744. return args;
  2745. });
  2746. }
  2747. if(env === 'rhino') {
  2748. /*jslint strict: false */
  2749. /*global define: false, process: false */
  2750. var jsLibRhinoArgs = (typeof rhinoArgs !== 'undefined' && rhinoArgs) || [].concat(Array.prototype.slice.call(arguments, 0));
  2751. define('rhino/args', function () {
  2752. var args = jsLibRhinoArgs;
  2753. //Ignore any command option used for main x.js branching
  2754. if (args[0] && args[0].indexOf('-') === 0) {
  2755. args = args.slice(1);
  2756. }
  2757. return args;
  2758. });
  2759. }
  2760. if(env === 'xpconnect') {
  2761. /*jslint strict: false */
  2762. /*global define, xpconnectArgs */
  2763. var jsLibXpConnectArgs = (typeof xpconnectArgs !== 'undefined' && xpconnectArgs) || [].concat(Array.prototype.slice.call(arguments, 0));
  2764. define('xpconnect/args', function () {
  2765. var args = jsLibXpConnectArgs;
  2766. //Ignore any command option used for main x.js branching
  2767. if (args[0] && args[0].indexOf('-') === 0) {
  2768. args = args.slice(1);
  2769. }
  2770. return args;
  2771. });
  2772. }
  2773. if(env === 'browser') {
  2774. /*jslint strict: false */
  2775. /*global define: false, console: false */
  2776. define('browser/load', ['./file'], function (file) {
  2777. function load(fileName) {
  2778. eval(file.readFile(fileName));
  2779. }
  2780. return load;
  2781. });
  2782. }
  2783. if(env === 'node') {
  2784. /*jslint strict: false */
  2785. /*global define: false, console: false */
  2786. define('node/load', ['fs'], function (fs) {
  2787. function load(fileName) {
  2788. var contents = fs.readFileSync(fileName, 'utf8');
  2789. process.compile(contents, fileName);
  2790. }
  2791. return load;
  2792. });
  2793. }
  2794. if(env === 'rhino') {
  2795. /*jslint strict: false */
  2796. /*global define: false, load: false */
  2797. define('rhino/load', function () {
  2798. return load;
  2799. });
  2800. }
  2801. if(env === 'xpconnect') {
  2802. /*jslint strict: false */
  2803. /*global define: false, load: false */
  2804. define('xpconnect/load', function () {
  2805. return load;
  2806. });
  2807. }
  2808. if(env === 'browser') {
  2809. /*jslint sloppy: true, nomen: true */
  2810. /*global require, define, console, XMLHttpRequest, requirejs, location */
  2811. define('browser/file', ['prim'], function (prim) {
  2812. var file,
  2813. currDirRegExp = /^\.(\/|$)/;
  2814. function frontSlash(path) {
  2815. return path.replace(/\\/g, '/');
  2816. }
  2817. function exists(path) {
  2818. var status, xhr = new XMLHttpRequest();
  2819. //Oh yeah, that is right SYNC IO. Behold its glory
  2820. //and horrible blocking behavior.
  2821. xhr.open('HEAD', path, false);
  2822. xhr.send();
  2823. status = xhr.status;
  2824. return status === 200 || status === 304;
  2825. }
  2826. function mkDir(dir) {
  2827. console.log('mkDir is no-op in browser');
  2828. }
  2829. function mkFullDir(dir) {
  2830. console.log('mkFullDir is no-op in browser');
  2831. }
  2832. file = {
  2833. backSlashRegExp: /\\/g,
  2834. exclusionRegExp: /^\./,
  2835. getLineSeparator: function () {
  2836. return '/';
  2837. },
  2838. exists: function (fileName) {
  2839. return exists(fileName);
  2840. },
  2841. parent: function (fileName) {
  2842. var parts = fileName.split('/');
  2843. parts.pop();
  2844. return parts.join('/');
  2845. },
  2846. /**
  2847. * Gets the absolute file path as a string, normalized
  2848. * to using front slashes for path separators.
  2849. * @param {String} fileName
  2850. */
  2851. absPath: function (fileName) {
  2852. var dir;
  2853. if (currDirRegExp.test(fileName)) {
  2854. dir = frontSlash(location.href);
  2855. if (dir.indexOf('/') !== -1) {
  2856. dir = dir.split('/');
  2857. //Pull off protocol and host, just want
  2858. //to allow paths (other build parts, like
  2859. //require._isSupportedBuildUrl do not support
  2860. //full URLs), but a full path from
  2861. //the root.
  2862. dir.splice(0, 3);
  2863. dir.pop();
  2864. dir = '/' + dir.join('/');
  2865. }
  2866. fileName = dir + fileName.substring(1);
  2867. }
  2868. return fileName;
  2869. },
  2870. normalize: function (fileName) {
  2871. return fileName;
  2872. },
  2873. isFile: function (path) {
  2874. return true;
  2875. },
  2876. isDirectory: function (path) {
  2877. return false;
  2878. },
  2879. getFilteredFileList: function (startDir, regExpFilters, makeUnixPaths) {
  2880. console.log('file.getFilteredFileList is no-op in browser');
  2881. },
  2882. copyDir: function (srcDir, destDir, regExpFilter, onlyCopyNew) {
  2883. console.log('file.copyDir is no-op in browser');
  2884. },
  2885. copyFile: function (srcFileName, destFileName, onlyCopyNew) {
  2886. console.log('file.copyFile is no-op in browser');
  2887. },
  2888. /**
  2889. * Renames a file. May fail if "to" already exists or is on another drive.
  2890. */
  2891. renameFile: function (from, to) {
  2892. console.log('file.renameFile is no-op in browser');
  2893. },
  2894. /**
  2895. * Reads a *text* file.
  2896. */
  2897. readFile: function (path, encoding) {
  2898. var xhr = new XMLHttpRequest();
  2899. //Oh yeah, that is right SYNC IO. Behold its glory
  2900. //and horrible blocking behavior.
  2901. xhr.open('GET', path, false);
  2902. xhr.send();
  2903. return xhr.responseText;
  2904. },
  2905. readFileAsync: function (path, encoding) {
  2906. var xhr = new XMLHttpRequest(),
  2907. d = prim();
  2908. xhr.open('GET', path, true);
  2909. xhr.send();
  2910. xhr.onreadystatechange = function () {
  2911. if (xhr.readyState === 4) {
  2912. if (xhr.status > 400) {
  2913. d.reject(new Error('Status: ' + xhr.status + ': ' + xhr.statusText));
  2914. } else {
  2915. d.resolve(xhr.responseText);
  2916. }
  2917. }
  2918. };
  2919. return d.promise;
  2920. },
  2921. saveUtf8File: function (fileName, fileContents) {
  2922. //summary: saves a *text* file using UTF-8 encoding.
  2923. file.saveFile(fileName, fileContents, "utf8");
  2924. },
  2925. saveFile: function (fileName, fileContents, encoding) {
  2926. requirejs.browser.saveFile(fileName, fileContents, encoding);
  2927. },
  2928. deleteFile: function (fileName) {
  2929. console.log('file.deleteFile is no-op in browser');
  2930. },
  2931. /**
  2932. * Deletes any empty directories under the given directory.
  2933. */
  2934. deleteEmptyDirs: function (startDir) {
  2935. console.log('file.deleteEmptyDirs is no-op in browser');
  2936. }
  2937. };
  2938. return file;
  2939. });
  2940. }
  2941. if(env === 'node') {
  2942. /*jslint plusplus: false, octal:false, strict: false */
  2943. /*global define: false, process: false */
  2944. define('node/file', ['fs', 'path', 'prim'], function (fs, path, prim) {
  2945. var isWindows = process.platform === 'win32',
  2946. windowsDriveRegExp = /^[a-zA-Z]\:\/$/,
  2947. file;
  2948. function frontSlash(path) {
  2949. return path.replace(/\\/g, '/');
  2950. }
  2951. function exists(path) {
  2952. if (isWindows && path.charAt(path.length - 1) === '/' &&
  2953. path.charAt(path.length - 2) !== ':') {
  2954. path = path.substring(0, path.length - 1);
  2955. }
  2956. try {
  2957. fs.statSync(path);
  2958. return true;
  2959. } catch (e) {
  2960. return false;
  2961. }
  2962. }
  2963. function mkDir(dir) {
  2964. if (!exists(dir) && (!isWindows || !windowsDriveRegExp.test(dir))) {
  2965. fs.mkdirSync(dir, 511);
  2966. }
  2967. }
  2968. function mkFullDir(dir) {
  2969. var parts = dir.split('/'),
  2970. currDir = '',
  2971. first = true;
  2972. parts.forEach(function (part) {
  2973. //First part may be empty string if path starts with a slash.
  2974. currDir += part + '/';
  2975. first = false;
  2976. if (part) {
  2977. mkDir(currDir);
  2978. }
  2979. });
  2980. }
  2981. file = {
  2982. backSlashRegExp: /\\/g,
  2983. exclusionRegExp: /^\./,
  2984. getLineSeparator: function () {
  2985. return '/';
  2986. },
  2987. exists: function (fileName) {
  2988. return exists(fileName);
  2989. },
  2990. parent: function (fileName) {
  2991. var parts = fileName.split('/');
  2992. parts.pop();
  2993. return parts.join('/');
  2994. },
  2995. /**
  2996. * Gets the absolute file path as a string, normalized
  2997. * to using front slashes for path separators.
  2998. * @param {String} fileName
  2999. */
  3000. absPath: function (fileName) {
  3001. return frontSlash(path.normalize(frontSlash(fs.realpathSync(fileName))));
  3002. },
  3003. normalize: function (fileName) {
  3004. return frontSlash(path.normalize(fileName));
  3005. },
  3006. isFile: function (path) {
  3007. return fs.statSync(path).isFile();
  3008. },
  3009. isDirectory: function (path) {
  3010. return fs.statSync(path).isDirectory();
  3011. },
  3012. getFilteredFileList: function (/*String*/startDir, /*RegExp*/regExpFilters, /*boolean?*/makeUnixPaths) {
  3013. //summary: Recurses startDir and finds matches to the files that match regExpFilters.include
  3014. //and do not match regExpFilters.exclude. Or just one regexp can be passed in for regExpFilters,
  3015. //and it will be treated as the "include" case.
  3016. //Ignores files/directories that start with a period (.) unless exclusionRegExp
  3017. //is set to another value.
  3018. var files = [], topDir, regExpInclude, regExpExclude, dirFileArray,
  3019. i, stat, filePath, ok, dirFiles, fileName;
  3020. topDir = startDir;
  3021. regExpInclude = regExpFilters.include || regExpFilters;
  3022. regExpExclude = regExpFilters.exclude || null;
  3023. if (file.exists(topDir)) {
  3024. dirFileArray = fs.readdirSync(topDir);
  3025. for (i = 0; i < dirFileArray.length; i++) {
  3026. fileName = dirFileArray[i];
  3027. filePath = path.join(topDir, fileName);
  3028. stat = fs.statSync(filePath);
  3029. if (stat.isFile()) {
  3030. if (makeUnixPaths) {
  3031. //Make sure we have a JS string.
  3032. if (filePath.indexOf("/") === -1) {
  3033. filePath = frontSlash(filePath);
  3034. }
  3035. }
  3036. ok = true;
  3037. if (regExpInclude) {
  3038. ok = filePath.match(regExpInclude);
  3039. }
  3040. if (ok && regExpExclude) {
  3041. ok = !filePath.match(regExpExclude);
  3042. }
  3043. if (ok && (!file.exclusionRegExp ||
  3044. !file.exclusionRegExp.test(fileName))) {
  3045. files.push(filePath);
  3046. }
  3047. } else if (stat.isDirectory() &&
  3048. (!file.exclusionRegExp || !file.exclusionRegExp.test(fileName))) {
  3049. dirFiles = this.getFilteredFileList(filePath, regExpFilters, makeUnixPaths);
  3050. //Do not use push.apply for dir listings, can hit limit of max number
  3051. //of arguments to a function call, #921.
  3052. dirFiles.forEach(function (dirFile) {
  3053. files.push(dirFile);
  3054. });
  3055. }
  3056. }
  3057. }
  3058. return files; //Array
  3059. },
  3060. copyDir: function (/*String*/srcDir, /*String*/destDir, /*RegExp?*/regExpFilter, /*boolean?*/onlyCopyNew) {
  3061. //summary: copies files from srcDir to destDir using the regExpFilter to determine if the
  3062. //file should be copied. Returns a list file name strings of the destinations that were copied.
  3063. regExpFilter = regExpFilter || /\w/;
  3064. //Normalize th directory names, but keep front slashes.
  3065. //path module on windows now returns backslashed paths.
  3066. srcDir = frontSlash(path.normalize(srcDir));
  3067. destDir = frontSlash(path.normalize(destDir));
  3068. var fileNames = file.getFilteredFileList(srcDir, regExpFilter, true),
  3069. copiedFiles = [], i, srcFileName, destFileName;
  3070. for (i = 0; i < fileNames.length; i++) {
  3071. srcFileName = fileNames[i];
  3072. destFileName = srcFileName.replace(srcDir, destDir);
  3073. if (file.copyFile(srcFileName, destFileName, onlyCopyNew)) {
  3074. copiedFiles.push(destFileName);
  3075. }
  3076. }
  3077. return copiedFiles.length ? copiedFiles : null; //Array or null
  3078. },
  3079. copyFile: function (/*String*/srcFileName, /*String*/destFileName, /*boolean?*/onlyCopyNew) {
  3080. //summary: copies srcFileName to destFileName. If onlyCopyNew is set, it only copies the file if
  3081. //srcFileName is newer than destFileName. Returns a boolean indicating if the copy occurred.
  3082. var parentDir;
  3083. //logger.trace("Src filename: " + srcFileName);
  3084. //logger.trace("Dest filename: " + destFileName);
  3085. //If onlyCopyNew is true, then compare dates and only copy if the src is newer
  3086. //than dest.
  3087. if (onlyCopyNew) {
  3088. if (file.exists(destFileName) && fs.statSync(destFileName).mtime.getTime() >= fs.statSync(srcFileName).mtime.getTime()) {
  3089. return false; //Boolean
  3090. }
  3091. }
  3092. //Make sure destination dir exists.
  3093. parentDir = path.dirname(destFileName);
  3094. if (!file.exists(parentDir)) {
  3095. mkFullDir(parentDir);
  3096. }
  3097. fs.writeFileSync(destFileName, fs.readFileSync(srcFileName, 'binary'), 'binary');
  3098. return true; //Boolean
  3099. },
  3100. /**
  3101. * Renames a file. May fail if "to" already exists or is on another drive.
  3102. */
  3103. renameFile: function (from, to) {
  3104. return fs.renameSync(from, to);
  3105. },
  3106. /**
  3107. * Reads a *text* file.
  3108. */
  3109. readFile: function (/*String*/path, /*String?*/encoding) {
  3110. if (encoding === 'utf-8') {
  3111. encoding = 'utf8';
  3112. }
  3113. if (!encoding) {
  3114. encoding = 'utf8';
  3115. }
  3116. var text = fs.readFileSync(path, encoding);
  3117. //Hmm, would not expect to get A BOM, but it seems to happen,
  3118. //remove it just in case.
  3119. if (text.indexOf('\uFEFF') === 0) {
  3120. text = text.substring(1, text.length);
  3121. }
  3122. return text;
  3123. },
  3124. readFileAsync: function (path, encoding) {
  3125. var d = prim();
  3126. try {
  3127. d.resolve(file.readFile(path, encoding));
  3128. } catch (e) {
  3129. d.reject(e);
  3130. }
  3131. return d.promise;
  3132. },
  3133. saveUtf8File: function (/*String*/fileName, /*String*/fileContents) {
  3134. //summary: saves a *text* file using UTF-8 encoding.
  3135. file.saveFile(fileName, fileContents, "utf8");
  3136. },
  3137. saveFile: function (/*String*/fileName, /*String*/fileContents, /*String?*/encoding) {
  3138. //summary: saves a *text* file.
  3139. var parentDir;
  3140. if (encoding === 'utf-8') {
  3141. encoding = 'utf8';
  3142. }
  3143. if (!encoding) {
  3144. encoding = 'utf8';
  3145. }
  3146. //Make sure destination directories exist.
  3147. parentDir = path.dirname(fileName);
  3148. if (!file.exists(parentDir)) {
  3149. mkFullDir(parentDir);
  3150. }
  3151. fs.writeFileSync(fileName, fileContents, encoding);
  3152. },
  3153. deleteFile: function (/*String*/fileName) {
  3154. //summary: deletes a file or directory if it exists.
  3155. var files, i, stat;
  3156. if (file.exists(fileName)) {
  3157. stat = fs.lstatSync(fileName);
  3158. if (stat.isDirectory()) {
  3159. files = fs.readdirSync(fileName);
  3160. for (i = 0; i < files.length; i++) {
  3161. this.deleteFile(path.join(fileName, files[i]));
  3162. }
  3163. fs.rmdirSync(fileName);
  3164. } else {
  3165. fs.unlinkSync(fileName);
  3166. }
  3167. }
  3168. },
  3169. /**
  3170. * Deletes any empty directories under the given directory.
  3171. */
  3172. deleteEmptyDirs: function (startDir) {
  3173. var dirFileArray, i, fileName, filePath, stat;
  3174. if (file.exists(startDir)) {
  3175. dirFileArray = fs.readdirSync(startDir);
  3176. for (i = 0; i < dirFileArray.length; i++) {
  3177. fileName = dirFileArray[i];
  3178. filePath = path.join(startDir, fileName);
  3179. stat = fs.lstatSync(filePath);
  3180. if (stat.isDirectory()) {
  3181. file.deleteEmptyDirs(filePath);
  3182. }
  3183. }
  3184. //If directory is now empty, remove it.
  3185. if (fs.readdirSync(startDir).length === 0) {
  3186. file.deleteFile(startDir);
  3187. }
  3188. }
  3189. }
  3190. };
  3191. return file;
  3192. });
  3193. }
  3194. if(env === 'rhino') {
  3195. //Helper functions to deal with file I/O.
  3196. /*jslint plusplus: false */
  3197. /*global java: false, define: false */
  3198. define('rhino/file', ['prim'], function (prim) {
  3199. var file = {
  3200. backSlashRegExp: /\\/g,
  3201. exclusionRegExp: /^\./,
  3202. getLineSeparator: function () {
  3203. return file.lineSeparator;
  3204. },
  3205. lineSeparator: java.lang.System.getProperty("line.separator"), //Java String
  3206. exists: function (fileName) {
  3207. return (new java.io.File(fileName)).exists();
  3208. },
  3209. parent: function (fileName) {
  3210. return file.absPath((new java.io.File(fileName)).getParentFile());
  3211. },
  3212. normalize: function (fileName) {
  3213. return file.absPath(fileName);
  3214. },
  3215. isFile: function (path) {
  3216. return (new java.io.File(path)).isFile();
  3217. },
  3218. isDirectory: function (path) {
  3219. return (new java.io.File(path)).isDirectory();
  3220. },
  3221. /**
  3222. * Gets the absolute file path as a string, normalized
  3223. * to using front slashes for path separators.
  3224. * @param {java.io.File||String} file
  3225. */
  3226. absPath: function (fileObj) {
  3227. if (typeof fileObj === "string") {
  3228. fileObj = new java.io.File(fileObj);
  3229. }
  3230. return (fileObj.getCanonicalPath() + "").replace(file.backSlashRegExp, "/");
  3231. },
  3232. getFilteredFileList: function (/*String*/startDir, /*RegExp*/regExpFilters, /*boolean?*/makeUnixPaths, /*boolean?*/startDirIsJavaObject) {
  3233. //summary: Recurses startDir and finds matches to the files that match regExpFilters.include
  3234. //and do not match regExpFilters.exclude. Or just one regexp can be passed in for regExpFilters,
  3235. //and it will be treated as the "include" case.
  3236. //Ignores files/directories that start with a period (.) unless exclusionRegExp
  3237. //is set to another value.
  3238. var files = [], topDir, regExpInclude, regExpExclude, dirFileArray,
  3239. i, fileObj, filePath, ok, dirFiles;
  3240. topDir = startDir;
  3241. if (!startDirIsJavaObject) {
  3242. topDir = new java.io.File(startDir);
  3243. }
  3244. regExpInclude = regExpFilters.include || regExpFilters;
  3245. regExpExclude = regExpFilters.exclude || null;
  3246. if (topDir.exists()) {
  3247. dirFileArray = topDir.listFiles();
  3248. for (i = 0; i < dirFileArray.length; i++) {
  3249. fileObj = dirFileArray[i];
  3250. if (fileObj.isFile()) {
  3251. filePath = fileObj.getPath();
  3252. if (makeUnixPaths) {
  3253. //Make sure we have a JS string.
  3254. filePath = String(filePath);
  3255. if (filePath.indexOf("/") === -1) {
  3256. filePath = filePath.replace(/\\/g, "/");
  3257. }
  3258. }
  3259. ok = true;
  3260. if (regExpInclude) {
  3261. ok = filePath.match(regExpInclude);
  3262. }
  3263. if (ok && regExpExclude) {
  3264. ok = !filePath.match(regExpExclude);
  3265. }
  3266. if (ok && (!file.exclusionRegExp ||
  3267. !file.exclusionRegExp.test(fileObj.getName()))) {
  3268. files.push(filePath);
  3269. }
  3270. } else if (fileObj.isDirectory() &&
  3271. (!file.exclusionRegExp || !file.exclusionRegExp.test(fileObj.getName()))) {
  3272. dirFiles = this.getFilteredFileList(fileObj, regExpFilters, makeUnixPaths, true);
  3273. //Do not use push.apply for dir listings, can hit limit of max number
  3274. //of arguments to a function call, #921.
  3275. dirFiles.forEach(function (dirFile) {
  3276. files.push(dirFile);
  3277. });
  3278. }
  3279. }
  3280. }
  3281. return files; //Array
  3282. },
  3283. copyDir: function (/*String*/srcDir, /*String*/destDir, /*RegExp?*/regExpFilter, /*boolean?*/onlyCopyNew) {
  3284. //summary: copies files from srcDir to destDir using the regExpFilter to determine if the
  3285. //file should be copied. Returns a list file name strings of the destinations that were copied.
  3286. regExpFilter = regExpFilter || /\w/;
  3287. var fileNames = file.getFilteredFileList(srcDir, regExpFilter, true),
  3288. copiedFiles = [], i, srcFileName, destFileName;
  3289. for (i = 0; i < fileNames.length; i++) {
  3290. srcFileName = fileNames[i];
  3291. destFileName = srcFileName.replace(srcDir, destDir);
  3292. if (file.copyFile(srcFileName, destFileName, onlyCopyNew)) {
  3293. copiedFiles.push(destFileName);
  3294. }
  3295. }
  3296. return copiedFiles.length ? copiedFiles : null; //Array or null
  3297. },
  3298. copyFile: function (/*String*/srcFileName, /*String*/destFileName, /*boolean?*/onlyCopyNew) {
  3299. //summary: copies srcFileName to destFileName. If onlyCopyNew is set, it only copies the file if
  3300. //srcFileName is newer than destFileName. Returns a boolean indicating if the copy occurred.
  3301. var destFile = new java.io.File(destFileName), srcFile, parentDir,
  3302. srcChannel, destChannel;
  3303. //logger.trace("Src filename: " + srcFileName);
  3304. //logger.trace("Dest filename: " + destFileName);
  3305. //If onlyCopyNew is true, then compare dates and only copy if the src is newer
  3306. //than dest.
  3307. if (onlyCopyNew) {
  3308. srcFile = new java.io.File(srcFileName);
  3309. if (destFile.exists() && destFile.lastModified() >= srcFile.lastModified()) {
  3310. return false; //Boolean
  3311. }
  3312. }
  3313. //Make sure destination dir exists.
  3314. parentDir = destFile.getParentFile();
  3315. if (!parentDir.exists()) {
  3316. if (!parentDir.mkdirs()) {
  3317. throw "Could not create directory: " + parentDir.getCanonicalPath();
  3318. }
  3319. }
  3320. //Java's version of copy file.
  3321. srcChannel = new java.io.FileInputStream(srcFileName).getChannel();
  3322. destChannel = new java.io.FileOutputStream(destFileName).getChannel();
  3323. destChannel.transferFrom(srcChannel, 0, srcChannel.size());
  3324. srcChannel.close();
  3325. destChannel.close();
  3326. return true; //Boolean
  3327. },
  3328. /**
  3329. * Renames a file. May fail if "to" already exists or is on another drive.
  3330. */
  3331. renameFile: function (from, to) {
  3332. return (new java.io.File(from)).renameTo((new java.io.File(to)));
  3333. },
  3334. readFile: function (/*String*/path, /*String?*/encoding) {
  3335. //A file read function that can deal with BOMs
  3336. encoding = encoding || "utf-8";
  3337. var fileObj = new java.io.File(path),
  3338. input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(fileObj), encoding)),
  3339. stringBuffer, line;
  3340. try {
  3341. stringBuffer = new java.lang.StringBuffer();
  3342. line = input.readLine();
  3343. // Byte Order Mark (BOM) - The Unicode Standard, version 3.0, page 324
  3344. // http://www.unicode.org/faq/utf_bom.html
  3345. // 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:
  3346. // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4508058
  3347. if (line && line.length() && line.charAt(0) === 0xfeff) {
  3348. // Eat the BOM, since we've already found the encoding on this file,
  3349. // and we plan to concatenating this buffer with others; the BOM should
  3350. // only appear at the top of a file.
  3351. line = line.substring(1);
  3352. }
  3353. while (line !== null) {
  3354. stringBuffer.append(line);
  3355. stringBuffer.append(file.lineSeparator);
  3356. line = input.readLine();
  3357. }
  3358. //Make sure we return a JavaScript string and not a Java string.
  3359. return String(stringBuffer.toString()); //String
  3360. } finally {
  3361. input.close();
  3362. }
  3363. },
  3364. readFileAsync: function (path, encoding) {
  3365. var d = prim();
  3366. try {
  3367. d.resolve(file.readFile(path, encoding));
  3368. } catch (e) {
  3369. d.reject(e);
  3370. }
  3371. return d.promise;
  3372. },
  3373. saveUtf8File: function (/*String*/fileName, /*String*/fileContents) {
  3374. //summary: saves a file using UTF-8 encoding.
  3375. file.saveFile(fileName, fileContents, "utf-8");
  3376. },
  3377. saveFile: function (/*String*/fileName, /*String*/fileContents, /*String?*/encoding) {
  3378. //summary: saves a file.
  3379. var outFile = new java.io.File(fileName), outWriter, parentDir, os;
  3380. parentDir = outFile.getAbsoluteFile().getParentFile();
  3381. if (!parentDir.exists()) {
  3382. if (!parentDir.mkdirs()) {
  3383. throw "Could not create directory: " + parentDir.getAbsolutePath();
  3384. }
  3385. }
  3386. if (encoding) {
  3387. outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile), encoding);
  3388. } else {
  3389. outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile));
  3390. }
  3391. os = new java.io.BufferedWriter(outWriter);
  3392. try {
  3393. //If in Nashorn, need to coerce the JS string to a Java string so that
  3394. //writer.write method dispatch correctly detects the type.
  3395. if (typeof importPackage !== 'undefined') {
  3396. os.write(fileContents);
  3397. } else {
  3398. os.write(new java.lang.String(fileContents));
  3399. }
  3400. } finally {
  3401. os.close();
  3402. }
  3403. },
  3404. deleteFile: function (/*String*/fileName) {
  3405. //summary: deletes a file or directory if it exists.
  3406. var fileObj = new java.io.File(fileName), files, i;
  3407. if (fileObj.exists()) {
  3408. if (fileObj.isDirectory()) {
  3409. files = fileObj.listFiles();
  3410. for (i = 0; i < files.length; i++) {
  3411. this.deleteFile(files[i]);
  3412. }
  3413. }
  3414. fileObj["delete"]();
  3415. }
  3416. },
  3417. /**
  3418. * Deletes any empty directories under the given directory.
  3419. * The startDirIsJavaObject is private to this implementation's
  3420. * recursion needs.
  3421. */
  3422. deleteEmptyDirs: function (startDir, startDirIsJavaObject) {
  3423. var topDir = startDir,
  3424. dirFileArray, i, fileObj;
  3425. if (!startDirIsJavaObject) {
  3426. topDir = new java.io.File(startDir);
  3427. }
  3428. if (topDir.exists()) {
  3429. dirFileArray = topDir.listFiles();
  3430. for (i = 0; i < dirFileArray.length; i++) {
  3431. fileObj = dirFileArray[i];
  3432. if (fileObj.isDirectory()) {
  3433. file.deleteEmptyDirs(fileObj, true);
  3434. }
  3435. }
  3436. //If the directory is empty now, delete it.
  3437. if (topDir.listFiles().length === 0) {
  3438. file.deleteFile(String(topDir.getPath()));
  3439. }
  3440. }
  3441. }
  3442. };
  3443. return file;
  3444. });
  3445. }
  3446. if(env === 'xpconnect') {
  3447. //Helper functions to deal with file I/O.
  3448. /*jslint plusplus: false */
  3449. /*global define, Components, xpcUtil */
  3450. define('xpconnect/file', ['prim'], function (prim) {
  3451. var file,
  3452. Cc = Components.classes,
  3453. Ci = Components.interfaces,
  3454. //Depends on xpcUtil which is set up in x.js
  3455. xpfile = xpcUtil.xpfile;
  3456. function mkFullDir(dirObj) {
  3457. //1 is DIRECTORY_TYPE, 511 is 0777 permissions
  3458. if (!dirObj.exists()) {
  3459. dirObj.create(1, 511);
  3460. }
  3461. }
  3462. file = {
  3463. backSlashRegExp: /\\/g,
  3464. exclusionRegExp: /^\./,
  3465. getLineSeparator: function () {
  3466. return file.lineSeparator;
  3467. },
  3468. lineSeparator: ('@mozilla.org/windows-registry-key;1' in Cc) ?
  3469. '\r\n' : '\n',
  3470. exists: function (fileName) {
  3471. return xpfile(fileName).exists();
  3472. },
  3473. parent: function (fileName) {
  3474. return xpfile(fileName).parent;
  3475. },
  3476. normalize: function (fileName) {
  3477. return file.absPath(fileName);
  3478. },
  3479. isFile: function (path) {
  3480. return xpfile(path).isFile();
  3481. },
  3482. isDirectory: function (path) {
  3483. return xpfile(path).isDirectory();
  3484. },
  3485. /**
  3486. * Gets the absolute file path as a string, normalized
  3487. * to using front slashes for path separators.
  3488. * @param {java.io.File||String} file
  3489. */
  3490. absPath: function (fileObj) {
  3491. if (typeof fileObj === "string") {
  3492. fileObj = xpfile(fileObj);
  3493. }
  3494. return fileObj.path;
  3495. },
  3496. getFilteredFileList: function (/*String*/startDir, /*RegExp*/regExpFilters, /*boolean?*/makeUnixPaths, /*boolean?*/startDirIsObject) {
  3497. //summary: Recurses startDir and finds matches to the files that match regExpFilters.include
  3498. //and do not match regExpFilters.exclude. Or just one regexp can be passed in for regExpFilters,
  3499. //and it will be treated as the "include" case.
  3500. //Ignores files/directories that start with a period (.) unless exclusionRegExp
  3501. //is set to another value.
  3502. var files = [], topDir, regExpInclude, regExpExclude, dirFileArray,
  3503. fileObj, filePath, ok, dirFiles;
  3504. topDir = startDir;
  3505. if (!startDirIsObject) {
  3506. topDir = xpfile(startDir);
  3507. }
  3508. regExpInclude = regExpFilters.include || regExpFilters;
  3509. regExpExclude = regExpFilters.exclude || null;
  3510. if (topDir.exists()) {
  3511. dirFileArray = topDir.directoryEntries;
  3512. while (dirFileArray.hasMoreElements()) {
  3513. fileObj = dirFileArray.getNext().QueryInterface(Ci.nsILocalFile);
  3514. if (fileObj.isFile()) {
  3515. filePath = fileObj.path;
  3516. if (makeUnixPaths) {
  3517. if (filePath.indexOf("/") === -1) {
  3518. filePath = filePath.replace(/\\/g, "/");
  3519. }
  3520. }
  3521. ok = true;
  3522. if (regExpInclude) {
  3523. ok = filePath.match(regExpInclude);
  3524. }
  3525. if (ok && regExpExclude) {
  3526. ok = !filePath.match(regExpExclude);
  3527. }
  3528. if (ok && (!file.exclusionRegExp ||
  3529. !file.exclusionRegExp.test(fileObj.leafName))) {
  3530. files.push(filePath);
  3531. }
  3532. } else if (fileObj.isDirectory() &&
  3533. (!file.exclusionRegExp || !file.exclusionRegExp.test(fileObj.leafName))) {
  3534. dirFiles = this.getFilteredFileList(fileObj, regExpFilters, makeUnixPaths, true);
  3535. //Do not use push.apply for dir listings, can hit limit of max number
  3536. //of arguments to a function call, #921.
  3537. dirFiles.forEach(function (dirFile) {
  3538. files.push(dirFile);
  3539. });
  3540. }
  3541. }
  3542. }
  3543. return files; //Array
  3544. },
  3545. copyDir: function (/*String*/srcDir, /*String*/destDir, /*RegExp?*/regExpFilter, /*boolean?*/onlyCopyNew) {
  3546. //summary: copies files from srcDir to destDir using the regExpFilter to determine if the
  3547. //file should be copied. Returns a list file name strings of the destinations that were copied.
  3548. regExpFilter = regExpFilter || /\w/;
  3549. var fileNames = file.getFilteredFileList(srcDir, regExpFilter, true),
  3550. copiedFiles = [], i, srcFileName, destFileName;
  3551. for (i = 0; i < fileNames.length; i += 1) {
  3552. srcFileName = fileNames[i];
  3553. destFileName = srcFileName.replace(srcDir, destDir);
  3554. if (file.copyFile(srcFileName, destFileName, onlyCopyNew)) {
  3555. copiedFiles.push(destFileName);
  3556. }
  3557. }
  3558. return copiedFiles.length ? copiedFiles : null; //Array or null
  3559. },
  3560. copyFile: function (/*String*/srcFileName, /*String*/destFileName, /*boolean?*/onlyCopyNew) {
  3561. //summary: copies srcFileName to destFileName. If onlyCopyNew is set, it only copies the file if
  3562. //srcFileName is newer than destFileName. Returns a boolean indicating if the copy occurred.
  3563. var destFile = xpfile(destFileName),
  3564. srcFile = xpfile(srcFileName);
  3565. //logger.trace("Src filename: " + srcFileName);
  3566. //logger.trace("Dest filename: " + destFileName);
  3567. //If onlyCopyNew is true, then compare dates and only copy if the src is newer
  3568. //than dest.
  3569. if (onlyCopyNew) {
  3570. if (destFile.exists() && destFile.lastModifiedTime >= srcFile.lastModifiedTime) {
  3571. return false; //Boolean
  3572. }
  3573. }
  3574. srcFile.copyTo(destFile.parent, destFile.leafName);
  3575. return true; //Boolean
  3576. },
  3577. /**
  3578. * Renames a file. May fail if "to" already exists or is on another drive.
  3579. */
  3580. renameFile: function (from, to) {
  3581. var toFile = xpfile(to);
  3582. return xpfile(from).moveTo(toFile.parent, toFile.leafName);
  3583. },
  3584. readFile: xpcUtil.readFile,
  3585. readFileAsync: function (path, encoding) {
  3586. var d = prim();
  3587. try {
  3588. d.resolve(file.readFile(path, encoding));
  3589. } catch (e) {
  3590. d.reject(e);
  3591. }
  3592. return d.promise;
  3593. },
  3594. saveUtf8File: function (/*String*/fileName, /*String*/fileContents) {
  3595. //summary: saves a file using UTF-8 encoding.
  3596. file.saveFile(fileName, fileContents, "utf-8");
  3597. },
  3598. saveFile: function (/*String*/fileName, /*String*/fileContents, /*String?*/encoding) {
  3599. var outStream, convertStream,
  3600. fileObj = xpfile(fileName);
  3601. mkFullDir(fileObj.parent);
  3602. try {
  3603. outStream = Cc['@mozilla.org/network/file-output-stream;1']
  3604. .createInstance(Ci.nsIFileOutputStream);
  3605. //438 is decimal for 0777
  3606. outStream.init(fileObj, 0x02 | 0x08 | 0x20, 511, 0);
  3607. convertStream = Cc['@mozilla.org/intl/converter-output-stream;1']
  3608. .createInstance(Ci.nsIConverterOutputStream);
  3609. convertStream.init(outStream, encoding, 0, 0);
  3610. convertStream.writeString(fileContents);
  3611. } catch (e) {
  3612. throw new Error((fileObj && fileObj.path || '') + ': ' + e);
  3613. } finally {
  3614. if (convertStream) {
  3615. convertStream.close();
  3616. }
  3617. if (outStream) {
  3618. outStream.close();
  3619. }
  3620. }
  3621. },
  3622. deleteFile: function (/*String*/fileName) {
  3623. //summary: deletes a file or directory if it exists.
  3624. var fileObj = xpfile(fileName);
  3625. if (fileObj.exists()) {
  3626. fileObj.remove(true);
  3627. }
  3628. },
  3629. /**
  3630. * Deletes any empty directories under the given directory.
  3631. * The startDirIsJavaObject is private to this implementation's
  3632. * recursion needs.
  3633. */
  3634. deleteEmptyDirs: function (startDir, startDirIsObject) {
  3635. var topDir = startDir,
  3636. dirFileArray, fileObj;
  3637. if (!startDirIsObject) {
  3638. topDir = xpfile(startDir);
  3639. }
  3640. if (topDir.exists()) {
  3641. dirFileArray = topDir.directoryEntries;
  3642. while (dirFileArray.hasMoreElements()) {
  3643. fileObj = dirFileArray.getNext().QueryInterface(Ci.nsILocalFile);
  3644. if (fileObj.isDirectory()) {
  3645. file.deleteEmptyDirs(fileObj, true);
  3646. }
  3647. }
  3648. //If the directory is empty now, delete it.
  3649. dirFileArray = topDir.directoryEntries;
  3650. if (!dirFileArray.hasMoreElements()) {
  3651. file.deleteFile(topDir.path);
  3652. }
  3653. }
  3654. }
  3655. };
  3656. return file;
  3657. });
  3658. }
  3659. if(env === 'browser') {
  3660. /*global process */
  3661. define('browser/quit', function () {
  3662. 'use strict';
  3663. return function (code) {
  3664. };
  3665. });
  3666. }
  3667. if(env === 'node') {
  3668. /*global process */
  3669. define('node/quit', function () {
  3670. 'use strict';
  3671. return function (code) {
  3672. var draining = 0;
  3673. var exit = function () {
  3674. if (draining === 0) {
  3675. process.exit(code);
  3676. } else {
  3677. draining -= 1;
  3678. }
  3679. };
  3680. if (process.stdout.bufferSize) {
  3681. draining += 1;
  3682. process.stdout.once('drain', exit);
  3683. }
  3684. if (process.stderr.bufferSize) {
  3685. draining += 1;
  3686. process.stderr.once('drain', exit);
  3687. }
  3688. exit();
  3689. };
  3690. });
  3691. }
  3692. if(env === 'rhino') {
  3693. /*global quit */
  3694. define('rhino/quit', function () {
  3695. 'use strict';
  3696. return function (code) {
  3697. return quit(code);
  3698. };
  3699. });
  3700. }
  3701. if(env === 'xpconnect') {
  3702. /*global quit */
  3703. define('xpconnect/quit', function () {
  3704. 'use strict';
  3705. return function (code) {
  3706. return quit(code);
  3707. };
  3708. });
  3709. }
  3710. if(env === 'browser') {
  3711. /*jslint strict: false */
  3712. /*global define: false, console: false */
  3713. define('browser/print', function () {
  3714. function print(msg) {
  3715. console.log(msg);
  3716. }
  3717. return print;
  3718. });
  3719. }
  3720. if(env === 'node') {
  3721. /*jslint strict: false */
  3722. /*global define: false, console: false */
  3723. define('node/print', function () {
  3724. function print(msg) {
  3725. console.log(msg);
  3726. }
  3727. return print;
  3728. });
  3729. }
  3730. if(env === 'rhino') {
  3731. /*jslint strict: false */
  3732. /*global define: false, print: false */
  3733. define('rhino/print', function () {
  3734. return print;
  3735. });
  3736. }
  3737. if(env === 'xpconnect') {
  3738. /*jslint strict: false */
  3739. /*global define: false, print: false */
  3740. define('xpconnect/print', function () {
  3741. return print;
  3742. });
  3743. }
  3744. /*jslint nomen: false, strict: false */
  3745. /*global define: false */
  3746. define('logger', ['env!env/print'], function (print) {
  3747. var logger = {
  3748. TRACE: 0,
  3749. INFO: 1,
  3750. WARN: 2,
  3751. ERROR: 3,
  3752. SILENT: 4,
  3753. level: 0,
  3754. logPrefix: "",
  3755. logLevel: function( level ) {
  3756. this.level = level;
  3757. },
  3758. trace: function (message) {
  3759. if (this.level <= this.TRACE) {
  3760. this._print(message);
  3761. }
  3762. },
  3763. info: function (message) {
  3764. if (this.level <= this.INFO) {
  3765. this._print(message);
  3766. }
  3767. },
  3768. warn: function (message) {
  3769. if (this.level <= this.WARN) {
  3770. this._print(message);
  3771. }
  3772. },
  3773. error: function (message) {
  3774. if (this.level <= this.ERROR) {
  3775. this._print(message);
  3776. }
  3777. },
  3778. _print: function (message) {
  3779. this._sysPrint((this.logPrefix ? (this.logPrefix + " ") : "") + message);
  3780. },
  3781. _sysPrint: function (message) {
  3782. print(message);
  3783. }
  3784. };
  3785. return logger;
  3786. });
  3787. //Just a blank file to use when building the optimizer with the optimizer,
  3788. //so that the build does not attempt to inline some env modules,
  3789. //like Node's fs and path.
  3790. (function webpackUniversalModuleDefinition(root, factory) {
  3791. /* istanbul ignore next */
  3792. if(typeof define === 'function' && define.amd)
  3793. define('esprima', [], factory);
  3794. /* istanbul ignore next */
  3795. else if(typeof exports === 'object')
  3796. exports["esprima"] = factory();
  3797. else
  3798. root["esprima"] = factory();
  3799. })(this, function() {
  3800. return /******/ (function(modules) { // webpackBootstrap
  3801. /******/ // The module cache
  3802. /******/ var installedModules = {};
  3803. /******/ // The require function
  3804. /******/ function __webpack_require__(moduleId) {
  3805. /******/ // Check if module is in cache
  3806. /* istanbul ignore if */
  3807. /******/ if(installedModules[moduleId])
  3808. /******/ return installedModules[moduleId].exports;
  3809. /******/ // Create a new module (and put it into the cache)
  3810. /******/ var module = installedModules[moduleId] = {
  3811. /******/ exports: {},
  3812. /******/ id: moduleId,
  3813. /******/ loaded: false
  3814. /******/ };
  3815. /******/ // Execute the module function
  3816. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  3817. /******/ // Flag the module as loaded
  3818. /******/ module.loaded = true;
  3819. /******/ // Return the exports of the module
  3820. /******/ return module.exports;
  3821. /******/ }
  3822. /******/ // expose the modules object (__webpack_modules__)
  3823. /******/ __webpack_require__.m = modules;
  3824. /******/ // expose the module cache
  3825. /******/ __webpack_require__.c = installedModules;
  3826. /******/ // __webpack_public_path__
  3827. /******/ __webpack_require__.p = "";
  3828. /******/ // Load entry module and return exports
  3829. /******/ return __webpack_require__(0);
  3830. /******/ })
  3831. /************************************************************************/
  3832. /******/ ([
  3833. /* 0 */
  3834. /***/ function(module, exports, __webpack_require__) {
  3835. "use strict";
  3836. /*
  3837. Copyright JS Foundation and other contributors, https://js.foundation/
  3838. Redistribution and use in source and binary forms, with or without
  3839. modification, are permitted provided that the following conditions are met:
  3840. * Redistributions of source code must retain the above copyright
  3841. notice, this list of conditions and the following disclaimer.
  3842. * Redistributions in binary form must reproduce the above copyright
  3843. notice, this list of conditions and the following disclaimer in the
  3844. documentation and/or other materials provided with the distribution.
  3845. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  3846. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  3847. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  3848. ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
  3849. DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  3850. (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  3851. LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  3852. ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  3853. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  3854. THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  3855. */
  3856. Object.defineProperty(exports, "__esModule", { value: true });
  3857. var comment_handler_1 = __webpack_require__(1);
  3858. var jsx_parser_1 = __webpack_require__(3);
  3859. var parser_1 = __webpack_require__(8);
  3860. var tokenizer_1 = __webpack_require__(15);
  3861. function parse(code, options, delegate) {
  3862. var commentHandler = null;
  3863. var proxyDelegate = function (node, metadata) {
  3864. if (delegate) {
  3865. delegate(node, metadata);
  3866. }
  3867. if (commentHandler) {
  3868. commentHandler.visit(node, metadata);
  3869. }
  3870. };
  3871. var parserDelegate = (typeof delegate === 'function') ? proxyDelegate : null;
  3872. var collectComment = false;
  3873. if (options) {
  3874. collectComment = (typeof options.comment === 'boolean' && options.comment);
  3875. var attachComment = (typeof options.attachComment === 'boolean' && options.attachComment);
  3876. if (collectComment || attachComment) {
  3877. commentHandler = new comment_handler_1.CommentHandler();
  3878. commentHandler.attach = attachComment;
  3879. options.comment = true;
  3880. parserDelegate = proxyDelegate;
  3881. }
  3882. }
  3883. var isModule = false;
  3884. if (options && typeof options.sourceType === 'string') {
  3885. isModule = (options.sourceType === 'module');
  3886. }
  3887. var parser;
  3888. if (options && typeof options.jsx === 'boolean' && options.jsx) {
  3889. parser = new jsx_parser_1.JSXParser(code, options, parserDelegate);
  3890. }
  3891. else {
  3892. parser = new parser_1.Parser(code, options, parserDelegate);
  3893. }
  3894. var program = isModule ? parser.parseModule() : parser.parseScript();
  3895. var ast = program;
  3896. if (collectComment && commentHandler) {
  3897. ast.comments = commentHandler.comments;
  3898. }
  3899. if (parser.config.tokens) {
  3900. ast.tokens = parser.tokens;
  3901. }
  3902. if (parser.config.tolerant) {
  3903. ast.errors = parser.errorHandler.errors;
  3904. }
  3905. return ast;
  3906. }
  3907. exports.parse = parse;
  3908. function parseModule(code, options, delegate) {
  3909. var parsingOptions = options || {};
  3910. parsingOptions.sourceType = 'module';
  3911. return parse(code, parsingOptions, delegate);
  3912. }
  3913. exports.parseModule = parseModule;
  3914. function parseScript(code, options, delegate) {
  3915. var parsingOptions = options || {};
  3916. parsingOptions.sourceType = 'script';
  3917. return parse(code, parsingOptions, delegate);
  3918. }
  3919. exports.parseScript = parseScript;
  3920. function tokenize(code, options, delegate) {
  3921. var tokenizer = new tokenizer_1.Tokenizer(code, options);
  3922. var tokens;
  3923. tokens = [];
  3924. try {
  3925. while (true) {
  3926. var token = tokenizer.getNextToken();
  3927. if (!token) {
  3928. break;
  3929. }
  3930. if (delegate) {
  3931. token = delegate(token);
  3932. }
  3933. tokens.push(token);
  3934. }
  3935. }
  3936. catch (e) {
  3937. tokenizer.errorHandler.tolerate(e);
  3938. }
  3939. if (tokenizer.errorHandler.tolerant) {
  3940. tokens.errors = tokenizer.errors();
  3941. }
  3942. return tokens;
  3943. }
  3944. exports.tokenize = tokenize;
  3945. var syntax_1 = __webpack_require__(2);
  3946. exports.Syntax = syntax_1.Syntax;
  3947. // Sync with *.json manifests.
  3948. exports.version = '4.0.0';
  3949. /***/ },
  3950. /* 1 */
  3951. /***/ function(module, exports, __webpack_require__) {
  3952. "use strict";
  3953. Object.defineProperty(exports, "__esModule", { value: true });
  3954. var syntax_1 = __webpack_require__(2);
  3955. var CommentHandler = (function () {
  3956. function CommentHandler() {
  3957. this.attach = false;
  3958. this.comments = [];
  3959. this.stack = [];
  3960. this.leading = [];
  3961. this.trailing = [];
  3962. }
  3963. CommentHandler.prototype.insertInnerComments = function (node, metadata) {
  3964. // innnerComments for properties empty block
  3965. // `function a() {/** comments **\/}`
  3966. if (node.type === syntax_1.Syntax.BlockStatement && node.body.length === 0) {
  3967. var innerComments = [];
  3968. for (var i = this.leading.length - 1; i >= 0; --i) {
  3969. var entry = this.leading[i];
  3970. if (metadata.end.offset >= entry.start) {
  3971. innerComments.unshift(entry.comment);
  3972. this.leading.splice(i, 1);
  3973. this.trailing.splice(i, 1);
  3974. }
  3975. }
  3976. if (innerComments.length) {
  3977. node.innerComments = innerComments;
  3978. }
  3979. }
  3980. };
  3981. CommentHandler.prototype.findTrailingComments = function (metadata) {
  3982. var trailingComments = [];
  3983. if (this.trailing.length > 0) {
  3984. for (var i = this.trailing.length - 1; i >= 0; --i) {
  3985. var entry_1 = this.trailing[i];
  3986. if (entry_1.start >= metadata.end.offset) {
  3987. trailingComments.unshift(entry_1.comment);
  3988. }
  3989. }
  3990. this.trailing.length = 0;
  3991. return trailingComments;
  3992. }
  3993. var entry = this.stack[this.stack.length - 1];
  3994. if (entry && entry.node.trailingComments) {
  3995. var firstComment = entry.node.trailingComments[0];
  3996. if (firstComment && firstComment.range[0] >= metadata.end.offset) {
  3997. trailingComments = entry.node.trailingComments;
  3998. delete entry.node.trailingComments;
  3999. }
  4000. }
  4001. return trailingComments;
  4002. };
  4003. CommentHandler.prototype.findLeadingComments = function (metadata) {
  4004. var leadingComments = [];
  4005. var target;
  4006. while (this.stack.length > 0) {
  4007. var entry = this.stack[this.stack.length - 1];
  4008. if (entry && entry.start >= metadata.start.offset) {
  4009. target = entry.node;
  4010. this.stack.pop();
  4011. }
  4012. else {
  4013. break;
  4014. }
  4015. }
  4016. if (target) {
  4017. var count = target.leadingComments ? target.leadingComments.length : 0;
  4018. for (var i = count - 1; i >= 0; --i) {
  4019. var comment = target.leadingComments[i];
  4020. if (comment.range[1] <= metadata.start.offset) {
  4021. leadingComments.unshift(comment);
  4022. target.leadingComments.splice(i, 1);
  4023. }
  4024. }
  4025. if (target.leadingComments && target.leadingComments.length === 0) {
  4026. delete target.leadingComments;
  4027. }
  4028. return leadingComments;
  4029. }
  4030. for (var i = this.leading.length - 1; i >= 0; --i) {
  4031. var entry = this.leading[i];
  4032. if (entry.start <= metadata.start.offset) {
  4033. leadingComments.unshift(entry.comment);
  4034. this.leading.splice(i, 1);
  4035. }
  4036. }
  4037. return leadingComments;
  4038. };
  4039. CommentHandler.prototype.visitNode = function (node, metadata) {
  4040. if (node.type === syntax_1.Syntax.Program && node.body.length > 0) {
  4041. return;
  4042. }
  4043. this.insertInnerComments(node, metadata);
  4044. var trailingComments = this.findTrailingComments(metadata);
  4045. var leadingComments = this.findLeadingComments(metadata);
  4046. if (leadingComments.length > 0) {
  4047. node.leadingComments = leadingComments;
  4048. }
  4049. if (trailingComments.length > 0) {
  4050. node.trailingComments = trailingComments;
  4051. }
  4052. this.stack.push({
  4053. node: node,
  4054. start: metadata.start.offset
  4055. });
  4056. };
  4057. CommentHandler.prototype.visitComment = function (node, metadata) {
  4058. var type = (node.type[0] === 'L') ? 'Line' : 'Block';
  4059. var comment = {
  4060. type: type,
  4061. value: node.value
  4062. };
  4063. if (node.range) {
  4064. comment.range = node.range;
  4065. }
  4066. if (node.loc) {
  4067. comment.loc = node.loc;
  4068. }
  4069. this.comments.push(comment);
  4070. if (this.attach) {
  4071. var entry = {
  4072. comment: {
  4073. type: type,
  4074. value: node.value,
  4075. range: [metadata.start.offset, metadata.end.offset]
  4076. },
  4077. start: metadata.start.offset
  4078. };
  4079. if (node.loc) {
  4080. entry.comment.loc = node.loc;
  4081. }
  4082. node.type = type;
  4083. this.leading.push(entry);
  4084. this.trailing.push(entry);
  4085. }
  4086. };
  4087. CommentHandler.prototype.visit = function (node, metadata) {
  4088. if (node.type === 'LineComment') {
  4089. this.visitComment(node, metadata);
  4090. }
  4091. else if (node.type === 'BlockComment') {
  4092. this.visitComment(node, metadata);
  4093. }
  4094. else if (this.attach) {
  4095. this.visitNode(node, metadata);
  4096. }
  4097. };
  4098. return CommentHandler;
  4099. }());
  4100. exports.CommentHandler = CommentHandler;
  4101. /***/ },
  4102. /* 2 */
  4103. /***/ function(module, exports) {
  4104. "use strict";
  4105. Object.defineProperty(exports, "__esModule", { value: true });
  4106. exports.Syntax = {
  4107. AssignmentExpression: 'AssignmentExpression',
  4108. AssignmentPattern: 'AssignmentPattern',
  4109. ArrayExpression: 'ArrayExpression',
  4110. ArrayPattern: 'ArrayPattern',
  4111. ArrowFunctionExpression: 'ArrowFunctionExpression',
  4112. AwaitExpression: 'AwaitExpression',
  4113. BlockStatement: 'BlockStatement',
  4114. BinaryExpression: 'BinaryExpression',
  4115. BreakStatement: 'BreakStatement',
  4116. CallExpression: 'CallExpression',
  4117. CatchClause: 'CatchClause',
  4118. ClassBody: 'ClassBody',
  4119. ClassDeclaration: 'ClassDeclaration',
  4120. ClassExpression: 'ClassExpression',
  4121. ConditionalExpression: 'ConditionalExpression',
  4122. ContinueStatement: 'ContinueStatement',
  4123. DoWhileStatement: 'DoWhileStatement',
  4124. DebuggerStatement: 'DebuggerStatement',
  4125. EmptyStatement: 'EmptyStatement',
  4126. ExportAllDeclaration: 'ExportAllDeclaration',
  4127. ExportDefaultDeclaration: 'ExportDefaultDeclaration',
  4128. ExportNamedDeclaration: 'ExportNamedDeclaration',
  4129. ExportSpecifier: 'ExportSpecifier',
  4130. ExpressionStatement: 'ExpressionStatement',
  4131. ForStatement: 'ForStatement',
  4132. ForOfStatement: 'ForOfStatement',
  4133. ForInStatement: 'ForInStatement',
  4134. FunctionDeclaration: 'FunctionDeclaration',
  4135. FunctionExpression: 'FunctionExpression',
  4136. Identifier: 'Identifier',
  4137. IfStatement: 'IfStatement',
  4138. ImportDeclaration: 'ImportDeclaration',
  4139. ImportDefaultSpecifier: 'ImportDefaultSpecifier',
  4140. ImportNamespaceSpecifier: 'ImportNamespaceSpecifier',
  4141. ImportSpecifier: 'ImportSpecifier',
  4142. Literal: 'Literal',
  4143. LabeledStatement: 'LabeledStatement',
  4144. LogicalExpression: 'LogicalExpression',
  4145. MemberExpression: 'MemberExpression',
  4146. MetaProperty: 'MetaProperty',
  4147. MethodDefinition: 'MethodDefinition',
  4148. NewExpression: 'NewExpression',
  4149. ObjectExpression: 'ObjectExpression',
  4150. ObjectPattern: 'ObjectPattern',
  4151. Program: 'Program',
  4152. Property: 'Property',
  4153. RestElement: 'RestElement',
  4154. ReturnStatement: 'ReturnStatement',
  4155. SequenceExpression: 'SequenceExpression',
  4156. SpreadElement: 'SpreadElement',
  4157. Super: 'Super',
  4158. SwitchCase: 'SwitchCase',
  4159. SwitchStatement: 'SwitchStatement',
  4160. TaggedTemplateExpression: 'TaggedTemplateExpression',
  4161. TemplateElement: 'TemplateElement',
  4162. TemplateLiteral: 'TemplateLiteral',
  4163. ThisExpression: 'ThisExpression',
  4164. ThrowStatement: 'ThrowStatement',
  4165. TryStatement: 'TryStatement',
  4166. UnaryExpression: 'UnaryExpression',
  4167. UpdateExpression: 'UpdateExpression',
  4168. VariableDeclaration: 'VariableDeclaration',
  4169. VariableDeclarator: 'VariableDeclarator',
  4170. WhileStatement: 'WhileStatement',
  4171. WithStatement: 'WithStatement',
  4172. YieldExpression: 'YieldExpression'
  4173. };
  4174. /***/ },
  4175. /* 3 */
  4176. /***/ function(module, exports, __webpack_require__) {
  4177. "use strict";
  4178. /* istanbul ignore next */
  4179. var __extends = (this && this.__extends) || (function () {
  4180. var extendStatics = Object.setPrototypeOf ||
  4181. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  4182. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  4183. return function (d, b) {
  4184. extendStatics(d, b);
  4185. function __() { this.constructor = d; }
  4186. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  4187. };
  4188. })();
  4189. Object.defineProperty(exports, "__esModule", { value: true });
  4190. var character_1 = __webpack_require__(4);
  4191. var JSXNode = __webpack_require__(5);
  4192. var jsx_syntax_1 = __webpack_require__(6);
  4193. var Node = __webpack_require__(7);
  4194. var parser_1 = __webpack_require__(8);
  4195. var token_1 = __webpack_require__(13);
  4196. var xhtml_entities_1 = __webpack_require__(14);
  4197. token_1.TokenName[100 /* Identifier */] = 'JSXIdentifier';
  4198. token_1.TokenName[101 /* Text */] = 'JSXText';
  4199. // Fully qualified element name, e.g. <svg:path> returns "svg:path"
  4200. function getQualifiedElementName(elementName) {
  4201. var qualifiedName;
  4202. switch (elementName.type) {
  4203. case jsx_syntax_1.JSXSyntax.JSXIdentifier:
  4204. var id = elementName;
  4205. qualifiedName = id.name;
  4206. break;
  4207. case jsx_syntax_1.JSXSyntax.JSXNamespacedName:
  4208. var ns = elementName;
  4209. qualifiedName = getQualifiedElementName(ns.namespace) + ':' +
  4210. getQualifiedElementName(ns.name);
  4211. break;
  4212. case jsx_syntax_1.JSXSyntax.JSXMemberExpression:
  4213. var expr = elementName;
  4214. qualifiedName = getQualifiedElementName(expr.object) + '.' +
  4215. getQualifiedElementName(expr.property);
  4216. break;
  4217. /* istanbul ignore next */
  4218. default:
  4219. break;
  4220. }
  4221. return qualifiedName;
  4222. }
  4223. var JSXParser = (function (_super) {
  4224. __extends(JSXParser, _super);
  4225. function JSXParser(code, options, delegate) {
  4226. return _super.call(this, code, options, delegate) || this;
  4227. }
  4228. JSXParser.prototype.parsePrimaryExpression = function () {
  4229. return this.match('<') ? this.parseJSXRoot() : _super.prototype.parsePrimaryExpression.call(this);
  4230. };
  4231. JSXParser.prototype.startJSX = function () {
  4232. // Unwind the scanner before the lookahead token.
  4233. this.scanner.index = this.startMarker.index;
  4234. this.scanner.lineNumber = this.startMarker.line;
  4235. this.scanner.lineStart = this.startMarker.index - this.startMarker.column;
  4236. };
  4237. JSXParser.prototype.finishJSX = function () {
  4238. // Prime the next lookahead.
  4239. this.nextToken();
  4240. };
  4241. JSXParser.prototype.reenterJSX = function () {
  4242. this.startJSX();
  4243. this.expectJSX('}');
  4244. // Pop the closing '}' added from the lookahead.
  4245. if (this.config.tokens) {
  4246. this.tokens.pop();
  4247. }
  4248. };
  4249. JSXParser.prototype.createJSXNode = function () {
  4250. this.collectComments();
  4251. return {
  4252. index: this.scanner.index,
  4253. line: this.scanner.lineNumber,
  4254. column: this.scanner.index - this.scanner.lineStart
  4255. };
  4256. };
  4257. JSXParser.prototype.createJSXChildNode = function () {
  4258. return {
  4259. index: this.scanner.index,
  4260. line: this.scanner.lineNumber,
  4261. column: this.scanner.index - this.scanner.lineStart
  4262. };
  4263. };
  4264. JSXParser.prototype.scanXHTMLEntity = function (quote) {
  4265. var result = '&';
  4266. var valid = true;
  4267. var terminated = false;
  4268. var numeric = false;
  4269. var hex = false;
  4270. while (!this.scanner.eof() && valid && !terminated) {
  4271. var ch = this.scanner.source[this.scanner.index];
  4272. if (ch === quote) {
  4273. break;
  4274. }
  4275. terminated = (ch === ';');
  4276. result += ch;
  4277. ++this.scanner.index;
  4278. if (!terminated) {
  4279. switch (result.length) {
  4280. case 2:
  4281. // e.g. '&#123;'
  4282. numeric = (ch === '#');
  4283. break;
  4284. case 3:
  4285. if (numeric) {
  4286. // e.g. '&#x41;'
  4287. hex = (ch === 'x');
  4288. valid = hex || character_1.Character.isDecimalDigit(ch.charCodeAt(0));
  4289. numeric = numeric && !hex;
  4290. }
  4291. break;
  4292. default:
  4293. valid = valid && !(numeric && !character_1.Character.isDecimalDigit(ch.charCodeAt(0)));
  4294. valid = valid && !(hex && !character_1.Character.isHexDigit(ch.charCodeAt(0)));
  4295. break;
  4296. }
  4297. }
  4298. }
  4299. if (valid && terminated && result.length > 2) {
  4300. // e.g. '&#x41;' becomes just '#x41'
  4301. var str = result.substr(1, result.length - 2);
  4302. if (numeric && str.length > 1) {
  4303. result = String.fromCharCode(parseInt(str.substr(1), 10));
  4304. }
  4305. else if (hex && str.length > 2) {
  4306. result = String.fromCharCode(parseInt('0' + str.substr(1), 16));
  4307. }
  4308. else if (!numeric && !hex && xhtml_entities_1.XHTMLEntities[str]) {
  4309. result = xhtml_entities_1.XHTMLEntities[str];
  4310. }
  4311. }
  4312. return result;
  4313. };
  4314. // Scan the next JSX token. This replaces Scanner#lex when in JSX mode.
  4315. JSXParser.prototype.lexJSX = function () {
  4316. var cp = this.scanner.source.charCodeAt(this.scanner.index);
  4317. // < > / : = { }
  4318. if (cp === 60 || cp === 62 || cp === 47 || cp === 58 || cp === 61 || cp === 123 || cp === 125) {
  4319. var value = this.scanner.source[this.scanner.index++];
  4320. return {
  4321. type: 7 /* Punctuator */,
  4322. value: value,
  4323. lineNumber: this.scanner.lineNumber,
  4324. lineStart: this.scanner.lineStart,
  4325. start: this.scanner.index - 1,
  4326. end: this.scanner.index
  4327. };
  4328. }
  4329. // " '
  4330. if (cp === 34 || cp === 39) {
  4331. var start = this.scanner.index;
  4332. var quote = this.scanner.source[this.scanner.index++];
  4333. var str = '';
  4334. while (!this.scanner.eof()) {
  4335. var ch = this.scanner.source[this.scanner.index++];
  4336. if (ch === quote) {
  4337. break;
  4338. }
  4339. else if (ch === '&') {
  4340. str += this.scanXHTMLEntity(quote);
  4341. }
  4342. else {
  4343. str += ch;
  4344. }
  4345. }
  4346. return {
  4347. type: 8 /* StringLiteral */,
  4348. value: str,
  4349. lineNumber: this.scanner.lineNumber,
  4350. lineStart: this.scanner.lineStart,
  4351. start: start,
  4352. end: this.scanner.index
  4353. };
  4354. }
  4355. // ... or .
  4356. if (cp === 46) {
  4357. var n1 = this.scanner.source.charCodeAt(this.scanner.index + 1);
  4358. var n2 = this.scanner.source.charCodeAt(this.scanner.index + 2);
  4359. var value = (n1 === 46 && n2 === 46) ? '...' : '.';
  4360. var start = this.scanner.index;
  4361. this.scanner.index += value.length;
  4362. return {
  4363. type: 7 /* Punctuator */,
  4364. value: value,
  4365. lineNumber: this.scanner.lineNumber,
  4366. lineStart: this.scanner.lineStart,
  4367. start: start,
  4368. end: this.scanner.index
  4369. };
  4370. }
  4371. // `
  4372. if (cp === 96) {
  4373. // Only placeholder, since it will be rescanned as a real assignment expression.
  4374. return {
  4375. type: 10 /* Template */,
  4376. value: '',
  4377. lineNumber: this.scanner.lineNumber,
  4378. lineStart: this.scanner.lineStart,
  4379. start: this.scanner.index,
  4380. end: this.scanner.index
  4381. };
  4382. }
  4383. // Identifer can not contain backslash (char code 92).
  4384. if (character_1.Character.isIdentifierStart(cp) && (cp !== 92)) {
  4385. var start = this.scanner.index;
  4386. ++this.scanner.index;
  4387. while (!this.scanner.eof()) {
  4388. var ch = this.scanner.source.charCodeAt(this.scanner.index);
  4389. if (character_1.Character.isIdentifierPart(ch) && (ch !== 92)) {
  4390. ++this.scanner.index;
  4391. }
  4392. else if (ch === 45) {
  4393. // Hyphen (char code 45) can be part of an identifier.
  4394. ++this.scanner.index;
  4395. }
  4396. else {
  4397. break;
  4398. }
  4399. }
  4400. var id = this.scanner.source.slice(start, this.scanner.index);
  4401. return {
  4402. type: 100 /* Identifier */,
  4403. value: id,
  4404. lineNumber: this.scanner.lineNumber,
  4405. lineStart: this.scanner.lineStart,
  4406. start: start,
  4407. end: this.scanner.index
  4408. };
  4409. }
  4410. return this.scanner.lex();
  4411. };
  4412. JSXParser.prototype.nextJSXToken = function () {
  4413. this.collectComments();
  4414. this.startMarker.index = this.scanner.index;
  4415. this.startMarker.line = this.scanner.lineNumber;
  4416. this.startMarker.column = this.scanner.index - this.scanner.lineStart;
  4417. var token = this.lexJSX();
  4418. this.lastMarker.index = this.scanner.index;
  4419. this.lastMarker.line = this.scanner.lineNumber;
  4420. this.lastMarker.column = this.scanner.index - this.scanner.lineStart;
  4421. if (this.config.tokens) {
  4422. this.tokens.push(this.convertToken(token));
  4423. }
  4424. return token;
  4425. };
  4426. JSXParser.prototype.nextJSXText = function () {
  4427. this.startMarker.index = this.scanner.index;
  4428. this.startMarker.line = this.scanner.lineNumber;
  4429. this.startMarker.column = this.scanner.index - this.scanner.lineStart;
  4430. var start = this.scanner.index;
  4431. var text = '';
  4432. while (!this.scanner.eof()) {
  4433. var ch = this.scanner.source[this.scanner.index];
  4434. if (ch === '{' || ch === '<') {
  4435. break;
  4436. }
  4437. ++this.scanner.index;
  4438. text += ch;
  4439. if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
  4440. ++this.scanner.lineNumber;
  4441. if (ch === '\r' && this.scanner.source[this.scanner.index] === '\n') {
  4442. ++this.scanner.index;
  4443. }
  4444. this.scanner.lineStart = this.scanner.index;
  4445. }
  4446. }
  4447. this.lastMarker.index = this.scanner.index;
  4448. this.lastMarker.line = this.scanner.lineNumber;
  4449. this.lastMarker.column = this.scanner.index - this.scanner.lineStart;
  4450. var token = {
  4451. type: 101 /* Text */,
  4452. value: text,
  4453. lineNumber: this.scanner.lineNumber,
  4454. lineStart: this.scanner.lineStart,
  4455. start: start,
  4456. end: this.scanner.index
  4457. };
  4458. if ((text.length > 0) && this.config.tokens) {
  4459. this.tokens.push(this.convertToken(token));
  4460. }
  4461. return token;
  4462. };
  4463. JSXParser.prototype.peekJSXToken = function () {
  4464. var state = this.scanner.saveState();
  4465. this.scanner.scanComments();
  4466. var next = this.lexJSX();
  4467. this.scanner.restoreState(state);
  4468. return next;
  4469. };
  4470. // Expect the next JSX token to match the specified punctuator.
  4471. // If not, an exception will be thrown.
  4472. JSXParser.prototype.expectJSX = function (value) {
  4473. var token = this.nextJSXToken();
  4474. if (token.type !== 7 /* Punctuator */ || token.value !== value) {
  4475. this.throwUnexpectedToken(token);
  4476. }
  4477. };
  4478. // Return true if the next JSX token matches the specified punctuator.
  4479. JSXParser.prototype.matchJSX = function (value) {
  4480. var next = this.peekJSXToken();
  4481. return next.type === 7 /* Punctuator */ && next.value === value;
  4482. };
  4483. JSXParser.prototype.parseJSXIdentifier = function () {
  4484. var node = this.createJSXNode();
  4485. var token = this.nextJSXToken();
  4486. if (token.type !== 100 /* Identifier */) {
  4487. this.throwUnexpectedToken(token);
  4488. }
  4489. return this.finalize(node, new JSXNode.JSXIdentifier(token.value));
  4490. };
  4491. JSXParser.prototype.parseJSXElementName = function () {
  4492. var node = this.createJSXNode();
  4493. var elementName = this.parseJSXIdentifier();
  4494. if (this.matchJSX(':')) {
  4495. var namespace = elementName;
  4496. this.expectJSX(':');
  4497. var name_1 = this.parseJSXIdentifier();
  4498. elementName = this.finalize(node, new JSXNode.JSXNamespacedName(namespace, name_1));
  4499. }
  4500. else if (this.matchJSX('.')) {
  4501. while (this.matchJSX('.')) {
  4502. var object = elementName;
  4503. this.expectJSX('.');
  4504. var property = this.parseJSXIdentifier();
  4505. elementName = this.finalize(node, new JSXNode.JSXMemberExpression(object, property));
  4506. }
  4507. }
  4508. return elementName;
  4509. };
  4510. JSXParser.prototype.parseJSXAttributeName = function () {
  4511. var node = this.createJSXNode();
  4512. var attributeName;
  4513. var identifier = this.parseJSXIdentifier();
  4514. if (this.matchJSX(':')) {
  4515. var namespace = identifier;
  4516. this.expectJSX(':');
  4517. var name_2 = this.parseJSXIdentifier();
  4518. attributeName = this.finalize(node, new JSXNode.JSXNamespacedName(namespace, name_2));
  4519. }
  4520. else {
  4521. attributeName = identifier;
  4522. }
  4523. return attributeName;
  4524. };
  4525. JSXParser.prototype.parseJSXStringLiteralAttribute = function () {
  4526. var node = this.createJSXNode();
  4527. var token = this.nextJSXToken();
  4528. if (token.type !== 8 /* StringLiteral */) {
  4529. this.throwUnexpectedToken(token);
  4530. }
  4531. var raw = this.getTokenRaw(token);
  4532. return this.finalize(node, new Node.Literal(token.value, raw));
  4533. };
  4534. JSXParser.prototype.parseJSXExpressionAttribute = function () {
  4535. var node = this.createJSXNode();
  4536. this.expectJSX('{');
  4537. this.finishJSX();
  4538. if (this.match('}')) {
  4539. this.tolerateError('JSX attributes must only be assigned a non-empty expression');
  4540. }
  4541. var expression = this.parseAssignmentExpression();
  4542. this.reenterJSX();
  4543. return this.finalize(node, new JSXNode.JSXExpressionContainer(expression));
  4544. };
  4545. JSXParser.prototype.parseJSXAttributeValue = function () {
  4546. return this.matchJSX('{') ? this.parseJSXExpressionAttribute() :
  4547. this.matchJSX('<') ? this.parseJSXElement() : this.parseJSXStringLiteralAttribute();
  4548. };
  4549. JSXParser.prototype.parseJSXNameValueAttribute = function () {
  4550. var node = this.createJSXNode();
  4551. var name = this.parseJSXAttributeName();
  4552. var value = null;
  4553. if (this.matchJSX('=')) {
  4554. this.expectJSX('=');
  4555. value = this.parseJSXAttributeValue();
  4556. }
  4557. return this.finalize(node, new JSXNode.JSXAttribute(name, value));
  4558. };
  4559. JSXParser.prototype.parseJSXSpreadAttribute = function () {
  4560. var node = this.createJSXNode();
  4561. this.expectJSX('{');
  4562. this.expectJSX('...');
  4563. this.finishJSX();
  4564. var argument = this.parseAssignmentExpression();
  4565. this.reenterJSX();
  4566. return this.finalize(node, new JSXNode.JSXSpreadAttribute(argument));
  4567. };
  4568. JSXParser.prototype.parseJSXAttributes = function () {
  4569. var attributes = [];
  4570. while (!this.matchJSX('/') && !this.matchJSX('>')) {
  4571. var attribute = this.matchJSX('{') ? this.parseJSXSpreadAttribute() :
  4572. this.parseJSXNameValueAttribute();
  4573. attributes.push(attribute);
  4574. }
  4575. return attributes;
  4576. };
  4577. JSXParser.prototype.parseJSXOpeningElement = function () {
  4578. var node = this.createJSXNode();
  4579. this.expectJSX('<');
  4580. var name = this.parseJSXElementName();
  4581. var attributes = this.parseJSXAttributes();
  4582. var selfClosing = this.matchJSX('/');
  4583. if (selfClosing) {
  4584. this.expectJSX('/');
  4585. }
  4586. this.expectJSX('>');
  4587. return this.finalize(node, new JSXNode.JSXOpeningElement(name, selfClosing, attributes));
  4588. };
  4589. JSXParser.prototype.parseJSXBoundaryElement = function () {
  4590. var node = this.createJSXNode();
  4591. this.expectJSX('<');
  4592. if (this.matchJSX('/')) {
  4593. this.expectJSX('/');
  4594. var name_3 = this.parseJSXElementName();
  4595. this.expectJSX('>');
  4596. return this.finalize(node, new JSXNode.JSXClosingElement(name_3));
  4597. }
  4598. var name = this.parseJSXElementName();
  4599. var attributes = this.parseJSXAttributes();
  4600. var selfClosing = this.matchJSX('/');
  4601. if (selfClosing) {
  4602. this.expectJSX('/');
  4603. }
  4604. this.expectJSX('>');
  4605. return this.finalize(node, new JSXNode.JSXOpeningElement(name, selfClosing, attributes));
  4606. };
  4607. JSXParser.prototype.parseJSXEmptyExpression = function () {
  4608. var node = this.createJSXChildNode();
  4609. this.collectComments();
  4610. this.lastMarker.index = this.scanner.index;
  4611. this.lastMarker.line = this.scanner.lineNumber;
  4612. this.lastMarker.column = this.scanner.index - this.scanner.lineStart;
  4613. return this.finalize(node, new JSXNode.JSXEmptyExpression());
  4614. };
  4615. JSXParser.prototype.parseJSXExpressionContainer = function () {
  4616. var node = this.createJSXNode();
  4617. this.expectJSX('{');
  4618. var expression;
  4619. if (this.matchJSX('}')) {
  4620. expression = this.parseJSXEmptyExpression();
  4621. this.expectJSX('}');
  4622. }
  4623. else {
  4624. this.finishJSX();
  4625. expression = this.parseAssignmentExpression();
  4626. this.reenterJSX();
  4627. }
  4628. return this.finalize(node, new JSXNode.JSXExpressionContainer(expression));
  4629. };
  4630. JSXParser.prototype.parseJSXChildren = function () {
  4631. var children = [];
  4632. while (!this.scanner.eof()) {
  4633. var node = this.createJSXChildNode();
  4634. var token = this.nextJSXText();
  4635. if (token.start < token.end) {
  4636. var raw = this.getTokenRaw(token);
  4637. var child = this.finalize(node, new JSXNode.JSXText(token.value, raw));
  4638. children.push(child);
  4639. }
  4640. if (this.scanner.source[this.scanner.index] === '{') {
  4641. var container = this.parseJSXExpressionContainer();
  4642. children.push(container);
  4643. }
  4644. else {
  4645. break;
  4646. }
  4647. }
  4648. return children;
  4649. };
  4650. JSXParser.prototype.parseComplexJSXElement = function (el) {
  4651. var stack = [];
  4652. while (!this.scanner.eof()) {
  4653. el.children = el.children.concat(this.parseJSXChildren());
  4654. var node = this.createJSXChildNode();
  4655. var element = this.parseJSXBoundaryElement();
  4656. if (element.type === jsx_syntax_1.JSXSyntax.JSXOpeningElement) {
  4657. var opening = element;
  4658. if (opening.selfClosing) {
  4659. var child = this.finalize(node, new JSXNode.JSXElement(opening, [], null));
  4660. el.children.push(child);
  4661. }
  4662. else {
  4663. stack.push(el);
  4664. el = { node: node, opening: opening, closing: null, children: [] };
  4665. }
  4666. }
  4667. if (element.type === jsx_syntax_1.JSXSyntax.JSXClosingElement) {
  4668. el.closing = element;
  4669. var open_1 = getQualifiedElementName(el.opening.name);
  4670. var close_1 = getQualifiedElementName(el.closing.name);
  4671. if (open_1 !== close_1) {
  4672. this.tolerateError('Expected corresponding JSX closing tag for %0', open_1);
  4673. }
  4674. if (stack.length > 0) {
  4675. var child = this.finalize(el.node, new JSXNode.JSXElement(el.opening, el.children, el.closing));
  4676. el = stack[stack.length - 1];
  4677. el.children.push(child);
  4678. stack.pop();
  4679. }
  4680. else {
  4681. break;
  4682. }
  4683. }
  4684. }
  4685. return el;
  4686. };
  4687. JSXParser.prototype.parseJSXElement = function () {
  4688. var node = this.createJSXNode();
  4689. var opening = this.parseJSXOpeningElement();
  4690. var children = [];
  4691. var closing = null;
  4692. if (!opening.selfClosing) {
  4693. var el = this.parseComplexJSXElement({ node: node, opening: opening, closing: closing, children: children });
  4694. children = el.children;
  4695. closing = el.closing;
  4696. }
  4697. return this.finalize(node, new JSXNode.JSXElement(opening, children, closing));
  4698. };
  4699. JSXParser.prototype.parseJSXRoot = function () {
  4700. // Pop the opening '<' added from the lookahead.
  4701. if (this.config.tokens) {
  4702. this.tokens.pop();
  4703. }
  4704. this.startJSX();
  4705. var element = this.parseJSXElement();
  4706. this.finishJSX();
  4707. return element;
  4708. };
  4709. JSXParser.prototype.isStartOfExpression = function () {
  4710. return _super.prototype.isStartOfExpression.call(this) || this.match('<');
  4711. };
  4712. return JSXParser;
  4713. }(parser_1.Parser));
  4714. exports.JSXParser = JSXParser;
  4715. /***/ },
  4716. /* 4 */
  4717. /***/ function(module, exports) {
  4718. "use strict";
  4719. Object.defineProperty(exports, "__esModule", { value: true });
  4720. // See also tools/generate-unicode-regex.js.
  4721. var Regex = {
  4722. // Unicode v8.0.0 NonAsciiIdentifierStart:
  4723. 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-\u08B4\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\u0AF9\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-\u0C5A\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\u0D5F-\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-\u13F5\u13F8-\u13FD\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\u19B0-\u19C9\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-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\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-\uAB65\uAB70-\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\uDCE0-\uDCF2\uDCF4\uDCF5\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\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\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\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]/,
  4724. // Unicode v8.0.0 NonAsciiIdentifierPart:
  4725. 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-\u08B4\u08E3-\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\u0AF9\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-\u0C5A\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\u0D5F-\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-\u13F5\u13F8-\u13FD\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-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\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-\uAB65\uAB70-\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-\uFE2F\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\uDCE0-\uDCF2\uDCF4\uDCF5\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\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\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]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\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\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/
  4726. };
  4727. exports.Character = {
  4728. /* tslint:disable:no-bitwise */
  4729. fromCodePoint: function (cp) {
  4730. return (cp < 0x10000) ? String.fromCharCode(cp) :
  4731. String.fromCharCode(0xD800 + ((cp - 0x10000) >> 10)) +
  4732. String.fromCharCode(0xDC00 + ((cp - 0x10000) & 1023));
  4733. },
  4734. // https://tc39.github.io/ecma262/#sec-white-space
  4735. isWhiteSpace: function (cp) {
  4736. return (cp === 0x20) || (cp === 0x09) || (cp === 0x0B) || (cp === 0x0C) || (cp === 0xA0) ||
  4737. (cp >= 0x1680 && [0x1680, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF].indexOf(cp) >= 0);
  4738. },
  4739. // https://tc39.github.io/ecma262/#sec-line-terminators
  4740. isLineTerminator: function (cp) {
  4741. return (cp === 0x0A) || (cp === 0x0D) || (cp === 0x2028) || (cp === 0x2029);
  4742. },
  4743. // https://tc39.github.io/ecma262/#sec-names-and-keywords
  4744. isIdentifierStart: function (cp) {
  4745. return (cp === 0x24) || (cp === 0x5F) ||
  4746. (cp >= 0x41 && cp <= 0x5A) ||
  4747. (cp >= 0x61 && cp <= 0x7A) ||
  4748. (cp === 0x5C) ||
  4749. ((cp >= 0x80) && Regex.NonAsciiIdentifierStart.test(exports.Character.fromCodePoint(cp)));
  4750. },
  4751. isIdentifierPart: function (cp) {
  4752. return (cp === 0x24) || (cp === 0x5F) ||
  4753. (cp >= 0x41 && cp <= 0x5A) ||
  4754. (cp >= 0x61 && cp <= 0x7A) ||
  4755. (cp >= 0x30 && cp <= 0x39) ||
  4756. (cp === 0x5C) ||
  4757. ((cp >= 0x80) && Regex.NonAsciiIdentifierPart.test(exports.Character.fromCodePoint(cp)));
  4758. },
  4759. // https://tc39.github.io/ecma262/#sec-literals-numeric-literals
  4760. isDecimalDigit: function (cp) {
  4761. return (cp >= 0x30 && cp <= 0x39); // 0..9
  4762. },
  4763. isHexDigit: function (cp) {
  4764. return (cp >= 0x30 && cp <= 0x39) ||
  4765. (cp >= 0x41 && cp <= 0x46) ||
  4766. (cp >= 0x61 && cp <= 0x66); // a..f
  4767. },
  4768. isOctalDigit: function (cp) {
  4769. return (cp >= 0x30 && cp <= 0x37); // 0..7
  4770. }
  4771. };
  4772. /***/ },
  4773. /* 5 */
  4774. /***/ function(module, exports, __webpack_require__) {
  4775. "use strict";
  4776. Object.defineProperty(exports, "__esModule", { value: true });
  4777. var jsx_syntax_1 = __webpack_require__(6);
  4778. /* tslint:disable:max-classes-per-file */
  4779. var JSXClosingElement = (function () {
  4780. function JSXClosingElement(name) {
  4781. this.type = jsx_syntax_1.JSXSyntax.JSXClosingElement;
  4782. this.name = name;
  4783. }
  4784. return JSXClosingElement;
  4785. }());
  4786. exports.JSXClosingElement = JSXClosingElement;
  4787. var JSXElement = (function () {
  4788. function JSXElement(openingElement, children, closingElement) {
  4789. this.type = jsx_syntax_1.JSXSyntax.JSXElement;
  4790. this.openingElement = openingElement;
  4791. this.children = children;
  4792. this.closingElement = closingElement;
  4793. }
  4794. return JSXElement;
  4795. }());
  4796. exports.JSXElement = JSXElement;
  4797. var JSXEmptyExpression = (function () {
  4798. function JSXEmptyExpression() {
  4799. this.type = jsx_syntax_1.JSXSyntax.JSXEmptyExpression;
  4800. }
  4801. return JSXEmptyExpression;
  4802. }());
  4803. exports.JSXEmptyExpression = JSXEmptyExpression;
  4804. var JSXExpressionContainer = (function () {
  4805. function JSXExpressionContainer(expression) {
  4806. this.type = jsx_syntax_1.JSXSyntax.JSXExpressionContainer;
  4807. this.expression = expression;
  4808. }
  4809. return JSXExpressionContainer;
  4810. }());
  4811. exports.JSXExpressionContainer = JSXExpressionContainer;
  4812. var JSXIdentifier = (function () {
  4813. function JSXIdentifier(name) {
  4814. this.type = jsx_syntax_1.JSXSyntax.JSXIdentifier;
  4815. this.name = name;
  4816. }
  4817. return JSXIdentifier;
  4818. }());
  4819. exports.JSXIdentifier = JSXIdentifier;
  4820. var JSXMemberExpression = (function () {
  4821. function JSXMemberExpression(object, property) {
  4822. this.type = jsx_syntax_1.JSXSyntax.JSXMemberExpression;
  4823. this.object = object;
  4824. this.property = property;
  4825. }
  4826. return JSXMemberExpression;
  4827. }());
  4828. exports.JSXMemberExpression = JSXMemberExpression;
  4829. var JSXAttribute = (function () {
  4830. function JSXAttribute(name, value) {
  4831. this.type = jsx_syntax_1.JSXSyntax.JSXAttribute;
  4832. this.name = name;
  4833. this.value = value;
  4834. }
  4835. return JSXAttribute;
  4836. }());
  4837. exports.JSXAttribute = JSXAttribute;
  4838. var JSXNamespacedName = (function () {
  4839. function JSXNamespacedName(namespace, name) {
  4840. this.type = jsx_syntax_1.JSXSyntax.JSXNamespacedName;
  4841. this.namespace = namespace;
  4842. this.name = name;
  4843. }
  4844. return JSXNamespacedName;
  4845. }());
  4846. exports.JSXNamespacedName = JSXNamespacedName;
  4847. var JSXOpeningElement = (function () {
  4848. function JSXOpeningElement(name, selfClosing, attributes) {
  4849. this.type = jsx_syntax_1.JSXSyntax.JSXOpeningElement;
  4850. this.name = name;
  4851. this.selfClosing = selfClosing;
  4852. this.attributes = attributes;
  4853. }
  4854. return JSXOpeningElement;
  4855. }());
  4856. exports.JSXOpeningElement = JSXOpeningElement;
  4857. var JSXSpreadAttribute = (function () {
  4858. function JSXSpreadAttribute(argument) {
  4859. this.type = jsx_syntax_1.JSXSyntax.JSXSpreadAttribute;
  4860. this.argument = argument;
  4861. }
  4862. return JSXSpreadAttribute;
  4863. }());
  4864. exports.JSXSpreadAttribute = JSXSpreadAttribute;
  4865. var JSXText = (function () {
  4866. function JSXText(value, raw) {
  4867. this.type = jsx_syntax_1.JSXSyntax.JSXText;
  4868. this.value = value;
  4869. this.raw = raw;
  4870. }
  4871. return JSXText;
  4872. }());
  4873. exports.JSXText = JSXText;
  4874. /***/ },
  4875. /* 6 */
  4876. /***/ function(module, exports) {
  4877. "use strict";
  4878. Object.defineProperty(exports, "__esModule", { value: true });
  4879. exports.JSXSyntax = {
  4880. JSXAttribute: 'JSXAttribute',
  4881. JSXClosingElement: 'JSXClosingElement',
  4882. JSXElement: 'JSXElement',
  4883. JSXEmptyExpression: 'JSXEmptyExpression',
  4884. JSXExpressionContainer: 'JSXExpressionContainer',
  4885. JSXIdentifier: 'JSXIdentifier',
  4886. JSXMemberExpression: 'JSXMemberExpression',
  4887. JSXNamespacedName: 'JSXNamespacedName',
  4888. JSXOpeningElement: 'JSXOpeningElement',
  4889. JSXSpreadAttribute: 'JSXSpreadAttribute',
  4890. JSXText: 'JSXText'
  4891. };
  4892. /***/ },
  4893. /* 7 */
  4894. /***/ function(module, exports, __webpack_require__) {
  4895. "use strict";
  4896. Object.defineProperty(exports, "__esModule", { value: true });
  4897. var syntax_1 = __webpack_require__(2);
  4898. /* tslint:disable:max-classes-per-file */
  4899. var ArrayExpression = (function () {
  4900. function ArrayExpression(elements) {
  4901. this.type = syntax_1.Syntax.ArrayExpression;
  4902. this.elements = elements;
  4903. }
  4904. return ArrayExpression;
  4905. }());
  4906. exports.ArrayExpression = ArrayExpression;
  4907. var ArrayPattern = (function () {
  4908. function ArrayPattern(elements) {
  4909. this.type = syntax_1.Syntax.ArrayPattern;
  4910. this.elements = elements;
  4911. }
  4912. return ArrayPattern;
  4913. }());
  4914. exports.ArrayPattern = ArrayPattern;
  4915. var ArrowFunctionExpression = (function () {
  4916. function ArrowFunctionExpression(params, body, expression) {
  4917. this.type = syntax_1.Syntax.ArrowFunctionExpression;
  4918. this.id = null;
  4919. this.params = params;
  4920. this.body = body;
  4921. this.generator = false;
  4922. this.expression = expression;
  4923. this.async = false;
  4924. }
  4925. return ArrowFunctionExpression;
  4926. }());
  4927. exports.ArrowFunctionExpression = ArrowFunctionExpression;
  4928. var AssignmentExpression = (function () {
  4929. function AssignmentExpression(operator, left, right) {
  4930. this.type = syntax_1.Syntax.AssignmentExpression;
  4931. this.operator = operator;
  4932. this.left = left;
  4933. this.right = right;
  4934. }
  4935. return AssignmentExpression;
  4936. }());
  4937. exports.AssignmentExpression = AssignmentExpression;
  4938. var AssignmentPattern = (function () {
  4939. function AssignmentPattern(left, right) {
  4940. this.type = syntax_1.Syntax.AssignmentPattern;
  4941. this.left = left;
  4942. this.right = right;
  4943. }
  4944. return AssignmentPattern;
  4945. }());
  4946. exports.AssignmentPattern = AssignmentPattern;
  4947. var AsyncArrowFunctionExpression = (function () {
  4948. function AsyncArrowFunctionExpression(params, body, expression) {
  4949. this.type = syntax_1.Syntax.ArrowFunctionExpression;
  4950. this.id = null;
  4951. this.params = params;
  4952. this.body = body;
  4953. this.generator = false;
  4954. this.expression = expression;
  4955. this.async = true;
  4956. }
  4957. return AsyncArrowFunctionExpression;
  4958. }());
  4959. exports.AsyncArrowFunctionExpression = AsyncArrowFunctionExpression;
  4960. var AsyncFunctionDeclaration = (function () {
  4961. function AsyncFunctionDeclaration(id, params, body) {
  4962. this.type = syntax_1.Syntax.FunctionDeclaration;
  4963. this.id = id;
  4964. this.params = params;
  4965. this.body = body;
  4966. this.generator = false;
  4967. this.expression = false;
  4968. this.async = true;
  4969. }
  4970. return AsyncFunctionDeclaration;
  4971. }());
  4972. exports.AsyncFunctionDeclaration = AsyncFunctionDeclaration;
  4973. var AsyncFunctionExpression = (function () {
  4974. function AsyncFunctionExpression(id, params, body) {
  4975. this.type = syntax_1.Syntax.FunctionExpression;
  4976. this.id = id;
  4977. this.params = params;
  4978. this.body = body;
  4979. this.generator = false;
  4980. this.expression = false;
  4981. this.async = true;
  4982. }
  4983. return AsyncFunctionExpression;
  4984. }());
  4985. exports.AsyncFunctionExpression = AsyncFunctionExpression;
  4986. var AwaitExpression = (function () {
  4987. function AwaitExpression(argument) {
  4988. this.type = syntax_1.Syntax.AwaitExpression;
  4989. this.argument = argument;
  4990. }
  4991. return AwaitExpression;
  4992. }());
  4993. exports.AwaitExpression = AwaitExpression;
  4994. var BinaryExpression = (function () {
  4995. function BinaryExpression(operator, left, right) {
  4996. var logical = (operator === '||' || operator === '&&');
  4997. this.type = logical ? syntax_1.Syntax.LogicalExpression : syntax_1.Syntax.BinaryExpression;
  4998. this.operator = operator;
  4999. this.left = left;
  5000. this.right = right;
  5001. }
  5002. return BinaryExpression;
  5003. }());
  5004. exports.BinaryExpression = BinaryExpression;
  5005. var BlockStatement = (function () {
  5006. function BlockStatement(body) {
  5007. this.type = syntax_1.Syntax.BlockStatement;
  5008. this.body = body;
  5009. }
  5010. return BlockStatement;
  5011. }());
  5012. exports.BlockStatement = BlockStatement;
  5013. var BreakStatement = (function () {
  5014. function BreakStatement(label) {
  5015. this.type = syntax_1.Syntax.BreakStatement;
  5016. this.label = label;
  5017. }
  5018. return BreakStatement;
  5019. }());
  5020. exports.BreakStatement = BreakStatement;
  5021. var CallExpression = (function () {
  5022. function CallExpression(callee, args) {
  5023. this.type = syntax_1.Syntax.CallExpression;
  5024. this.callee = callee;
  5025. this.arguments = args;
  5026. }
  5027. return CallExpression;
  5028. }());
  5029. exports.CallExpression = CallExpression;
  5030. var CatchClause = (function () {
  5031. function CatchClause(param, body) {
  5032. this.type = syntax_1.Syntax.CatchClause;
  5033. this.param = param;
  5034. this.body = body;
  5035. }
  5036. return CatchClause;
  5037. }());
  5038. exports.CatchClause = CatchClause;
  5039. var ClassBody = (function () {
  5040. function ClassBody(body) {
  5041. this.type = syntax_1.Syntax.ClassBody;
  5042. this.body = body;
  5043. }
  5044. return ClassBody;
  5045. }());
  5046. exports.ClassBody = ClassBody;
  5047. var ClassDeclaration = (function () {
  5048. function ClassDeclaration(id, superClass, body) {
  5049. this.type = syntax_1.Syntax.ClassDeclaration;
  5050. this.id = id;
  5051. this.superClass = superClass;
  5052. this.body = body;
  5053. }
  5054. return ClassDeclaration;
  5055. }());
  5056. exports.ClassDeclaration = ClassDeclaration;
  5057. var ClassExpression = (function () {
  5058. function ClassExpression(id, superClass, body) {
  5059. this.type = syntax_1.Syntax.ClassExpression;
  5060. this.id = id;
  5061. this.superClass = superClass;
  5062. this.body = body;
  5063. }
  5064. return ClassExpression;
  5065. }());
  5066. exports.ClassExpression = ClassExpression;
  5067. var ComputedMemberExpression = (function () {
  5068. function ComputedMemberExpression(object, property) {
  5069. this.type = syntax_1.Syntax.MemberExpression;
  5070. this.computed = true;
  5071. this.object = object;
  5072. this.property = property;
  5073. }
  5074. return ComputedMemberExpression;
  5075. }());
  5076. exports.ComputedMemberExpression = ComputedMemberExpression;
  5077. var ConditionalExpression = (function () {
  5078. function ConditionalExpression(test, consequent, alternate) {
  5079. this.type = syntax_1.Syntax.ConditionalExpression;
  5080. this.test = test;
  5081. this.consequent = consequent;
  5082. this.alternate = alternate;
  5083. }
  5084. return ConditionalExpression;
  5085. }());
  5086. exports.ConditionalExpression = ConditionalExpression;
  5087. var ContinueStatement = (function () {
  5088. function ContinueStatement(label) {
  5089. this.type = syntax_1.Syntax.ContinueStatement;
  5090. this.label = label;
  5091. }
  5092. return ContinueStatement;
  5093. }());
  5094. exports.ContinueStatement = ContinueStatement;
  5095. var DebuggerStatement = (function () {
  5096. function DebuggerStatement() {
  5097. this.type = syntax_1.Syntax.DebuggerStatement;
  5098. }
  5099. return DebuggerStatement;
  5100. }());
  5101. exports.DebuggerStatement = DebuggerStatement;
  5102. var Directive = (function () {
  5103. function Directive(expression, directive) {
  5104. this.type = syntax_1.Syntax.ExpressionStatement;
  5105. this.expression = expression;
  5106. this.directive = directive;
  5107. }
  5108. return Directive;
  5109. }());
  5110. exports.Directive = Directive;
  5111. var DoWhileStatement = (function () {
  5112. function DoWhileStatement(body, test) {
  5113. this.type = syntax_1.Syntax.DoWhileStatement;
  5114. this.body = body;
  5115. this.test = test;
  5116. }
  5117. return DoWhileStatement;
  5118. }());
  5119. exports.DoWhileStatement = DoWhileStatement;
  5120. var EmptyStatement = (function () {
  5121. function EmptyStatement() {
  5122. this.type = syntax_1.Syntax.EmptyStatement;
  5123. }
  5124. return EmptyStatement;
  5125. }());
  5126. exports.EmptyStatement = EmptyStatement;
  5127. var ExportAllDeclaration = (function () {
  5128. function ExportAllDeclaration(source) {
  5129. this.type = syntax_1.Syntax.ExportAllDeclaration;
  5130. this.source = source;
  5131. }
  5132. return ExportAllDeclaration;
  5133. }());
  5134. exports.ExportAllDeclaration = ExportAllDeclaration;
  5135. var ExportDefaultDeclaration = (function () {
  5136. function ExportDefaultDeclaration(declaration) {
  5137. this.type = syntax_1.Syntax.ExportDefaultDeclaration;
  5138. this.declaration = declaration;
  5139. }
  5140. return ExportDefaultDeclaration;
  5141. }());
  5142. exports.ExportDefaultDeclaration = ExportDefaultDeclaration;
  5143. var ExportNamedDeclaration = (function () {
  5144. function ExportNamedDeclaration(declaration, specifiers, source) {
  5145. this.type = syntax_1.Syntax.ExportNamedDeclaration;
  5146. this.declaration = declaration;
  5147. this.specifiers = specifiers;
  5148. this.source = source;
  5149. }
  5150. return ExportNamedDeclaration;
  5151. }());
  5152. exports.ExportNamedDeclaration = ExportNamedDeclaration;
  5153. var ExportSpecifier = (function () {
  5154. function ExportSpecifier(local, exported) {
  5155. this.type = syntax_1.Syntax.ExportSpecifier;
  5156. this.exported = exported;
  5157. this.local = local;
  5158. }
  5159. return ExportSpecifier;
  5160. }());
  5161. exports.ExportSpecifier = ExportSpecifier;
  5162. var ExpressionStatement = (function () {
  5163. function ExpressionStatement(expression) {
  5164. this.type = syntax_1.Syntax.ExpressionStatement;
  5165. this.expression = expression;
  5166. }
  5167. return ExpressionStatement;
  5168. }());
  5169. exports.ExpressionStatement = ExpressionStatement;
  5170. var ForInStatement = (function () {
  5171. function ForInStatement(left, right, body) {
  5172. this.type = syntax_1.Syntax.ForInStatement;
  5173. this.left = left;
  5174. this.right = right;
  5175. this.body = body;
  5176. this.each = false;
  5177. }
  5178. return ForInStatement;
  5179. }());
  5180. exports.ForInStatement = ForInStatement;
  5181. var ForOfStatement = (function () {
  5182. function ForOfStatement(left, right, body) {
  5183. this.type = syntax_1.Syntax.ForOfStatement;
  5184. this.left = left;
  5185. this.right = right;
  5186. this.body = body;
  5187. }
  5188. return ForOfStatement;
  5189. }());
  5190. exports.ForOfStatement = ForOfStatement;
  5191. var ForStatement = (function () {
  5192. function ForStatement(init, test, update, body) {
  5193. this.type = syntax_1.Syntax.ForStatement;
  5194. this.init = init;
  5195. this.test = test;
  5196. this.update = update;
  5197. this.body = body;
  5198. }
  5199. return ForStatement;
  5200. }());
  5201. exports.ForStatement = ForStatement;
  5202. var FunctionDeclaration = (function () {
  5203. function FunctionDeclaration(id, params, body, generator) {
  5204. this.type = syntax_1.Syntax.FunctionDeclaration;
  5205. this.id = id;
  5206. this.params = params;
  5207. this.body = body;
  5208. this.generator = generator;
  5209. this.expression = false;
  5210. this.async = false;
  5211. }
  5212. return FunctionDeclaration;
  5213. }());
  5214. exports.FunctionDeclaration = FunctionDeclaration;
  5215. var FunctionExpression = (function () {
  5216. function FunctionExpression(id, params, body, generator) {
  5217. this.type = syntax_1.Syntax.FunctionExpression;
  5218. this.id = id;
  5219. this.params = params;
  5220. this.body = body;
  5221. this.generator = generator;
  5222. this.expression = false;
  5223. this.async = false;
  5224. }
  5225. return FunctionExpression;
  5226. }());
  5227. exports.FunctionExpression = FunctionExpression;
  5228. var Identifier = (function () {
  5229. function Identifier(name) {
  5230. this.type = syntax_1.Syntax.Identifier;
  5231. this.name = name;
  5232. }
  5233. return Identifier;
  5234. }());
  5235. exports.Identifier = Identifier;
  5236. var IfStatement = (function () {
  5237. function IfStatement(test, consequent, alternate) {
  5238. this.type = syntax_1.Syntax.IfStatement;
  5239. this.test = test;
  5240. this.consequent = consequent;
  5241. this.alternate = alternate;
  5242. }
  5243. return IfStatement;
  5244. }());
  5245. exports.IfStatement = IfStatement;
  5246. var ImportDeclaration = (function () {
  5247. function ImportDeclaration(specifiers, source) {
  5248. this.type = syntax_1.Syntax.ImportDeclaration;
  5249. this.specifiers = specifiers;
  5250. this.source = source;
  5251. }
  5252. return ImportDeclaration;
  5253. }());
  5254. exports.ImportDeclaration = ImportDeclaration;
  5255. var ImportDefaultSpecifier = (function () {
  5256. function ImportDefaultSpecifier(local) {
  5257. this.type = syntax_1.Syntax.ImportDefaultSpecifier;
  5258. this.local = local;
  5259. }
  5260. return ImportDefaultSpecifier;
  5261. }());
  5262. exports.ImportDefaultSpecifier = ImportDefaultSpecifier;
  5263. var ImportNamespaceSpecifier = (function () {
  5264. function ImportNamespaceSpecifier(local) {
  5265. this.type = syntax_1.Syntax.ImportNamespaceSpecifier;
  5266. this.local = local;
  5267. }
  5268. return ImportNamespaceSpecifier;
  5269. }());
  5270. exports.ImportNamespaceSpecifier = ImportNamespaceSpecifier;
  5271. var ImportSpecifier = (function () {
  5272. function ImportSpecifier(local, imported) {
  5273. this.type = syntax_1.Syntax.ImportSpecifier;
  5274. this.local = local;
  5275. this.imported = imported;
  5276. }
  5277. return ImportSpecifier;
  5278. }());
  5279. exports.ImportSpecifier = ImportSpecifier;
  5280. var LabeledStatement = (function () {
  5281. function LabeledStatement(label, body) {
  5282. this.type = syntax_1.Syntax.LabeledStatement;
  5283. this.label = label;
  5284. this.body = body;
  5285. }
  5286. return LabeledStatement;
  5287. }());
  5288. exports.LabeledStatement = LabeledStatement;
  5289. var Literal = (function () {
  5290. function Literal(value, raw) {
  5291. this.type = syntax_1.Syntax.Literal;
  5292. this.value = value;
  5293. this.raw = raw;
  5294. }
  5295. return Literal;
  5296. }());
  5297. exports.Literal = Literal;
  5298. var MetaProperty = (function () {
  5299. function MetaProperty(meta, property) {
  5300. this.type = syntax_1.Syntax.MetaProperty;
  5301. this.meta = meta;
  5302. this.property = property;
  5303. }
  5304. return MetaProperty;
  5305. }());
  5306. exports.MetaProperty = MetaProperty;
  5307. var MethodDefinition = (function () {
  5308. function MethodDefinition(key, computed, value, kind, isStatic) {
  5309. this.type = syntax_1.Syntax.MethodDefinition;
  5310. this.key = key;
  5311. this.computed = computed;
  5312. this.value = value;
  5313. this.kind = kind;
  5314. this.static = isStatic;
  5315. }
  5316. return MethodDefinition;
  5317. }());
  5318. exports.MethodDefinition = MethodDefinition;
  5319. var Module = (function () {
  5320. function Module(body) {
  5321. this.type = syntax_1.Syntax.Program;
  5322. this.body = body;
  5323. this.sourceType = 'module';
  5324. }
  5325. return Module;
  5326. }());
  5327. exports.Module = Module;
  5328. var NewExpression = (function () {
  5329. function NewExpression(callee, args) {
  5330. this.type = syntax_1.Syntax.NewExpression;
  5331. this.callee = callee;
  5332. this.arguments = args;
  5333. }
  5334. return NewExpression;
  5335. }());
  5336. exports.NewExpression = NewExpression;
  5337. var ObjectExpression = (function () {
  5338. function ObjectExpression(properties) {
  5339. this.type = syntax_1.Syntax.ObjectExpression;
  5340. this.properties = properties;
  5341. }
  5342. return ObjectExpression;
  5343. }());
  5344. exports.ObjectExpression = ObjectExpression;
  5345. var ObjectPattern = (function () {
  5346. function ObjectPattern(properties) {
  5347. this.type = syntax_1.Syntax.ObjectPattern;
  5348. this.properties = properties;
  5349. }
  5350. return ObjectPattern;
  5351. }());
  5352. exports.ObjectPattern = ObjectPattern;
  5353. var Property = (function () {
  5354. function Property(kind, key, computed, value, method, shorthand) {
  5355. this.type = syntax_1.Syntax.Property;
  5356. this.key = key;
  5357. this.computed = computed;
  5358. this.value = value;
  5359. this.kind = kind;
  5360. this.method = method;
  5361. this.shorthand = shorthand;
  5362. }
  5363. return Property;
  5364. }());
  5365. exports.Property = Property;
  5366. var RegexLiteral = (function () {
  5367. function RegexLiteral(value, raw, pattern, flags) {
  5368. this.type = syntax_1.Syntax.Literal;
  5369. this.value = value;
  5370. this.raw = raw;
  5371. this.regex = { pattern: pattern, flags: flags };
  5372. }
  5373. return RegexLiteral;
  5374. }());
  5375. exports.RegexLiteral = RegexLiteral;
  5376. var RestElement = (function () {
  5377. function RestElement(argument) {
  5378. this.type = syntax_1.Syntax.RestElement;
  5379. this.argument = argument;
  5380. }
  5381. return RestElement;
  5382. }());
  5383. exports.RestElement = RestElement;
  5384. var ReturnStatement = (function () {
  5385. function ReturnStatement(argument) {
  5386. this.type = syntax_1.Syntax.ReturnStatement;
  5387. this.argument = argument;
  5388. }
  5389. return ReturnStatement;
  5390. }());
  5391. exports.ReturnStatement = ReturnStatement;
  5392. var Script = (function () {
  5393. function Script(body) {
  5394. this.type = syntax_1.Syntax.Program;
  5395. this.body = body;
  5396. this.sourceType = 'script';
  5397. }
  5398. return Script;
  5399. }());
  5400. exports.Script = Script;
  5401. var SequenceExpression = (function () {
  5402. function SequenceExpression(expressions) {
  5403. this.type = syntax_1.Syntax.SequenceExpression;
  5404. this.expressions = expressions;
  5405. }
  5406. return SequenceExpression;
  5407. }());
  5408. exports.SequenceExpression = SequenceExpression;
  5409. var SpreadElement = (function () {
  5410. function SpreadElement(argument) {
  5411. this.type = syntax_1.Syntax.SpreadElement;
  5412. this.argument = argument;
  5413. }
  5414. return SpreadElement;
  5415. }());
  5416. exports.SpreadElement = SpreadElement;
  5417. var StaticMemberExpression = (function () {
  5418. function StaticMemberExpression(object, property) {
  5419. this.type = syntax_1.Syntax.MemberExpression;
  5420. this.computed = false;
  5421. this.object = object;
  5422. this.property = property;
  5423. }
  5424. return StaticMemberExpression;
  5425. }());
  5426. exports.StaticMemberExpression = StaticMemberExpression;
  5427. var Super = (function () {
  5428. function Super() {
  5429. this.type = syntax_1.Syntax.Super;
  5430. }
  5431. return Super;
  5432. }());
  5433. exports.Super = Super;
  5434. var SwitchCase = (function () {
  5435. function SwitchCase(test, consequent) {
  5436. this.type = syntax_1.Syntax.SwitchCase;
  5437. this.test = test;
  5438. this.consequent = consequent;
  5439. }
  5440. return SwitchCase;
  5441. }());
  5442. exports.SwitchCase = SwitchCase;
  5443. var SwitchStatement = (function () {
  5444. function SwitchStatement(discriminant, cases) {
  5445. this.type = syntax_1.Syntax.SwitchStatement;
  5446. this.discriminant = discriminant;
  5447. this.cases = cases;
  5448. }
  5449. return SwitchStatement;
  5450. }());
  5451. exports.SwitchStatement = SwitchStatement;
  5452. var TaggedTemplateExpression = (function () {
  5453. function TaggedTemplateExpression(tag, quasi) {
  5454. this.type = syntax_1.Syntax.TaggedTemplateExpression;
  5455. this.tag = tag;
  5456. this.quasi = quasi;
  5457. }
  5458. return TaggedTemplateExpression;
  5459. }());
  5460. exports.TaggedTemplateExpression = TaggedTemplateExpression;
  5461. var TemplateElement = (function () {
  5462. function TemplateElement(value, tail) {
  5463. this.type = syntax_1.Syntax.TemplateElement;
  5464. this.value = value;
  5465. this.tail = tail;
  5466. }
  5467. return TemplateElement;
  5468. }());
  5469. exports.TemplateElement = TemplateElement;
  5470. var TemplateLiteral = (function () {
  5471. function TemplateLiteral(quasis, expressions) {
  5472. this.type = syntax_1.Syntax.TemplateLiteral;
  5473. this.quasis = quasis;
  5474. this.expressions = expressions;
  5475. }
  5476. return TemplateLiteral;
  5477. }());
  5478. exports.TemplateLiteral = TemplateLiteral;
  5479. var ThisExpression = (function () {
  5480. function ThisExpression() {
  5481. this.type = syntax_1.Syntax.ThisExpression;
  5482. }
  5483. return ThisExpression;
  5484. }());
  5485. exports.ThisExpression = ThisExpression;
  5486. var ThrowStatement = (function () {
  5487. function ThrowStatement(argument) {
  5488. this.type = syntax_1.Syntax.ThrowStatement;
  5489. this.argument = argument;
  5490. }
  5491. return ThrowStatement;
  5492. }());
  5493. exports.ThrowStatement = ThrowStatement;
  5494. var TryStatement = (function () {
  5495. function TryStatement(block, handler, finalizer) {
  5496. this.type = syntax_1.Syntax.TryStatement;
  5497. this.block = block;
  5498. this.handler = handler;
  5499. this.finalizer = finalizer;
  5500. }
  5501. return TryStatement;
  5502. }());
  5503. exports.TryStatement = TryStatement;
  5504. var UnaryExpression = (function () {
  5505. function UnaryExpression(operator, argument) {
  5506. this.type = syntax_1.Syntax.UnaryExpression;
  5507. this.operator = operator;
  5508. this.argument = argument;
  5509. this.prefix = true;
  5510. }
  5511. return UnaryExpression;
  5512. }());
  5513. exports.UnaryExpression = UnaryExpression;
  5514. var UpdateExpression = (function () {
  5515. function UpdateExpression(operator, argument, prefix) {
  5516. this.type = syntax_1.Syntax.UpdateExpression;
  5517. this.operator = operator;
  5518. this.argument = argument;
  5519. this.prefix = prefix;
  5520. }
  5521. return UpdateExpression;
  5522. }());
  5523. exports.UpdateExpression = UpdateExpression;
  5524. var VariableDeclaration = (function () {
  5525. function VariableDeclaration(declarations, kind) {
  5526. this.type = syntax_1.Syntax.VariableDeclaration;
  5527. this.declarations = declarations;
  5528. this.kind = kind;
  5529. }
  5530. return VariableDeclaration;
  5531. }());
  5532. exports.VariableDeclaration = VariableDeclaration;
  5533. var VariableDeclarator = (function () {
  5534. function VariableDeclarator(id, init) {
  5535. this.type = syntax_1.Syntax.VariableDeclarator;
  5536. this.id = id;
  5537. this.init = init;
  5538. }
  5539. return VariableDeclarator;
  5540. }());
  5541. exports.VariableDeclarator = VariableDeclarator;
  5542. var WhileStatement = (function () {
  5543. function WhileStatement(test, body) {
  5544. this.type = syntax_1.Syntax.WhileStatement;
  5545. this.test = test;
  5546. this.body = body;
  5547. }
  5548. return WhileStatement;
  5549. }());
  5550. exports.WhileStatement = WhileStatement;
  5551. var WithStatement = (function () {
  5552. function WithStatement(object, body) {
  5553. this.type = syntax_1.Syntax.WithStatement;
  5554. this.object = object;
  5555. this.body = body;
  5556. }
  5557. return WithStatement;
  5558. }());
  5559. exports.WithStatement = WithStatement;
  5560. var YieldExpression = (function () {
  5561. function YieldExpression(argument, delegate) {
  5562. this.type = syntax_1.Syntax.YieldExpression;
  5563. this.argument = argument;
  5564. this.delegate = delegate;
  5565. }
  5566. return YieldExpression;
  5567. }());
  5568. exports.YieldExpression = YieldExpression;
  5569. /***/ },
  5570. /* 8 */
  5571. /***/ function(module, exports, __webpack_require__) {
  5572. "use strict";
  5573. Object.defineProperty(exports, "__esModule", { value: true });
  5574. var assert_1 = __webpack_require__(9);
  5575. var error_handler_1 = __webpack_require__(10);
  5576. var messages_1 = __webpack_require__(11);
  5577. var Node = __webpack_require__(7);
  5578. var scanner_1 = __webpack_require__(12);
  5579. var syntax_1 = __webpack_require__(2);
  5580. var token_1 = __webpack_require__(13);
  5581. var ArrowParameterPlaceHolder = 'ArrowParameterPlaceHolder';
  5582. var Parser = (function () {
  5583. function Parser(code, options, delegate) {
  5584. if (options === void 0) { options = {}; }
  5585. this.config = {
  5586. range: (typeof options.range === 'boolean') && options.range,
  5587. loc: (typeof options.loc === 'boolean') && options.loc,
  5588. source: null,
  5589. tokens: (typeof options.tokens === 'boolean') && options.tokens,
  5590. comment: (typeof options.comment === 'boolean') && options.comment,
  5591. tolerant: (typeof options.tolerant === 'boolean') && options.tolerant
  5592. };
  5593. if (this.config.loc && options.source && options.source !== null) {
  5594. this.config.source = String(options.source);
  5595. }
  5596. this.delegate = delegate;
  5597. this.errorHandler = new error_handler_1.ErrorHandler();
  5598. this.errorHandler.tolerant = this.config.tolerant;
  5599. this.scanner = new scanner_1.Scanner(code, this.errorHandler);
  5600. this.scanner.trackComment = this.config.comment;
  5601. this.operatorPrecedence = {
  5602. ')': 0,
  5603. ';': 0,
  5604. ',': 0,
  5605. '=': 0,
  5606. ']': 0,
  5607. '||': 1,
  5608. '&&': 2,
  5609. '|': 3,
  5610. '^': 4,
  5611. '&': 5,
  5612. '==': 6,
  5613. '!=': 6,
  5614. '===': 6,
  5615. '!==': 6,
  5616. '<': 7,
  5617. '>': 7,
  5618. '<=': 7,
  5619. '>=': 7,
  5620. '<<': 8,
  5621. '>>': 8,
  5622. '>>>': 8,
  5623. '+': 9,
  5624. '-': 9,
  5625. '*': 11,
  5626. '/': 11,
  5627. '%': 11
  5628. };
  5629. this.lookahead = {
  5630. type: 2 /* EOF */,
  5631. value: '',
  5632. lineNumber: this.scanner.lineNumber,
  5633. lineStart: 0,
  5634. start: 0,
  5635. end: 0
  5636. };
  5637. this.hasLineTerminator = false;
  5638. this.context = {
  5639. isModule: false,
  5640. await: false,
  5641. allowIn: true,
  5642. allowStrictDirective: true,
  5643. allowYield: true,
  5644. firstCoverInitializedNameError: null,
  5645. isAssignmentTarget: false,
  5646. isBindingElement: false,
  5647. inFunctionBody: false,
  5648. inIteration: false,
  5649. inSwitch: false,
  5650. labelSet: {},
  5651. strict: false
  5652. };
  5653. this.tokens = [];
  5654. this.startMarker = {
  5655. index: 0,
  5656. line: this.scanner.lineNumber,
  5657. column: 0
  5658. };
  5659. this.lastMarker = {
  5660. index: 0,
  5661. line: this.scanner.lineNumber,
  5662. column: 0
  5663. };
  5664. this.nextToken();
  5665. this.lastMarker = {
  5666. index: this.scanner.index,
  5667. line: this.scanner.lineNumber,
  5668. column: this.scanner.index - this.scanner.lineStart
  5669. };
  5670. }
  5671. Parser.prototype.throwError = function (messageFormat) {
  5672. var values = [];
  5673. for (var _i = 1; _i < arguments.length; _i++) {
  5674. values[_i - 1] = arguments[_i];
  5675. }
  5676. var args = Array.prototype.slice.call(arguments, 1);
  5677. var msg = messageFormat.replace(/%(\d)/g, function (whole, idx) {
  5678. assert_1.assert(idx < args.length, 'Message reference must be in range');
  5679. return args[idx];
  5680. });
  5681. var index = this.lastMarker.index;
  5682. var line = this.lastMarker.line;
  5683. var column = this.lastMarker.column + 1;
  5684. throw this.errorHandler.createError(index, line, column, msg);
  5685. };
  5686. Parser.prototype.tolerateError = function (messageFormat) {
  5687. var values = [];
  5688. for (var _i = 1; _i < arguments.length; _i++) {
  5689. values[_i - 1] = arguments[_i];
  5690. }
  5691. var args = Array.prototype.slice.call(arguments, 1);
  5692. var msg = messageFormat.replace(/%(\d)/g, function (whole, idx) {
  5693. assert_1.assert(idx < args.length, 'Message reference must be in range');
  5694. return args[idx];
  5695. });
  5696. var index = this.lastMarker.index;
  5697. var line = this.scanner.lineNumber;
  5698. var column = this.lastMarker.column + 1;
  5699. this.errorHandler.tolerateError(index, line, column, msg);
  5700. };
  5701. // Throw an exception because of the token.
  5702. Parser.prototype.unexpectedTokenError = function (token, message) {
  5703. var msg = message || messages_1.Messages.UnexpectedToken;
  5704. var value;
  5705. if (token) {
  5706. if (!message) {
  5707. msg = (token.type === 2 /* EOF */) ? messages_1.Messages.UnexpectedEOS :
  5708. (token.type === 3 /* Identifier */) ? messages_1.Messages.UnexpectedIdentifier :
  5709. (token.type === 6 /* NumericLiteral */) ? messages_1.Messages.UnexpectedNumber :
  5710. (token.type === 8 /* StringLiteral */) ? messages_1.Messages.UnexpectedString :
  5711. (token.type === 10 /* Template */) ? messages_1.Messages.UnexpectedTemplate :
  5712. messages_1.Messages.UnexpectedToken;
  5713. if (token.type === 4 /* Keyword */) {
  5714. if (this.scanner.isFutureReservedWord(token.value)) {
  5715. msg = messages_1.Messages.UnexpectedReserved;
  5716. }
  5717. else if (this.context.strict && this.scanner.isStrictModeReservedWord(token.value)) {
  5718. msg = messages_1.Messages.StrictReservedWord;
  5719. }
  5720. }
  5721. }
  5722. value = token.value;
  5723. }
  5724. else {
  5725. value = 'ILLEGAL';
  5726. }
  5727. msg = msg.replace('%0', value);
  5728. if (token && typeof token.lineNumber === 'number') {
  5729. var index = token.start;
  5730. var line = token.lineNumber;
  5731. var lastMarkerLineStart = this.lastMarker.index - this.lastMarker.column;
  5732. var column = token.start - lastMarkerLineStart + 1;
  5733. return this.errorHandler.createError(index, line, column, msg);
  5734. }
  5735. else {
  5736. var index = this.lastMarker.index;
  5737. var line = this.lastMarker.line;
  5738. var column = this.lastMarker.column + 1;
  5739. return this.errorHandler.createError(index, line, column, msg);
  5740. }
  5741. };
  5742. Parser.prototype.throwUnexpectedToken = function (token, message) {
  5743. throw this.unexpectedTokenError(token, message);
  5744. };
  5745. Parser.prototype.tolerateUnexpectedToken = function (token, message) {
  5746. this.errorHandler.tolerate(this.unexpectedTokenError(token, message));
  5747. };
  5748. Parser.prototype.collectComments = function () {
  5749. if (!this.config.comment) {
  5750. this.scanner.scanComments();
  5751. }
  5752. else {
  5753. var comments = this.scanner.scanComments();
  5754. if (comments.length > 0 && this.delegate) {
  5755. for (var i = 0; i < comments.length; ++i) {
  5756. var e = comments[i];
  5757. var node = void 0;
  5758. node = {
  5759. type: e.multiLine ? 'BlockComment' : 'LineComment',
  5760. value: this.scanner.source.slice(e.slice[0], e.slice[1])
  5761. };
  5762. if (this.config.range) {
  5763. node.range = e.range;
  5764. }
  5765. if (this.config.loc) {
  5766. node.loc = e.loc;
  5767. }
  5768. var metadata = {
  5769. start: {
  5770. line: e.loc.start.line,
  5771. column: e.loc.start.column,
  5772. offset: e.range[0]
  5773. },
  5774. end: {
  5775. line: e.loc.end.line,
  5776. column: e.loc.end.column,
  5777. offset: e.range[1]
  5778. }
  5779. };
  5780. this.delegate(node, metadata);
  5781. }
  5782. }
  5783. }
  5784. };
  5785. // From internal representation to an external structure
  5786. Parser.prototype.getTokenRaw = function (token) {
  5787. return this.scanner.source.slice(token.start, token.end);
  5788. };
  5789. Parser.prototype.convertToken = function (token) {
  5790. var t = {
  5791. type: token_1.TokenName[token.type],
  5792. value: this.getTokenRaw(token)
  5793. };
  5794. if (this.config.range) {
  5795. t.range = [token.start, token.end];
  5796. }
  5797. if (this.config.loc) {
  5798. t.loc = {
  5799. start: {
  5800. line: this.startMarker.line,
  5801. column: this.startMarker.column
  5802. },
  5803. end: {
  5804. line: this.scanner.lineNumber,
  5805. column: this.scanner.index - this.scanner.lineStart
  5806. }
  5807. };
  5808. }
  5809. if (token.type === 9 /* RegularExpression */) {
  5810. var pattern = token.pattern;
  5811. var flags = token.flags;
  5812. t.regex = { pattern: pattern, flags: flags };
  5813. }
  5814. return t;
  5815. };
  5816. Parser.prototype.nextToken = function () {
  5817. var token = this.lookahead;
  5818. this.lastMarker.index = this.scanner.index;
  5819. this.lastMarker.line = this.scanner.lineNumber;
  5820. this.lastMarker.column = this.scanner.index - this.scanner.lineStart;
  5821. this.collectComments();
  5822. if (this.scanner.index !== this.startMarker.index) {
  5823. this.startMarker.index = this.scanner.index;
  5824. this.startMarker.line = this.scanner.lineNumber;
  5825. this.startMarker.column = this.scanner.index - this.scanner.lineStart;
  5826. }
  5827. var next = this.scanner.lex();
  5828. this.hasLineTerminator = (token.lineNumber !== next.lineNumber);
  5829. if (next && this.context.strict && next.type === 3 /* Identifier */) {
  5830. if (this.scanner.isStrictModeReservedWord(next.value)) {
  5831. next.type = 4 /* Keyword */;
  5832. }
  5833. }
  5834. this.lookahead = next;
  5835. if (this.config.tokens && next.type !== 2 /* EOF */) {
  5836. this.tokens.push(this.convertToken(next));
  5837. }
  5838. return token;
  5839. };
  5840. Parser.prototype.nextRegexToken = function () {
  5841. this.collectComments();
  5842. var token = this.scanner.scanRegExp();
  5843. if (this.config.tokens) {
  5844. // Pop the previous token, '/' or '/='
  5845. // This is added from the lookahead token.
  5846. this.tokens.pop();
  5847. this.tokens.push(this.convertToken(token));
  5848. }
  5849. // Prime the next lookahead.
  5850. this.lookahead = token;
  5851. this.nextToken();
  5852. return token;
  5853. };
  5854. Parser.prototype.createNode = function () {
  5855. return {
  5856. index: this.startMarker.index,
  5857. line: this.startMarker.line,
  5858. column: this.startMarker.column
  5859. };
  5860. };
  5861. Parser.prototype.startNode = function (token) {
  5862. return {
  5863. index: token.start,
  5864. line: token.lineNumber,
  5865. column: token.start - token.lineStart
  5866. };
  5867. };
  5868. Parser.prototype.finalize = function (marker, node) {
  5869. if (this.config.range) {
  5870. node.range = [marker.index, this.lastMarker.index];
  5871. }
  5872. if (this.config.loc) {
  5873. node.loc = {
  5874. start: {
  5875. line: marker.line,
  5876. column: marker.column,
  5877. },
  5878. end: {
  5879. line: this.lastMarker.line,
  5880. column: this.lastMarker.column
  5881. }
  5882. };
  5883. if (this.config.source) {
  5884. node.loc.source = this.config.source;
  5885. }
  5886. }
  5887. if (this.delegate) {
  5888. var metadata = {
  5889. start: {
  5890. line: marker.line,
  5891. column: marker.column,
  5892. offset: marker.index
  5893. },
  5894. end: {
  5895. line: this.lastMarker.line,
  5896. column: this.lastMarker.column,
  5897. offset: this.lastMarker.index
  5898. }
  5899. };
  5900. this.delegate(node, metadata);
  5901. }
  5902. return node;
  5903. };
  5904. // Expect the next token to match the specified punctuator.
  5905. // If not, an exception will be thrown.
  5906. Parser.prototype.expect = function (value) {
  5907. var token = this.nextToken();
  5908. if (token.type !== 7 /* Punctuator */ || token.value !== value) {
  5909. this.throwUnexpectedToken(token);
  5910. }
  5911. };
  5912. // Quietly expect a comma when in tolerant mode, otherwise delegates to expect().
  5913. Parser.prototype.expectCommaSeparator = function () {
  5914. if (this.config.tolerant) {
  5915. var token = this.lookahead;
  5916. if (token.type === 7 /* Punctuator */ && token.value === ',') {
  5917. this.nextToken();
  5918. }
  5919. else if (token.type === 7 /* Punctuator */ && token.value === ';') {
  5920. this.nextToken();
  5921. this.tolerateUnexpectedToken(token);
  5922. }
  5923. else {
  5924. this.tolerateUnexpectedToken(token, messages_1.Messages.UnexpectedToken);
  5925. }
  5926. }
  5927. else {
  5928. this.expect(',');
  5929. }
  5930. };
  5931. // Expect the next token to match the specified keyword.
  5932. // If not, an exception will be thrown.
  5933. Parser.prototype.expectKeyword = function (keyword) {
  5934. var token = this.nextToken();
  5935. if (token.type !== 4 /* Keyword */ || token.value !== keyword) {
  5936. this.throwUnexpectedToken(token);
  5937. }
  5938. };
  5939. // Return true if the next token matches the specified punctuator.
  5940. Parser.prototype.match = function (value) {
  5941. return this.lookahead.type === 7 /* Punctuator */ && this.lookahead.value === value;
  5942. };
  5943. // Return true if the next token matches the specified keyword
  5944. Parser.prototype.matchKeyword = function (keyword) {
  5945. return this.lookahead.type === 4 /* Keyword */ && this.lookahead.value === keyword;
  5946. };
  5947. // Return true if the next token matches the specified contextual keyword
  5948. // (where an identifier is sometimes a keyword depending on the context)
  5949. Parser.prototype.matchContextualKeyword = function (keyword) {
  5950. return this.lookahead.type === 3 /* Identifier */ && this.lookahead.value === keyword;
  5951. };
  5952. // Return true if the next token is an assignment operator
  5953. Parser.prototype.matchAssign = function () {
  5954. if (this.lookahead.type !== 7 /* Punctuator */) {
  5955. return false;
  5956. }
  5957. var op = this.lookahead.value;
  5958. return op === '=' ||
  5959. op === '*=' ||
  5960. op === '**=' ||
  5961. op === '/=' ||
  5962. op === '%=' ||
  5963. op === '+=' ||
  5964. op === '-=' ||
  5965. op === '<<=' ||
  5966. op === '>>=' ||
  5967. op === '>>>=' ||
  5968. op === '&=' ||
  5969. op === '^=' ||
  5970. op === '|=';
  5971. };
  5972. // Cover grammar support.
  5973. //
  5974. // When an assignment expression position starts with an left parenthesis, the determination of the type
  5975. // of the syntax is to be deferred arbitrarily long until the end of the parentheses pair (plus a lookahead)
  5976. // or the first comma. This situation also defers the determination of all the expressions nested in the pair.
  5977. //
  5978. // There are three productions that can be parsed in a parentheses pair that needs to be determined
  5979. // after the outermost pair is closed. They are:
  5980. //
  5981. // 1. AssignmentExpression
  5982. // 2. BindingElements
  5983. // 3. AssignmentTargets
  5984. //
  5985. // In order to avoid exponential backtracking, we use two flags to denote if the production can be
  5986. // binding element or assignment target.
  5987. //
  5988. // The three productions have the relationship:
  5989. //
  5990. // BindingElements ⊆ AssignmentTargets ⊆ AssignmentExpression
  5991. //
  5992. // with a single exception that CoverInitializedName when used directly in an Expression, generates
  5993. // an early error. Therefore, we need the third state, firstCoverInitializedNameError, to track the
  5994. // first usage of CoverInitializedName and report it when we reached the end of the parentheses pair.
  5995. //
  5996. // isolateCoverGrammar function runs the given parser function with a new cover grammar context, and it does not
  5997. // effect the current flags. This means the production the parser parses is only used as an expression. Therefore
  5998. // the CoverInitializedName check is conducted.
  5999. //
  6000. // inheritCoverGrammar function runs the given parse function with a new cover grammar context, and it propagates
  6001. // the flags outside of the parser. This means the production the parser parses is used as a part of a potential
  6002. // pattern. The CoverInitializedName check is deferred.
  6003. Parser.prototype.isolateCoverGrammar = function (parseFunction) {
  6004. var previousIsBindingElement = this.context.isBindingElement;
  6005. var previousIsAssignmentTarget = this.context.isAssignmentTarget;
  6006. var previousFirstCoverInitializedNameError = this.context.firstCoverInitializedNameError;
  6007. this.context.isBindingElement = true;
  6008. this.context.isAssignmentTarget = true;
  6009. this.context.firstCoverInitializedNameError = null;
  6010. var result = parseFunction.call(this);
  6011. if (this.context.firstCoverInitializedNameError !== null) {
  6012. this.throwUnexpectedToken(this.context.firstCoverInitializedNameError);
  6013. }
  6014. this.context.isBindingElement = previousIsBindingElement;
  6015. this.context.isAssignmentTarget = previousIsAssignmentTarget;
  6016. this.context.firstCoverInitializedNameError = previousFirstCoverInitializedNameError;
  6017. return result;
  6018. };
  6019. Parser.prototype.inheritCoverGrammar = function (parseFunction) {
  6020. var previousIsBindingElement = this.context.isBindingElement;
  6021. var previousIsAssignmentTarget = this.context.isAssignmentTarget;
  6022. var previousFirstCoverInitializedNameError = this.context.firstCoverInitializedNameError;
  6023. this.context.isBindingElement = true;
  6024. this.context.isAssignmentTarget = true;
  6025. this.context.firstCoverInitializedNameError = null;
  6026. var result = parseFunction.call(this);
  6027. this.context.isBindingElement = this.context.isBindingElement && previousIsBindingElement;
  6028. this.context.isAssignmentTarget = this.context.isAssignmentTarget && previousIsAssignmentTarget;
  6029. this.context.firstCoverInitializedNameError = previousFirstCoverInitializedNameError || this.context.firstCoverInitializedNameError;
  6030. return result;
  6031. };
  6032. Parser.prototype.consumeSemicolon = function () {
  6033. if (this.match(';')) {
  6034. this.nextToken();
  6035. }
  6036. else if (!this.hasLineTerminator) {
  6037. if (this.lookahead.type !== 2 /* EOF */ && !this.match('}')) {
  6038. this.throwUnexpectedToken(this.lookahead);
  6039. }
  6040. this.lastMarker.index = this.startMarker.index;
  6041. this.lastMarker.line = this.startMarker.line;
  6042. this.lastMarker.column = this.startMarker.column;
  6043. }
  6044. };
  6045. // https://tc39.github.io/ecma262/#sec-primary-expression
  6046. Parser.prototype.parsePrimaryExpression = function () {
  6047. var node = this.createNode();
  6048. var expr;
  6049. var token, raw;
  6050. switch (this.lookahead.type) {
  6051. case 3 /* Identifier */:
  6052. if ((this.context.isModule || this.context.await) && this.lookahead.value === 'await') {
  6053. this.tolerateUnexpectedToken(this.lookahead);
  6054. }
  6055. expr = this.matchAsyncFunction() ? this.parseFunctionExpression() : this.finalize(node, new Node.Identifier(this.nextToken().value));
  6056. break;
  6057. case 6 /* NumericLiteral */:
  6058. case 8 /* StringLiteral */:
  6059. if (this.context.strict && this.lookahead.octal) {
  6060. this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.StrictOctalLiteral);
  6061. }
  6062. this.context.isAssignmentTarget = false;
  6063. this.context.isBindingElement = false;
  6064. token = this.nextToken();
  6065. raw = this.getTokenRaw(token);
  6066. expr = this.finalize(node, new Node.Literal(token.value, raw));
  6067. break;
  6068. case 1 /* BooleanLiteral */:
  6069. this.context.isAssignmentTarget = false;
  6070. this.context.isBindingElement = false;
  6071. token = this.nextToken();
  6072. raw = this.getTokenRaw(token);
  6073. expr = this.finalize(node, new Node.Literal(token.value === 'true', raw));
  6074. break;
  6075. case 5 /* NullLiteral */:
  6076. this.context.isAssignmentTarget = false;
  6077. this.context.isBindingElement = false;
  6078. token = this.nextToken();
  6079. raw = this.getTokenRaw(token);
  6080. expr = this.finalize(node, new Node.Literal(null, raw));
  6081. break;
  6082. case 10 /* Template */:
  6083. expr = this.parseTemplateLiteral();
  6084. break;
  6085. case 7 /* Punctuator */:
  6086. switch (this.lookahead.value) {
  6087. case '(':
  6088. this.context.isBindingElement = false;
  6089. expr = this.inheritCoverGrammar(this.parseGroupExpression);
  6090. break;
  6091. case '[':
  6092. expr = this.inheritCoverGrammar(this.parseArrayInitializer);
  6093. break;
  6094. case '{':
  6095. expr = this.inheritCoverGrammar(this.parseObjectInitializer);
  6096. break;
  6097. case '/':
  6098. case '/=':
  6099. this.context.isAssignmentTarget = false;
  6100. this.context.isBindingElement = false;
  6101. this.scanner.index = this.startMarker.index;
  6102. token = this.nextRegexToken();
  6103. raw = this.getTokenRaw(token);
  6104. expr = this.finalize(node, new Node.RegexLiteral(token.regex, raw, token.pattern, token.flags));
  6105. break;
  6106. default:
  6107. expr = this.throwUnexpectedToken(this.nextToken());
  6108. }
  6109. break;
  6110. case 4 /* Keyword */:
  6111. if (!this.context.strict && this.context.allowYield && this.matchKeyword('yield')) {
  6112. expr = this.parseIdentifierName();
  6113. }
  6114. else if (!this.context.strict && this.matchKeyword('let')) {
  6115. expr = this.finalize(node, new Node.Identifier(this.nextToken().value));
  6116. }
  6117. else {
  6118. this.context.isAssignmentTarget = false;
  6119. this.context.isBindingElement = false;
  6120. if (this.matchKeyword('function')) {
  6121. expr = this.parseFunctionExpression();
  6122. }
  6123. else if (this.matchKeyword('this')) {
  6124. this.nextToken();
  6125. expr = this.finalize(node, new Node.ThisExpression());
  6126. }
  6127. else if (this.matchKeyword('class')) {
  6128. expr = this.parseClassExpression();
  6129. }
  6130. else {
  6131. expr = this.throwUnexpectedToken(this.nextToken());
  6132. }
  6133. }
  6134. break;
  6135. default:
  6136. expr = this.throwUnexpectedToken(this.nextToken());
  6137. }
  6138. return expr;
  6139. };
  6140. // https://tc39.github.io/ecma262/#sec-array-initializer
  6141. Parser.prototype.parseSpreadElement = function () {
  6142. var node = this.createNode();
  6143. this.expect('...');
  6144. var arg = this.inheritCoverGrammar(this.parseAssignmentExpression);
  6145. return this.finalize(node, new Node.SpreadElement(arg));
  6146. };
  6147. Parser.prototype.parseArrayInitializer = function () {
  6148. var node = this.createNode();
  6149. var elements = [];
  6150. this.expect('[');
  6151. while (!this.match(']')) {
  6152. if (this.match(',')) {
  6153. this.nextToken();
  6154. elements.push(null);
  6155. }
  6156. else if (this.match('...')) {
  6157. var element = this.parseSpreadElement();
  6158. if (!this.match(']')) {
  6159. this.context.isAssignmentTarget = false;
  6160. this.context.isBindingElement = false;
  6161. this.expect(',');
  6162. }
  6163. elements.push(element);
  6164. }
  6165. else {
  6166. elements.push(this.inheritCoverGrammar(this.parseAssignmentExpression));
  6167. if (!this.match(']')) {
  6168. this.expect(',');
  6169. }
  6170. }
  6171. }
  6172. this.expect(']');
  6173. return this.finalize(node, new Node.ArrayExpression(elements));
  6174. };
  6175. // https://tc39.github.io/ecma262/#sec-object-initializer
  6176. Parser.prototype.parsePropertyMethod = function (params) {
  6177. this.context.isAssignmentTarget = false;
  6178. this.context.isBindingElement = false;
  6179. var previousStrict = this.context.strict;
  6180. var previousAllowStrictDirective = this.context.allowStrictDirective;
  6181. this.context.allowStrictDirective = params.simple;
  6182. var body = this.isolateCoverGrammar(this.parseFunctionSourceElements);
  6183. if (this.context.strict && params.firstRestricted) {
  6184. this.tolerateUnexpectedToken(params.firstRestricted, params.message);
  6185. }
  6186. if (this.context.strict && params.stricted) {
  6187. this.tolerateUnexpectedToken(params.stricted, params.message);
  6188. }
  6189. this.context.strict = previousStrict;
  6190. this.context.allowStrictDirective = previousAllowStrictDirective;
  6191. return body;
  6192. };
  6193. Parser.prototype.parsePropertyMethodFunction = function () {
  6194. var isGenerator = false;
  6195. var node = this.createNode();
  6196. var previousAllowYield = this.context.allowYield;
  6197. this.context.allowYield = false;
  6198. var params = this.parseFormalParameters();
  6199. var method = this.parsePropertyMethod(params);
  6200. this.context.allowYield = previousAllowYield;
  6201. return this.finalize(node, new Node.FunctionExpression(null, params.params, method, isGenerator));
  6202. };
  6203. Parser.prototype.parsePropertyMethodAsyncFunction = function () {
  6204. var node = this.createNode();
  6205. var previousAllowYield = this.context.allowYield;
  6206. var previousAwait = this.context.await;
  6207. this.context.allowYield = false;
  6208. this.context.await = true;
  6209. var params = this.parseFormalParameters();
  6210. var method = this.parsePropertyMethod(params);
  6211. this.context.allowYield = previousAllowYield;
  6212. this.context.await = previousAwait;
  6213. return this.finalize(node, new Node.AsyncFunctionExpression(null, params.params, method));
  6214. };
  6215. Parser.prototype.parseObjectPropertyKey = function () {
  6216. var node = this.createNode();
  6217. var token = this.nextToken();
  6218. var key;
  6219. switch (token.type) {
  6220. case 8 /* StringLiteral */:
  6221. case 6 /* NumericLiteral */:
  6222. if (this.context.strict && token.octal) {
  6223. this.tolerateUnexpectedToken(token, messages_1.Messages.StrictOctalLiteral);
  6224. }
  6225. var raw = this.getTokenRaw(token);
  6226. key = this.finalize(node, new Node.Literal(token.value, raw));
  6227. break;
  6228. case 3 /* Identifier */:
  6229. case 1 /* BooleanLiteral */:
  6230. case 5 /* NullLiteral */:
  6231. case 4 /* Keyword */:
  6232. key = this.finalize(node, new Node.Identifier(token.value));
  6233. break;
  6234. case 7 /* Punctuator */:
  6235. if (token.value === '[') {
  6236. key = this.isolateCoverGrammar(this.parseAssignmentExpression);
  6237. this.expect(']');
  6238. }
  6239. else {
  6240. key = this.throwUnexpectedToken(token);
  6241. }
  6242. break;
  6243. default:
  6244. key = this.throwUnexpectedToken(token);
  6245. }
  6246. return key;
  6247. };
  6248. Parser.prototype.isPropertyKey = function (key, value) {
  6249. return (key.type === syntax_1.Syntax.Identifier && key.name === value) ||
  6250. (key.type === syntax_1.Syntax.Literal && key.value === value);
  6251. };
  6252. Parser.prototype.parseObjectProperty = function (hasProto) {
  6253. var node = this.createNode();
  6254. var token = this.lookahead;
  6255. var kind;
  6256. var key = null;
  6257. var value = null;
  6258. var computed = false;
  6259. var method = false;
  6260. var shorthand = false;
  6261. var isAsync = false;
  6262. if (token.type === 3 /* Identifier */) {
  6263. var id = token.value;
  6264. this.nextToken();
  6265. computed = this.match('[');
  6266. isAsync = !this.hasLineTerminator && (id === 'async') &&
  6267. !this.match(':') && !this.match('(') && !this.match('*');
  6268. key = isAsync ? this.parseObjectPropertyKey() : this.finalize(node, new Node.Identifier(id));
  6269. }
  6270. else if (this.match('*')) {
  6271. this.nextToken();
  6272. }
  6273. else {
  6274. computed = this.match('[');
  6275. key = this.parseObjectPropertyKey();
  6276. }
  6277. var lookaheadPropertyKey = this.qualifiedPropertyName(this.lookahead);
  6278. if (token.type === 3 /* Identifier */ && !isAsync && token.value === 'get' && lookaheadPropertyKey) {
  6279. kind = 'get';
  6280. computed = this.match('[');
  6281. key = this.parseObjectPropertyKey();
  6282. this.context.allowYield = false;
  6283. value = this.parseGetterMethod();
  6284. }
  6285. else if (token.type === 3 /* Identifier */ && !isAsync && token.value === 'set' && lookaheadPropertyKey) {
  6286. kind = 'set';
  6287. computed = this.match('[');
  6288. key = this.parseObjectPropertyKey();
  6289. value = this.parseSetterMethod();
  6290. }
  6291. else if (token.type === 7 /* Punctuator */ && token.value === '*' && lookaheadPropertyKey) {
  6292. kind = 'init';
  6293. computed = this.match('[');
  6294. key = this.parseObjectPropertyKey();
  6295. value = this.parseGeneratorMethod();
  6296. method = true;
  6297. }
  6298. else {
  6299. if (!key) {
  6300. this.throwUnexpectedToken(this.lookahead);
  6301. }
  6302. kind = 'init';
  6303. if (this.match(':') && !isAsync) {
  6304. if (!computed && this.isPropertyKey(key, '__proto__')) {
  6305. if (hasProto.value) {
  6306. this.tolerateError(messages_1.Messages.DuplicateProtoProperty);
  6307. }
  6308. hasProto.value = true;
  6309. }
  6310. this.nextToken();
  6311. value = this.inheritCoverGrammar(this.parseAssignmentExpression);
  6312. }
  6313. else if (this.match('(')) {
  6314. value = isAsync ? this.parsePropertyMethodAsyncFunction() : this.parsePropertyMethodFunction();
  6315. method = true;
  6316. }
  6317. else if (token.type === 3 /* Identifier */) {
  6318. var id = this.finalize(node, new Node.Identifier(token.value));
  6319. if (this.match('=')) {
  6320. this.context.firstCoverInitializedNameError = this.lookahead;
  6321. this.nextToken();
  6322. shorthand = true;
  6323. var init = this.isolateCoverGrammar(this.parseAssignmentExpression);
  6324. value = this.finalize(node, new Node.AssignmentPattern(id, init));
  6325. }
  6326. else {
  6327. shorthand = true;
  6328. value = id;
  6329. }
  6330. }
  6331. else {
  6332. this.throwUnexpectedToken(this.nextToken());
  6333. }
  6334. }
  6335. return this.finalize(node, new Node.Property(kind, key, computed, value, method, shorthand));
  6336. };
  6337. Parser.prototype.parseObjectInitializer = function () {
  6338. var node = this.createNode();
  6339. this.expect('{');
  6340. var properties = [];
  6341. var hasProto = { value: false };
  6342. while (!this.match('}')) {
  6343. properties.push(this.parseObjectProperty(hasProto));
  6344. if (!this.match('}')) {
  6345. this.expectCommaSeparator();
  6346. }
  6347. }
  6348. this.expect('}');
  6349. return this.finalize(node, new Node.ObjectExpression(properties));
  6350. };
  6351. // https://tc39.github.io/ecma262/#sec-template-literals
  6352. Parser.prototype.parseTemplateHead = function () {
  6353. assert_1.assert(this.lookahead.head, 'Template literal must start with a template head');
  6354. var node = this.createNode();
  6355. var token = this.nextToken();
  6356. var raw = token.value;
  6357. var cooked = token.cooked;
  6358. return this.finalize(node, new Node.TemplateElement({ raw: raw, cooked: cooked }, token.tail));
  6359. };
  6360. Parser.prototype.parseTemplateElement = function () {
  6361. if (this.lookahead.type !== 10 /* Template */) {
  6362. this.throwUnexpectedToken();
  6363. }
  6364. var node = this.createNode();
  6365. var token = this.nextToken();
  6366. var raw = token.value;
  6367. var cooked = token.cooked;
  6368. return this.finalize(node, new Node.TemplateElement({ raw: raw, cooked: cooked }, token.tail));
  6369. };
  6370. Parser.prototype.parseTemplateLiteral = function () {
  6371. var node = this.createNode();
  6372. var expressions = [];
  6373. var quasis = [];
  6374. var quasi = this.parseTemplateHead();
  6375. quasis.push(quasi);
  6376. while (!quasi.tail) {
  6377. expressions.push(this.parseExpression());
  6378. quasi = this.parseTemplateElement();
  6379. quasis.push(quasi);
  6380. }
  6381. return this.finalize(node, new Node.TemplateLiteral(quasis, expressions));
  6382. };
  6383. // https://tc39.github.io/ecma262/#sec-grouping-operator
  6384. Parser.prototype.reinterpretExpressionAsPattern = function (expr) {
  6385. switch (expr.type) {
  6386. case syntax_1.Syntax.Identifier:
  6387. case syntax_1.Syntax.MemberExpression:
  6388. case syntax_1.Syntax.RestElement:
  6389. case syntax_1.Syntax.AssignmentPattern:
  6390. break;
  6391. case syntax_1.Syntax.SpreadElement:
  6392. expr.type = syntax_1.Syntax.RestElement;
  6393. this.reinterpretExpressionAsPattern(expr.argument);
  6394. break;
  6395. case syntax_1.Syntax.ArrayExpression:
  6396. expr.type = syntax_1.Syntax.ArrayPattern;
  6397. for (var i = 0; i < expr.elements.length; i++) {
  6398. if (expr.elements[i] !== null) {
  6399. this.reinterpretExpressionAsPattern(expr.elements[i]);
  6400. }
  6401. }
  6402. break;
  6403. case syntax_1.Syntax.ObjectExpression:
  6404. expr.type = syntax_1.Syntax.ObjectPattern;
  6405. for (var i = 0; i < expr.properties.length; i++) {
  6406. this.reinterpretExpressionAsPattern(expr.properties[i].value);
  6407. }
  6408. break;
  6409. case syntax_1.Syntax.AssignmentExpression:
  6410. expr.type = syntax_1.Syntax.AssignmentPattern;
  6411. delete expr.operator;
  6412. this.reinterpretExpressionAsPattern(expr.left);
  6413. break;
  6414. default:
  6415. // Allow other node type for tolerant parsing.
  6416. break;
  6417. }
  6418. };
  6419. Parser.prototype.parseGroupExpression = function () {
  6420. var expr;
  6421. this.expect('(');
  6422. if (this.match(')')) {
  6423. this.nextToken();
  6424. if (!this.match('=>')) {
  6425. this.expect('=>');
  6426. }
  6427. expr = {
  6428. type: ArrowParameterPlaceHolder,
  6429. params: [],
  6430. async: false
  6431. };
  6432. }
  6433. else {
  6434. var startToken = this.lookahead;
  6435. var params = [];
  6436. if (this.match('...')) {
  6437. expr = this.parseRestElement(params);
  6438. this.expect(')');
  6439. if (!this.match('=>')) {
  6440. this.expect('=>');
  6441. }
  6442. expr = {
  6443. type: ArrowParameterPlaceHolder,
  6444. params: [expr],
  6445. async: false
  6446. };
  6447. }
  6448. else {
  6449. var arrow = false;
  6450. this.context.isBindingElement = true;
  6451. expr = this.inheritCoverGrammar(this.parseAssignmentExpression);
  6452. if (this.match(',')) {
  6453. var expressions = [];
  6454. this.context.isAssignmentTarget = false;
  6455. expressions.push(expr);
  6456. while (this.lookahead.type !== 2 /* EOF */) {
  6457. if (!this.match(',')) {
  6458. break;
  6459. }
  6460. this.nextToken();
  6461. if (this.match(')')) {
  6462. this.nextToken();
  6463. for (var i = 0; i < expressions.length; i++) {
  6464. this.reinterpretExpressionAsPattern(expressions[i]);
  6465. }
  6466. arrow = true;
  6467. expr = {
  6468. type: ArrowParameterPlaceHolder,
  6469. params: expressions,
  6470. async: false
  6471. };
  6472. }
  6473. else if (this.match('...')) {
  6474. if (!this.context.isBindingElement) {
  6475. this.throwUnexpectedToken(this.lookahead);
  6476. }
  6477. expressions.push(this.parseRestElement(params));
  6478. this.expect(')');
  6479. if (!this.match('=>')) {
  6480. this.expect('=>');
  6481. }
  6482. this.context.isBindingElement = false;
  6483. for (var i = 0; i < expressions.length; i++) {
  6484. this.reinterpretExpressionAsPattern(expressions[i]);
  6485. }
  6486. arrow = true;
  6487. expr = {
  6488. type: ArrowParameterPlaceHolder,
  6489. params: expressions,
  6490. async: false
  6491. };
  6492. }
  6493. else {
  6494. expressions.push(this.inheritCoverGrammar(this.parseAssignmentExpression));
  6495. }
  6496. if (arrow) {
  6497. break;
  6498. }
  6499. }
  6500. if (!arrow) {
  6501. expr = this.finalize(this.startNode(startToken), new Node.SequenceExpression(expressions));
  6502. }
  6503. }
  6504. if (!arrow) {
  6505. this.expect(')');
  6506. if (this.match('=>')) {
  6507. if (expr.type === syntax_1.Syntax.Identifier && expr.name === 'yield') {
  6508. arrow = true;
  6509. expr = {
  6510. type: ArrowParameterPlaceHolder,
  6511. params: [expr],
  6512. async: false
  6513. };
  6514. }
  6515. if (!arrow) {
  6516. if (!this.context.isBindingElement) {
  6517. this.throwUnexpectedToken(this.lookahead);
  6518. }
  6519. if (expr.type === syntax_1.Syntax.SequenceExpression) {
  6520. for (var i = 0; i < expr.expressions.length; i++) {
  6521. this.reinterpretExpressionAsPattern(expr.expressions[i]);
  6522. }
  6523. }
  6524. else {
  6525. this.reinterpretExpressionAsPattern(expr);
  6526. }
  6527. var parameters = (expr.type === syntax_1.Syntax.SequenceExpression ? expr.expressions : [expr]);
  6528. expr = {
  6529. type: ArrowParameterPlaceHolder,
  6530. params: parameters,
  6531. async: false
  6532. };
  6533. }
  6534. }
  6535. this.context.isBindingElement = false;
  6536. }
  6537. }
  6538. }
  6539. return expr;
  6540. };
  6541. // https://tc39.github.io/ecma262/#sec-left-hand-side-expressions
  6542. Parser.prototype.parseArguments = function () {
  6543. this.expect('(');
  6544. var args = [];
  6545. if (!this.match(')')) {
  6546. while (true) {
  6547. var expr = this.match('...') ? this.parseSpreadElement() :
  6548. this.isolateCoverGrammar(this.parseAssignmentExpression);
  6549. args.push(expr);
  6550. if (this.match(')')) {
  6551. break;
  6552. }
  6553. this.expectCommaSeparator();
  6554. if (this.match(')')) {
  6555. break;
  6556. }
  6557. }
  6558. }
  6559. this.expect(')');
  6560. return args;
  6561. };
  6562. Parser.prototype.isIdentifierName = function (token) {
  6563. return token.type === 3 /* Identifier */ ||
  6564. token.type === 4 /* Keyword */ ||
  6565. token.type === 1 /* BooleanLiteral */ ||
  6566. token.type === 5 /* NullLiteral */;
  6567. };
  6568. Parser.prototype.parseIdentifierName = function () {
  6569. var node = this.createNode();
  6570. var token = this.nextToken();
  6571. if (!this.isIdentifierName(token)) {
  6572. this.throwUnexpectedToken(token);
  6573. }
  6574. return this.finalize(node, new Node.Identifier(token.value));
  6575. };
  6576. Parser.prototype.parseNewExpression = function () {
  6577. var node = this.createNode();
  6578. var id = this.parseIdentifierName();
  6579. assert_1.assert(id.name === 'new', 'New expression must start with `new`');
  6580. var expr;
  6581. if (this.match('.')) {
  6582. this.nextToken();
  6583. if (this.lookahead.type === 3 /* Identifier */ && this.context.inFunctionBody && this.lookahead.value === 'target') {
  6584. var property = this.parseIdentifierName();
  6585. expr = new Node.MetaProperty(id, property);
  6586. }
  6587. else {
  6588. this.throwUnexpectedToken(this.lookahead);
  6589. }
  6590. }
  6591. else {
  6592. var callee = this.isolateCoverGrammar(this.parseLeftHandSideExpression);
  6593. var args = this.match('(') ? this.parseArguments() : [];
  6594. expr = new Node.NewExpression(callee, args);
  6595. this.context.isAssignmentTarget = false;
  6596. this.context.isBindingElement = false;
  6597. }
  6598. return this.finalize(node, expr);
  6599. };
  6600. Parser.prototype.parseAsyncArgument = function () {
  6601. var arg = this.parseAssignmentExpression();
  6602. this.context.firstCoverInitializedNameError = null;
  6603. return arg;
  6604. };
  6605. Parser.prototype.parseAsyncArguments = function () {
  6606. this.expect('(');
  6607. var args = [];
  6608. if (!this.match(')')) {
  6609. while (true) {
  6610. var expr = this.match('...') ? this.parseSpreadElement() :
  6611. this.isolateCoverGrammar(this.parseAsyncArgument);
  6612. args.push(expr);
  6613. if (this.match(')')) {
  6614. break;
  6615. }
  6616. this.expectCommaSeparator();
  6617. if (this.match(')')) {
  6618. break;
  6619. }
  6620. }
  6621. }
  6622. this.expect(')');
  6623. return args;
  6624. };
  6625. Parser.prototype.parseLeftHandSideExpressionAllowCall = function () {
  6626. var startToken = this.lookahead;
  6627. var maybeAsync = this.matchContextualKeyword('async');
  6628. var previousAllowIn = this.context.allowIn;
  6629. this.context.allowIn = true;
  6630. var expr;
  6631. if (this.matchKeyword('super') && this.context.inFunctionBody) {
  6632. expr = this.createNode();
  6633. this.nextToken();
  6634. expr = this.finalize(expr, new Node.Super());
  6635. if (!this.match('(') && !this.match('.') && !this.match('[')) {
  6636. this.throwUnexpectedToken(this.lookahead);
  6637. }
  6638. }
  6639. else {
  6640. expr = this.inheritCoverGrammar(this.matchKeyword('new') ? this.parseNewExpression : this.parsePrimaryExpression);
  6641. }
  6642. while (true) {
  6643. if (this.match('.')) {
  6644. this.context.isBindingElement = false;
  6645. this.context.isAssignmentTarget = true;
  6646. this.expect('.');
  6647. var property = this.parseIdentifierName();
  6648. expr = this.finalize(this.startNode(startToken), new Node.StaticMemberExpression(expr, property));
  6649. }
  6650. else if (this.match('(')) {
  6651. var asyncArrow = maybeAsync && (startToken.lineNumber === this.lookahead.lineNumber);
  6652. this.context.isBindingElement = false;
  6653. this.context.isAssignmentTarget = false;
  6654. var args = asyncArrow ? this.parseAsyncArguments() : this.parseArguments();
  6655. expr = this.finalize(this.startNode(startToken), new Node.CallExpression(expr, args));
  6656. if (asyncArrow && this.match('=>')) {
  6657. for (var i = 0; i < args.length; ++i) {
  6658. this.reinterpretExpressionAsPattern(args[i]);
  6659. }
  6660. expr = {
  6661. type: ArrowParameterPlaceHolder,
  6662. params: args,
  6663. async: true
  6664. };
  6665. }
  6666. }
  6667. else if (this.match('[')) {
  6668. this.context.isBindingElement = false;
  6669. this.context.isAssignmentTarget = true;
  6670. this.expect('[');
  6671. var property = this.isolateCoverGrammar(this.parseExpression);
  6672. this.expect(']');
  6673. expr = this.finalize(this.startNode(startToken), new Node.ComputedMemberExpression(expr, property));
  6674. }
  6675. else if (this.lookahead.type === 10 /* Template */ && this.lookahead.head) {
  6676. var quasi = this.parseTemplateLiteral();
  6677. expr = this.finalize(this.startNode(startToken), new Node.TaggedTemplateExpression(expr, quasi));
  6678. }
  6679. else {
  6680. break;
  6681. }
  6682. }
  6683. this.context.allowIn = previousAllowIn;
  6684. return expr;
  6685. };
  6686. Parser.prototype.parseSuper = function () {
  6687. var node = this.createNode();
  6688. this.expectKeyword('super');
  6689. if (!this.match('[') && !this.match('.')) {
  6690. this.throwUnexpectedToken(this.lookahead);
  6691. }
  6692. return this.finalize(node, new Node.Super());
  6693. };
  6694. Parser.prototype.parseLeftHandSideExpression = function () {
  6695. assert_1.assert(this.context.allowIn, 'callee of new expression always allow in keyword.');
  6696. var node = this.startNode(this.lookahead);
  6697. var expr = (this.matchKeyword('super') && this.context.inFunctionBody) ? this.parseSuper() :
  6698. this.inheritCoverGrammar(this.matchKeyword('new') ? this.parseNewExpression : this.parsePrimaryExpression);
  6699. while (true) {
  6700. if (this.match('[')) {
  6701. this.context.isBindingElement = false;
  6702. this.context.isAssignmentTarget = true;
  6703. this.expect('[');
  6704. var property = this.isolateCoverGrammar(this.parseExpression);
  6705. this.expect(']');
  6706. expr = this.finalize(node, new Node.ComputedMemberExpression(expr, property));
  6707. }
  6708. else if (this.match('.')) {
  6709. this.context.isBindingElement = false;
  6710. this.context.isAssignmentTarget = true;
  6711. this.expect('.');
  6712. var property = this.parseIdentifierName();
  6713. expr = this.finalize(node, new Node.StaticMemberExpression(expr, property));
  6714. }
  6715. else if (this.lookahead.type === 10 /* Template */ && this.lookahead.head) {
  6716. var quasi = this.parseTemplateLiteral();
  6717. expr = this.finalize(node, new Node.TaggedTemplateExpression(expr, quasi));
  6718. }
  6719. else {
  6720. break;
  6721. }
  6722. }
  6723. return expr;
  6724. };
  6725. // https://tc39.github.io/ecma262/#sec-update-expressions
  6726. Parser.prototype.parseUpdateExpression = function () {
  6727. var expr;
  6728. var startToken = this.lookahead;
  6729. if (this.match('++') || this.match('--')) {
  6730. var node = this.startNode(startToken);
  6731. var token = this.nextToken();
  6732. expr = this.inheritCoverGrammar(this.parseUnaryExpression);
  6733. if (this.context.strict && expr.type === syntax_1.Syntax.Identifier && this.scanner.isRestrictedWord(expr.name)) {
  6734. this.tolerateError(messages_1.Messages.StrictLHSPrefix);
  6735. }
  6736. if (!this.context.isAssignmentTarget) {
  6737. this.tolerateError(messages_1.Messages.InvalidLHSInAssignment);
  6738. }
  6739. var prefix = true;
  6740. expr = this.finalize(node, new Node.UpdateExpression(token.value, expr, prefix));
  6741. this.context.isAssignmentTarget = false;
  6742. this.context.isBindingElement = false;
  6743. }
  6744. else {
  6745. expr = this.inheritCoverGrammar(this.parseLeftHandSideExpressionAllowCall);
  6746. if (!this.hasLineTerminator && this.lookahead.type === 7 /* Punctuator */) {
  6747. if (this.match('++') || this.match('--')) {
  6748. if (this.context.strict && expr.type === syntax_1.Syntax.Identifier && this.scanner.isRestrictedWord(expr.name)) {
  6749. this.tolerateError(messages_1.Messages.StrictLHSPostfix);
  6750. }
  6751. if (!this.context.isAssignmentTarget) {
  6752. this.tolerateError(messages_1.Messages.InvalidLHSInAssignment);
  6753. }
  6754. this.context.isAssignmentTarget = false;
  6755. this.context.isBindingElement = false;
  6756. var operator = this.nextToken().value;
  6757. var prefix = false;
  6758. expr = this.finalize(this.startNode(startToken), new Node.UpdateExpression(operator, expr, prefix));
  6759. }
  6760. }
  6761. }
  6762. return expr;
  6763. };
  6764. // https://tc39.github.io/ecma262/#sec-unary-operators
  6765. Parser.prototype.parseAwaitExpression = function () {
  6766. var node = this.createNode();
  6767. this.nextToken();
  6768. var argument = this.parseUnaryExpression();
  6769. return this.finalize(node, new Node.AwaitExpression(argument));
  6770. };
  6771. Parser.prototype.parseUnaryExpression = function () {
  6772. var expr;
  6773. if (this.match('+') || this.match('-') || this.match('~') || this.match('!') ||
  6774. this.matchKeyword('delete') || this.matchKeyword('void') || this.matchKeyword('typeof')) {
  6775. var node = this.startNode(this.lookahead);
  6776. var token = this.nextToken();
  6777. expr = this.inheritCoverGrammar(this.parseUnaryExpression);
  6778. expr = this.finalize(node, new Node.UnaryExpression(token.value, expr));
  6779. if (this.context.strict && expr.operator === 'delete' && expr.argument.type === syntax_1.Syntax.Identifier) {
  6780. this.tolerateError(messages_1.Messages.StrictDelete);
  6781. }
  6782. this.context.isAssignmentTarget = false;
  6783. this.context.isBindingElement = false;
  6784. }
  6785. else if (this.context.await && this.matchContextualKeyword('await')) {
  6786. expr = this.parseAwaitExpression();
  6787. }
  6788. else {
  6789. expr = this.parseUpdateExpression();
  6790. }
  6791. return expr;
  6792. };
  6793. Parser.prototype.parseExponentiationExpression = function () {
  6794. var startToken = this.lookahead;
  6795. var expr = this.inheritCoverGrammar(this.parseUnaryExpression);
  6796. if (expr.type !== syntax_1.Syntax.UnaryExpression && this.match('**')) {
  6797. this.nextToken();
  6798. this.context.isAssignmentTarget = false;
  6799. this.context.isBindingElement = false;
  6800. var left = expr;
  6801. var right = this.isolateCoverGrammar(this.parseExponentiationExpression);
  6802. expr = this.finalize(this.startNode(startToken), new Node.BinaryExpression('**', left, right));
  6803. }
  6804. return expr;
  6805. };
  6806. // https://tc39.github.io/ecma262/#sec-exp-operator
  6807. // https://tc39.github.io/ecma262/#sec-multiplicative-operators
  6808. // https://tc39.github.io/ecma262/#sec-additive-operators
  6809. // https://tc39.github.io/ecma262/#sec-bitwise-shift-operators
  6810. // https://tc39.github.io/ecma262/#sec-relational-operators
  6811. // https://tc39.github.io/ecma262/#sec-equality-operators
  6812. // https://tc39.github.io/ecma262/#sec-binary-bitwise-operators
  6813. // https://tc39.github.io/ecma262/#sec-binary-logical-operators
  6814. Parser.prototype.binaryPrecedence = function (token) {
  6815. var op = token.value;
  6816. var precedence;
  6817. if (token.type === 7 /* Punctuator */) {
  6818. precedence = this.operatorPrecedence[op] || 0;
  6819. }
  6820. else if (token.type === 4 /* Keyword */) {
  6821. precedence = (op === 'instanceof' || (this.context.allowIn && op === 'in')) ? 7 : 0;
  6822. }
  6823. else {
  6824. precedence = 0;
  6825. }
  6826. return precedence;
  6827. };
  6828. Parser.prototype.parseBinaryExpression = function () {
  6829. var startToken = this.lookahead;
  6830. var expr = this.inheritCoverGrammar(this.parseExponentiationExpression);
  6831. var token = this.lookahead;
  6832. var prec = this.binaryPrecedence(token);
  6833. if (prec > 0) {
  6834. this.nextToken();
  6835. this.context.isAssignmentTarget = false;
  6836. this.context.isBindingElement = false;
  6837. var markers = [startToken, this.lookahead];
  6838. var left = expr;
  6839. var right = this.isolateCoverGrammar(this.parseExponentiationExpression);
  6840. var stack = [left, token.value, right];
  6841. var precedences = [prec];
  6842. while (true) {
  6843. prec = this.binaryPrecedence(this.lookahead);
  6844. if (prec <= 0) {
  6845. break;
  6846. }
  6847. // Reduce: make a binary expression from the three topmost entries.
  6848. while ((stack.length > 2) && (prec <= precedences[precedences.length - 1])) {
  6849. right = stack.pop();
  6850. var operator = stack.pop();
  6851. precedences.pop();
  6852. left = stack.pop();
  6853. markers.pop();
  6854. var node = this.startNode(markers[markers.length - 1]);
  6855. stack.push(this.finalize(node, new Node.BinaryExpression(operator, left, right)));
  6856. }
  6857. // Shift.
  6858. stack.push(this.nextToken().value);
  6859. precedences.push(prec);
  6860. markers.push(this.lookahead);
  6861. stack.push(this.isolateCoverGrammar(this.parseExponentiationExpression));
  6862. }
  6863. // Final reduce to clean-up the stack.
  6864. var i = stack.length - 1;
  6865. expr = stack[i];
  6866. markers.pop();
  6867. while (i > 1) {
  6868. var node = this.startNode(markers.pop());
  6869. var operator = stack[i - 1];
  6870. expr = this.finalize(node, new Node.BinaryExpression(operator, stack[i - 2], expr));
  6871. i -= 2;
  6872. }
  6873. }
  6874. return expr;
  6875. };
  6876. // https://tc39.github.io/ecma262/#sec-conditional-operator
  6877. Parser.prototype.parseConditionalExpression = function () {
  6878. var startToken = this.lookahead;
  6879. var expr = this.inheritCoverGrammar(this.parseBinaryExpression);
  6880. if (this.match('?')) {
  6881. this.nextToken();
  6882. var previousAllowIn = this.context.allowIn;
  6883. this.context.allowIn = true;
  6884. var consequent = this.isolateCoverGrammar(this.parseAssignmentExpression);
  6885. this.context.allowIn = previousAllowIn;
  6886. this.expect(':');
  6887. var alternate = this.isolateCoverGrammar(this.parseAssignmentExpression);
  6888. expr = this.finalize(this.startNode(startToken), new Node.ConditionalExpression(expr, consequent, alternate));
  6889. this.context.isAssignmentTarget = false;
  6890. this.context.isBindingElement = false;
  6891. }
  6892. return expr;
  6893. };
  6894. // https://tc39.github.io/ecma262/#sec-assignment-operators
  6895. Parser.prototype.checkPatternParam = function (options, param) {
  6896. switch (param.type) {
  6897. case syntax_1.Syntax.Identifier:
  6898. this.validateParam(options, param, param.name);
  6899. break;
  6900. case syntax_1.Syntax.RestElement:
  6901. this.checkPatternParam(options, param.argument);
  6902. break;
  6903. case syntax_1.Syntax.AssignmentPattern:
  6904. this.checkPatternParam(options, param.left);
  6905. break;
  6906. case syntax_1.Syntax.ArrayPattern:
  6907. for (var i = 0; i < param.elements.length; i++) {
  6908. if (param.elements[i] !== null) {
  6909. this.checkPatternParam(options, param.elements[i]);
  6910. }
  6911. }
  6912. break;
  6913. case syntax_1.Syntax.ObjectPattern:
  6914. for (var i = 0; i < param.properties.length; i++) {
  6915. this.checkPatternParam(options, param.properties[i].value);
  6916. }
  6917. break;
  6918. default:
  6919. break;
  6920. }
  6921. options.simple = options.simple && (param instanceof Node.Identifier);
  6922. };
  6923. Parser.prototype.reinterpretAsCoverFormalsList = function (expr) {
  6924. var params = [expr];
  6925. var options;
  6926. var asyncArrow = false;
  6927. switch (expr.type) {
  6928. case syntax_1.Syntax.Identifier:
  6929. break;
  6930. case ArrowParameterPlaceHolder:
  6931. params = expr.params;
  6932. asyncArrow = expr.async;
  6933. break;
  6934. default:
  6935. return null;
  6936. }
  6937. options = {
  6938. simple: true,
  6939. paramSet: {}
  6940. };
  6941. for (var i = 0; i < params.length; ++i) {
  6942. var param = params[i];
  6943. if (param.type === syntax_1.Syntax.AssignmentPattern) {
  6944. if (param.right.type === syntax_1.Syntax.YieldExpression) {
  6945. if (param.right.argument) {
  6946. this.throwUnexpectedToken(this.lookahead);
  6947. }
  6948. param.right.type = syntax_1.Syntax.Identifier;
  6949. param.right.name = 'yield';
  6950. delete param.right.argument;
  6951. delete param.right.delegate;
  6952. }
  6953. }
  6954. else if (asyncArrow && param.type === syntax_1.Syntax.Identifier && param.name === 'await') {
  6955. this.throwUnexpectedToken(this.lookahead);
  6956. }
  6957. this.checkPatternParam(options, param);
  6958. params[i] = param;
  6959. }
  6960. if (this.context.strict || !this.context.allowYield) {
  6961. for (var i = 0; i < params.length; ++i) {
  6962. var param = params[i];
  6963. if (param.type === syntax_1.Syntax.YieldExpression) {
  6964. this.throwUnexpectedToken(this.lookahead);
  6965. }
  6966. }
  6967. }
  6968. if (options.message === messages_1.Messages.StrictParamDupe) {
  6969. var token = this.context.strict ? options.stricted : options.firstRestricted;
  6970. this.throwUnexpectedToken(token, options.message);
  6971. }
  6972. return {
  6973. simple: options.simple,
  6974. params: params,
  6975. stricted: options.stricted,
  6976. firstRestricted: options.firstRestricted,
  6977. message: options.message
  6978. };
  6979. };
  6980. Parser.prototype.parseAssignmentExpression = function () {
  6981. var expr;
  6982. if (!this.context.allowYield && this.matchKeyword('yield')) {
  6983. expr = this.parseYieldExpression();
  6984. }
  6985. else {
  6986. var startToken = this.lookahead;
  6987. var token = startToken;
  6988. expr = this.parseConditionalExpression();
  6989. if (token.type === 3 /* Identifier */ && (token.lineNumber === this.lookahead.lineNumber) && token.value === 'async') {
  6990. if (this.lookahead.type === 3 /* Identifier */ || this.matchKeyword('yield')) {
  6991. var arg = this.parsePrimaryExpression();
  6992. this.reinterpretExpressionAsPattern(arg);
  6993. expr = {
  6994. type: ArrowParameterPlaceHolder,
  6995. params: [arg],
  6996. async: true
  6997. };
  6998. }
  6999. }
  7000. if (expr.type === ArrowParameterPlaceHolder || this.match('=>')) {
  7001. // https://tc39.github.io/ecma262/#sec-arrow-function-definitions
  7002. this.context.isAssignmentTarget = false;
  7003. this.context.isBindingElement = false;
  7004. var isAsync = expr.async;
  7005. var list = this.reinterpretAsCoverFormalsList(expr);
  7006. if (list) {
  7007. if (this.hasLineTerminator) {
  7008. this.tolerateUnexpectedToken(this.lookahead);
  7009. }
  7010. this.context.firstCoverInitializedNameError = null;
  7011. var previousStrict = this.context.strict;
  7012. var previousAllowStrictDirective = this.context.allowStrictDirective;
  7013. this.context.allowStrictDirective = list.simple;
  7014. var previousAllowYield = this.context.allowYield;
  7015. var previousAwait = this.context.await;
  7016. this.context.allowYield = true;
  7017. this.context.await = isAsync;
  7018. var node = this.startNode(startToken);
  7019. this.expect('=>');
  7020. var body = void 0;
  7021. if (this.match('{')) {
  7022. var previousAllowIn = this.context.allowIn;
  7023. this.context.allowIn = true;
  7024. body = this.parseFunctionSourceElements();
  7025. this.context.allowIn = previousAllowIn;
  7026. }
  7027. else {
  7028. body = this.isolateCoverGrammar(this.parseAssignmentExpression);
  7029. }
  7030. var expression = body.type !== syntax_1.Syntax.BlockStatement;
  7031. if (this.context.strict && list.firstRestricted) {
  7032. this.throwUnexpectedToken(list.firstRestricted, list.message);
  7033. }
  7034. if (this.context.strict && list.stricted) {
  7035. this.tolerateUnexpectedToken(list.stricted, list.message);
  7036. }
  7037. expr = isAsync ? this.finalize(node, new Node.AsyncArrowFunctionExpression(list.params, body, expression)) :
  7038. this.finalize(node, new Node.ArrowFunctionExpression(list.params, body, expression));
  7039. this.context.strict = previousStrict;
  7040. this.context.allowStrictDirective = previousAllowStrictDirective;
  7041. this.context.allowYield = previousAllowYield;
  7042. this.context.await = previousAwait;
  7043. }
  7044. }
  7045. else {
  7046. if (this.matchAssign()) {
  7047. if (!this.context.isAssignmentTarget) {
  7048. this.tolerateError(messages_1.Messages.InvalidLHSInAssignment);
  7049. }
  7050. if (this.context.strict && expr.type === syntax_1.Syntax.Identifier) {
  7051. var id = expr;
  7052. if (this.scanner.isRestrictedWord(id.name)) {
  7053. this.tolerateUnexpectedToken(token, messages_1.Messages.StrictLHSAssignment);
  7054. }
  7055. if (this.scanner.isStrictModeReservedWord(id.name)) {
  7056. this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord);
  7057. }
  7058. }
  7059. if (!this.match('=')) {
  7060. this.context.isAssignmentTarget = false;
  7061. this.context.isBindingElement = false;
  7062. }
  7063. else {
  7064. this.reinterpretExpressionAsPattern(expr);
  7065. }
  7066. token = this.nextToken();
  7067. var operator = token.value;
  7068. var right = this.isolateCoverGrammar(this.parseAssignmentExpression);
  7069. expr = this.finalize(this.startNode(startToken), new Node.AssignmentExpression(operator, expr, right));
  7070. this.context.firstCoverInitializedNameError = null;
  7071. }
  7072. }
  7073. }
  7074. return expr;
  7075. };
  7076. // https://tc39.github.io/ecma262/#sec-comma-operator
  7077. Parser.prototype.parseExpression = function () {
  7078. var startToken = this.lookahead;
  7079. var expr = this.isolateCoverGrammar(this.parseAssignmentExpression);
  7080. if (this.match(',')) {
  7081. var expressions = [];
  7082. expressions.push(expr);
  7083. while (this.lookahead.type !== 2 /* EOF */) {
  7084. if (!this.match(',')) {
  7085. break;
  7086. }
  7087. this.nextToken();
  7088. expressions.push(this.isolateCoverGrammar(this.parseAssignmentExpression));
  7089. }
  7090. expr = this.finalize(this.startNode(startToken), new Node.SequenceExpression(expressions));
  7091. }
  7092. return expr;
  7093. };
  7094. // https://tc39.github.io/ecma262/#sec-block
  7095. Parser.prototype.parseStatementListItem = function () {
  7096. var statement;
  7097. this.context.isAssignmentTarget = true;
  7098. this.context.isBindingElement = true;
  7099. if (this.lookahead.type === 4 /* Keyword */) {
  7100. switch (this.lookahead.value) {
  7101. case 'export':
  7102. if (!this.context.isModule) {
  7103. this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.IllegalExportDeclaration);
  7104. }
  7105. statement = this.parseExportDeclaration();
  7106. break;
  7107. case 'import':
  7108. if (!this.context.isModule) {
  7109. this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.IllegalImportDeclaration);
  7110. }
  7111. statement = this.parseImportDeclaration();
  7112. break;
  7113. case 'const':
  7114. statement = this.parseLexicalDeclaration({ inFor: false });
  7115. break;
  7116. case 'function':
  7117. statement = this.parseFunctionDeclaration();
  7118. break;
  7119. case 'class':
  7120. statement = this.parseClassDeclaration();
  7121. break;
  7122. case 'let':
  7123. statement = this.isLexicalDeclaration() ? this.parseLexicalDeclaration({ inFor: false }) : this.parseStatement();
  7124. break;
  7125. default:
  7126. statement = this.parseStatement();
  7127. break;
  7128. }
  7129. }
  7130. else {
  7131. statement = this.parseStatement();
  7132. }
  7133. return statement;
  7134. };
  7135. Parser.prototype.parseBlock = function () {
  7136. var node = this.createNode();
  7137. this.expect('{');
  7138. var block = [];
  7139. while (true) {
  7140. if (this.match('}')) {
  7141. break;
  7142. }
  7143. block.push(this.parseStatementListItem());
  7144. }
  7145. this.expect('}');
  7146. return this.finalize(node, new Node.BlockStatement(block));
  7147. };
  7148. // https://tc39.github.io/ecma262/#sec-let-and-const-declarations
  7149. Parser.prototype.parseLexicalBinding = function (kind, options) {
  7150. var node = this.createNode();
  7151. var params = [];
  7152. var id = this.parsePattern(params, kind);
  7153. if (this.context.strict && id.type === syntax_1.Syntax.Identifier) {
  7154. if (this.scanner.isRestrictedWord(id.name)) {
  7155. this.tolerateError(messages_1.Messages.StrictVarName);
  7156. }
  7157. }
  7158. var init = null;
  7159. if (kind === 'const') {
  7160. if (!this.matchKeyword('in') && !this.matchContextualKeyword('of')) {
  7161. if (this.match('=')) {
  7162. this.nextToken();
  7163. init = this.isolateCoverGrammar(this.parseAssignmentExpression);
  7164. }
  7165. else {
  7166. this.throwError(messages_1.Messages.DeclarationMissingInitializer, 'const');
  7167. }
  7168. }
  7169. }
  7170. else if ((!options.inFor && id.type !== syntax_1.Syntax.Identifier) || this.match('=')) {
  7171. this.expect('=');
  7172. init = this.isolateCoverGrammar(this.parseAssignmentExpression);
  7173. }
  7174. return this.finalize(node, new Node.VariableDeclarator(id, init));
  7175. };
  7176. Parser.prototype.parseBindingList = function (kind, options) {
  7177. var list = [this.parseLexicalBinding(kind, options)];
  7178. while (this.match(',')) {
  7179. this.nextToken();
  7180. list.push(this.parseLexicalBinding(kind, options));
  7181. }
  7182. return list;
  7183. };
  7184. Parser.prototype.isLexicalDeclaration = function () {
  7185. var state = this.scanner.saveState();
  7186. this.scanner.scanComments();
  7187. var next = this.scanner.lex();
  7188. this.scanner.restoreState(state);
  7189. return (next.type === 3 /* Identifier */) ||
  7190. (next.type === 7 /* Punctuator */ && next.value === '[') ||
  7191. (next.type === 7 /* Punctuator */ && next.value === '{') ||
  7192. (next.type === 4 /* Keyword */ && next.value === 'let') ||
  7193. (next.type === 4 /* Keyword */ && next.value === 'yield');
  7194. };
  7195. Parser.prototype.parseLexicalDeclaration = function (options) {
  7196. var node = this.createNode();
  7197. var kind = this.nextToken().value;
  7198. assert_1.assert(kind === 'let' || kind === 'const', 'Lexical declaration must be either let or const');
  7199. var declarations = this.parseBindingList(kind, options);
  7200. this.consumeSemicolon();
  7201. return this.finalize(node, new Node.VariableDeclaration(declarations, kind));
  7202. };
  7203. // https://tc39.github.io/ecma262/#sec-destructuring-binding-patterns
  7204. Parser.prototype.parseBindingRestElement = function (params, kind) {
  7205. var node = this.createNode();
  7206. this.expect('...');
  7207. var arg = this.parsePattern(params, kind);
  7208. return this.finalize(node, new Node.RestElement(arg));
  7209. };
  7210. Parser.prototype.parseArrayPattern = function (params, kind) {
  7211. var node = this.createNode();
  7212. this.expect('[');
  7213. var elements = [];
  7214. while (!this.match(']')) {
  7215. if (this.match(',')) {
  7216. this.nextToken();
  7217. elements.push(null);
  7218. }
  7219. else {
  7220. if (this.match('...')) {
  7221. elements.push(this.parseBindingRestElement(params, kind));
  7222. break;
  7223. }
  7224. else {
  7225. elements.push(this.parsePatternWithDefault(params, kind));
  7226. }
  7227. if (!this.match(']')) {
  7228. this.expect(',');
  7229. }
  7230. }
  7231. }
  7232. this.expect(']');
  7233. return this.finalize(node, new Node.ArrayPattern(elements));
  7234. };
  7235. Parser.prototype.parsePropertyPattern = function (params, kind) {
  7236. var node = this.createNode();
  7237. var computed = false;
  7238. var shorthand = false;
  7239. var method = false;
  7240. var key;
  7241. var value;
  7242. if (this.lookahead.type === 3 /* Identifier */) {
  7243. var keyToken = this.lookahead;
  7244. key = this.parseVariableIdentifier();
  7245. var init = this.finalize(node, new Node.Identifier(keyToken.value));
  7246. if (this.match('=')) {
  7247. params.push(keyToken);
  7248. shorthand = true;
  7249. this.nextToken();
  7250. var expr = this.parseAssignmentExpression();
  7251. value = this.finalize(this.startNode(keyToken), new Node.AssignmentPattern(init, expr));
  7252. }
  7253. else if (!this.match(':')) {
  7254. params.push(keyToken);
  7255. shorthand = true;
  7256. value = init;
  7257. }
  7258. else {
  7259. this.expect(':');
  7260. value = this.parsePatternWithDefault(params, kind);
  7261. }
  7262. }
  7263. else {
  7264. computed = this.match('[');
  7265. key = this.parseObjectPropertyKey();
  7266. this.expect(':');
  7267. value = this.parsePatternWithDefault(params, kind);
  7268. }
  7269. return this.finalize(node, new Node.Property('init', key, computed, value, method, shorthand));
  7270. };
  7271. Parser.prototype.parseObjectPattern = function (params, kind) {
  7272. var node = this.createNode();
  7273. var properties = [];
  7274. this.expect('{');
  7275. while (!this.match('}')) {
  7276. properties.push(this.parsePropertyPattern(params, kind));
  7277. if (!this.match('}')) {
  7278. this.expect(',');
  7279. }
  7280. }
  7281. this.expect('}');
  7282. return this.finalize(node, new Node.ObjectPattern(properties));
  7283. };
  7284. Parser.prototype.parsePattern = function (params, kind) {
  7285. var pattern;
  7286. if (this.match('[')) {
  7287. pattern = this.parseArrayPattern(params, kind);
  7288. }
  7289. else if (this.match('{')) {
  7290. pattern = this.parseObjectPattern(params, kind);
  7291. }
  7292. else {
  7293. if (this.matchKeyword('let') && (kind === 'const' || kind === 'let')) {
  7294. this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.LetInLexicalBinding);
  7295. }
  7296. params.push(this.lookahead);
  7297. pattern = this.parseVariableIdentifier(kind);
  7298. }
  7299. return pattern;
  7300. };
  7301. Parser.prototype.parsePatternWithDefault = function (params, kind) {
  7302. var startToken = this.lookahead;
  7303. var pattern = this.parsePattern(params, kind);
  7304. if (this.match('=')) {
  7305. this.nextToken();
  7306. var previousAllowYield = this.context.allowYield;
  7307. this.context.allowYield = true;
  7308. var right = this.isolateCoverGrammar(this.parseAssignmentExpression);
  7309. this.context.allowYield = previousAllowYield;
  7310. pattern = this.finalize(this.startNode(startToken), new Node.AssignmentPattern(pattern, right));
  7311. }
  7312. return pattern;
  7313. };
  7314. // https://tc39.github.io/ecma262/#sec-variable-statement
  7315. Parser.prototype.parseVariableIdentifier = function (kind) {
  7316. var node = this.createNode();
  7317. var token = this.nextToken();
  7318. if (token.type === 4 /* Keyword */ && token.value === 'yield') {
  7319. if (this.context.strict) {
  7320. this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord);
  7321. }
  7322. else if (!this.context.allowYield) {
  7323. this.throwUnexpectedToken(token);
  7324. }
  7325. }
  7326. else if (token.type !== 3 /* Identifier */) {
  7327. if (this.context.strict && token.type === 4 /* Keyword */ && this.scanner.isStrictModeReservedWord(token.value)) {
  7328. this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord);
  7329. }
  7330. else {
  7331. if (this.context.strict || token.value !== 'let' || kind !== 'var') {
  7332. this.throwUnexpectedToken(token);
  7333. }
  7334. }
  7335. }
  7336. else if ((this.context.isModule || this.context.await) && token.type === 3 /* Identifier */ && token.value === 'await') {
  7337. this.tolerateUnexpectedToken(token);
  7338. }
  7339. return this.finalize(node, new Node.Identifier(token.value));
  7340. };
  7341. Parser.prototype.parseVariableDeclaration = function (options) {
  7342. var node = this.createNode();
  7343. var params = [];
  7344. var id = this.parsePattern(params, 'var');
  7345. if (this.context.strict && id.type === syntax_1.Syntax.Identifier) {
  7346. if (this.scanner.isRestrictedWord(id.name)) {
  7347. this.tolerateError(messages_1.Messages.StrictVarName);
  7348. }
  7349. }
  7350. var init = null;
  7351. if (this.match('=')) {
  7352. this.nextToken();
  7353. init = this.isolateCoverGrammar(this.parseAssignmentExpression);
  7354. }
  7355. else if (id.type !== syntax_1.Syntax.Identifier && !options.inFor) {
  7356. this.expect('=');
  7357. }
  7358. return this.finalize(node, new Node.VariableDeclarator(id, init));
  7359. };
  7360. Parser.prototype.parseVariableDeclarationList = function (options) {
  7361. var opt = { inFor: options.inFor };
  7362. var list = [];
  7363. list.push(this.parseVariableDeclaration(opt));
  7364. while (this.match(',')) {
  7365. this.nextToken();
  7366. list.push(this.parseVariableDeclaration(opt));
  7367. }
  7368. return list;
  7369. };
  7370. Parser.prototype.parseVariableStatement = function () {
  7371. var node = this.createNode();
  7372. this.expectKeyword('var');
  7373. var declarations = this.parseVariableDeclarationList({ inFor: false });
  7374. this.consumeSemicolon();
  7375. return this.finalize(node, new Node.VariableDeclaration(declarations, 'var'));
  7376. };
  7377. // https://tc39.github.io/ecma262/#sec-empty-statement
  7378. Parser.prototype.parseEmptyStatement = function () {
  7379. var node = this.createNode();
  7380. this.expect(';');
  7381. return this.finalize(node, new Node.EmptyStatement());
  7382. };
  7383. // https://tc39.github.io/ecma262/#sec-expression-statement
  7384. Parser.prototype.parseExpressionStatement = function () {
  7385. var node = this.createNode();
  7386. var expr = this.parseExpression();
  7387. this.consumeSemicolon();
  7388. return this.finalize(node, new Node.ExpressionStatement(expr));
  7389. };
  7390. // https://tc39.github.io/ecma262/#sec-if-statement
  7391. Parser.prototype.parseIfClause = function () {
  7392. if (this.context.strict && this.matchKeyword('function')) {
  7393. this.tolerateError(messages_1.Messages.StrictFunction);
  7394. }
  7395. return this.parseStatement();
  7396. };
  7397. Parser.prototype.parseIfStatement = function () {
  7398. var node = this.createNode();
  7399. var consequent;
  7400. var alternate = null;
  7401. this.expectKeyword('if');
  7402. this.expect('(');
  7403. var test = this.parseExpression();
  7404. if (!this.match(')') && this.config.tolerant) {
  7405. this.tolerateUnexpectedToken(this.nextToken());
  7406. consequent = this.finalize(this.createNode(), new Node.EmptyStatement());
  7407. }
  7408. else {
  7409. this.expect(')');
  7410. consequent = this.parseIfClause();
  7411. if (this.matchKeyword('else')) {
  7412. this.nextToken();
  7413. alternate = this.parseIfClause();
  7414. }
  7415. }
  7416. return this.finalize(node, new Node.IfStatement(test, consequent, alternate));
  7417. };
  7418. // https://tc39.github.io/ecma262/#sec-do-while-statement
  7419. Parser.prototype.parseDoWhileStatement = function () {
  7420. var node = this.createNode();
  7421. this.expectKeyword('do');
  7422. var previousInIteration = this.context.inIteration;
  7423. this.context.inIteration = true;
  7424. var body = this.parseStatement();
  7425. this.context.inIteration = previousInIteration;
  7426. this.expectKeyword('while');
  7427. this.expect('(');
  7428. var test = this.parseExpression();
  7429. if (!this.match(')') && this.config.tolerant) {
  7430. this.tolerateUnexpectedToken(this.nextToken());
  7431. }
  7432. else {
  7433. this.expect(')');
  7434. if (this.match(';')) {
  7435. this.nextToken();
  7436. }
  7437. }
  7438. return this.finalize(node, new Node.DoWhileStatement(body, test));
  7439. };
  7440. // https://tc39.github.io/ecma262/#sec-while-statement
  7441. Parser.prototype.parseWhileStatement = function () {
  7442. var node = this.createNode();
  7443. var body;
  7444. this.expectKeyword('while');
  7445. this.expect('(');
  7446. var test = this.parseExpression();
  7447. if (!this.match(')') && this.config.tolerant) {
  7448. this.tolerateUnexpectedToken(this.nextToken());
  7449. body = this.finalize(this.createNode(), new Node.EmptyStatement());
  7450. }
  7451. else {
  7452. this.expect(')');
  7453. var previousInIteration = this.context.inIteration;
  7454. this.context.inIteration = true;
  7455. body = this.parseStatement();
  7456. this.context.inIteration = previousInIteration;
  7457. }
  7458. return this.finalize(node, new Node.WhileStatement(test, body));
  7459. };
  7460. // https://tc39.github.io/ecma262/#sec-for-statement
  7461. // https://tc39.github.io/ecma262/#sec-for-in-and-for-of-statements
  7462. Parser.prototype.parseForStatement = function () {
  7463. var init = null;
  7464. var test = null;
  7465. var update = null;
  7466. var forIn = true;
  7467. var left, right;
  7468. var node = this.createNode();
  7469. this.expectKeyword('for');
  7470. this.expect('(');
  7471. if (this.match(';')) {
  7472. this.nextToken();
  7473. }
  7474. else {
  7475. if (this.matchKeyword('var')) {
  7476. init = this.createNode();
  7477. this.nextToken();
  7478. var previousAllowIn = this.context.allowIn;
  7479. this.context.allowIn = false;
  7480. var declarations = this.parseVariableDeclarationList({ inFor: true });
  7481. this.context.allowIn = previousAllowIn;
  7482. if (declarations.length === 1 && this.matchKeyword('in')) {
  7483. var decl = declarations[0];
  7484. if (decl.init && (decl.id.type === syntax_1.Syntax.ArrayPattern || decl.id.type === syntax_1.Syntax.ObjectPattern || this.context.strict)) {
  7485. this.tolerateError(messages_1.Messages.ForInOfLoopInitializer, 'for-in');
  7486. }
  7487. init = this.finalize(init, new Node.VariableDeclaration(declarations, 'var'));
  7488. this.nextToken();
  7489. left = init;
  7490. right = this.parseExpression();
  7491. init = null;
  7492. }
  7493. else if (declarations.length === 1 && declarations[0].init === null && this.matchContextualKeyword('of')) {
  7494. init = this.finalize(init, new Node.VariableDeclaration(declarations, 'var'));
  7495. this.nextToken();
  7496. left = init;
  7497. right = this.parseAssignmentExpression();
  7498. init = null;
  7499. forIn = false;
  7500. }
  7501. else {
  7502. init = this.finalize(init, new Node.VariableDeclaration(declarations, 'var'));
  7503. this.expect(';');
  7504. }
  7505. }
  7506. else if (this.matchKeyword('const') || this.matchKeyword('let')) {
  7507. init = this.createNode();
  7508. var kind = this.nextToken().value;
  7509. if (!this.context.strict && this.lookahead.value === 'in') {
  7510. init = this.finalize(init, new Node.Identifier(kind));
  7511. this.nextToken();
  7512. left = init;
  7513. right = this.parseExpression();
  7514. init = null;
  7515. }
  7516. else {
  7517. var previousAllowIn = this.context.allowIn;
  7518. this.context.allowIn = false;
  7519. var declarations = this.parseBindingList(kind, { inFor: true });
  7520. this.context.allowIn = previousAllowIn;
  7521. if (declarations.length === 1 && declarations[0].init === null && this.matchKeyword('in')) {
  7522. init = this.finalize(init, new Node.VariableDeclaration(declarations, kind));
  7523. this.nextToken();
  7524. left = init;
  7525. right = this.parseExpression();
  7526. init = null;
  7527. }
  7528. else if (declarations.length === 1 && declarations[0].init === null && this.matchContextualKeyword('of')) {
  7529. init = this.finalize(init, new Node.VariableDeclaration(declarations, kind));
  7530. this.nextToken();
  7531. left = init;
  7532. right = this.parseAssignmentExpression();
  7533. init = null;
  7534. forIn = false;
  7535. }
  7536. else {
  7537. this.consumeSemicolon();
  7538. init = this.finalize(init, new Node.VariableDeclaration(declarations, kind));
  7539. }
  7540. }
  7541. }
  7542. else {
  7543. var initStartToken = this.lookahead;
  7544. var previousAllowIn = this.context.allowIn;
  7545. this.context.allowIn = false;
  7546. init = this.inheritCoverGrammar(this.parseAssignmentExpression);
  7547. this.context.allowIn = previousAllowIn;
  7548. if (this.matchKeyword('in')) {
  7549. if (!this.context.isAssignmentTarget || init.type === syntax_1.Syntax.AssignmentExpression) {
  7550. this.tolerateError(messages_1.Messages.InvalidLHSInForIn);
  7551. }
  7552. this.nextToken();
  7553. this.reinterpretExpressionAsPattern(init);
  7554. left = init;
  7555. right = this.parseExpression();
  7556. init = null;
  7557. }
  7558. else if (this.matchContextualKeyword('of')) {
  7559. if (!this.context.isAssignmentTarget || init.type === syntax_1.Syntax.AssignmentExpression) {
  7560. this.tolerateError(messages_1.Messages.InvalidLHSInForLoop);
  7561. }
  7562. this.nextToken();
  7563. this.reinterpretExpressionAsPattern(init);
  7564. left = init;
  7565. right = this.parseAssignmentExpression();
  7566. init = null;
  7567. forIn = false;
  7568. }
  7569. else {
  7570. if (this.match(',')) {
  7571. var initSeq = [init];
  7572. while (this.match(',')) {
  7573. this.nextToken();
  7574. initSeq.push(this.isolateCoverGrammar(this.parseAssignmentExpression));
  7575. }
  7576. init = this.finalize(this.startNode(initStartToken), new Node.SequenceExpression(initSeq));
  7577. }
  7578. this.expect(';');
  7579. }
  7580. }
  7581. }
  7582. if (typeof left === 'undefined') {
  7583. if (!this.match(';')) {
  7584. test = this.parseExpression();
  7585. }
  7586. this.expect(';');
  7587. if (!this.match(')')) {
  7588. update = this.parseExpression();
  7589. }
  7590. }
  7591. var body;
  7592. if (!this.match(')') && this.config.tolerant) {
  7593. this.tolerateUnexpectedToken(this.nextToken());
  7594. body = this.finalize(this.createNode(), new Node.EmptyStatement());
  7595. }
  7596. else {
  7597. this.expect(')');
  7598. var previousInIteration = this.context.inIteration;
  7599. this.context.inIteration = true;
  7600. body = this.isolateCoverGrammar(this.parseStatement);
  7601. this.context.inIteration = previousInIteration;
  7602. }
  7603. return (typeof left === 'undefined') ?
  7604. this.finalize(node, new Node.ForStatement(init, test, update, body)) :
  7605. forIn ? this.finalize(node, new Node.ForInStatement(left, right, body)) :
  7606. this.finalize(node, new Node.ForOfStatement(left, right, body));
  7607. };
  7608. // https://tc39.github.io/ecma262/#sec-continue-statement
  7609. Parser.prototype.parseContinueStatement = function () {
  7610. var node = this.createNode();
  7611. this.expectKeyword('continue');
  7612. var label = null;
  7613. if (this.lookahead.type === 3 /* Identifier */ && !this.hasLineTerminator) {
  7614. var id = this.parseVariableIdentifier();
  7615. label = id;
  7616. var key = '$' + id.name;
  7617. if (!Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) {
  7618. this.throwError(messages_1.Messages.UnknownLabel, id.name);
  7619. }
  7620. }
  7621. this.consumeSemicolon();
  7622. if (label === null && !this.context.inIteration) {
  7623. this.throwError(messages_1.Messages.IllegalContinue);
  7624. }
  7625. return this.finalize(node, new Node.ContinueStatement(label));
  7626. };
  7627. // https://tc39.github.io/ecma262/#sec-break-statement
  7628. Parser.prototype.parseBreakStatement = function () {
  7629. var node = this.createNode();
  7630. this.expectKeyword('break');
  7631. var label = null;
  7632. if (this.lookahead.type === 3 /* Identifier */ && !this.hasLineTerminator) {
  7633. var id = this.parseVariableIdentifier();
  7634. var key = '$' + id.name;
  7635. if (!Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) {
  7636. this.throwError(messages_1.Messages.UnknownLabel, id.name);
  7637. }
  7638. label = id;
  7639. }
  7640. this.consumeSemicolon();
  7641. if (label === null && !this.context.inIteration && !this.context.inSwitch) {
  7642. this.throwError(messages_1.Messages.IllegalBreak);
  7643. }
  7644. return this.finalize(node, new Node.BreakStatement(label));
  7645. };
  7646. // https://tc39.github.io/ecma262/#sec-return-statement
  7647. Parser.prototype.parseReturnStatement = function () {
  7648. if (!this.context.inFunctionBody) {
  7649. this.tolerateError(messages_1.Messages.IllegalReturn);
  7650. }
  7651. var node = this.createNode();
  7652. this.expectKeyword('return');
  7653. var hasArgument = !this.match(';') && !this.match('}') &&
  7654. !this.hasLineTerminator && this.lookahead.type !== 2 /* EOF */;
  7655. var argument = hasArgument ? this.parseExpression() : null;
  7656. this.consumeSemicolon();
  7657. return this.finalize(node, new Node.ReturnStatement(argument));
  7658. };
  7659. // https://tc39.github.io/ecma262/#sec-with-statement
  7660. Parser.prototype.parseWithStatement = function () {
  7661. if (this.context.strict) {
  7662. this.tolerateError(messages_1.Messages.StrictModeWith);
  7663. }
  7664. var node = this.createNode();
  7665. var body;
  7666. this.expectKeyword('with');
  7667. this.expect('(');
  7668. var object = this.parseExpression();
  7669. if (!this.match(')') && this.config.tolerant) {
  7670. this.tolerateUnexpectedToken(this.nextToken());
  7671. body = this.finalize(this.createNode(), new Node.EmptyStatement());
  7672. }
  7673. else {
  7674. this.expect(')');
  7675. body = this.parseStatement();
  7676. }
  7677. return this.finalize(node, new Node.WithStatement(object, body));
  7678. };
  7679. // https://tc39.github.io/ecma262/#sec-switch-statement
  7680. Parser.prototype.parseSwitchCase = function () {
  7681. var node = this.createNode();
  7682. var test;
  7683. if (this.matchKeyword('default')) {
  7684. this.nextToken();
  7685. test = null;
  7686. }
  7687. else {
  7688. this.expectKeyword('case');
  7689. test = this.parseExpression();
  7690. }
  7691. this.expect(':');
  7692. var consequent = [];
  7693. while (true) {
  7694. if (this.match('}') || this.matchKeyword('default') || this.matchKeyword('case')) {
  7695. break;
  7696. }
  7697. consequent.push(this.parseStatementListItem());
  7698. }
  7699. return this.finalize(node, new Node.SwitchCase(test, consequent));
  7700. };
  7701. Parser.prototype.parseSwitchStatement = function () {
  7702. var node = this.createNode();
  7703. this.expectKeyword('switch');
  7704. this.expect('(');
  7705. var discriminant = this.parseExpression();
  7706. this.expect(')');
  7707. var previousInSwitch = this.context.inSwitch;
  7708. this.context.inSwitch = true;
  7709. var cases = [];
  7710. var defaultFound = false;
  7711. this.expect('{');
  7712. while (true) {
  7713. if (this.match('}')) {
  7714. break;
  7715. }
  7716. var clause = this.parseSwitchCase();
  7717. if (clause.test === null) {
  7718. if (defaultFound) {
  7719. this.throwError(messages_1.Messages.MultipleDefaultsInSwitch);
  7720. }
  7721. defaultFound = true;
  7722. }
  7723. cases.push(clause);
  7724. }
  7725. this.expect('}');
  7726. this.context.inSwitch = previousInSwitch;
  7727. return this.finalize(node, new Node.SwitchStatement(discriminant, cases));
  7728. };
  7729. // https://tc39.github.io/ecma262/#sec-labelled-statements
  7730. Parser.prototype.parseLabelledStatement = function () {
  7731. var node = this.createNode();
  7732. var expr = this.parseExpression();
  7733. var statement;
  7734. if ((expr.type === syntax_1.Syntax.Identifier) && this.match(':')) {
  7735. this.nextToken();
  7736. var id = expr;
  7737. var key = '$' + id.name;
  7738. if (Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) {
  7739. this.throwError(messages_1.Messages.Redeclaration, 'Label', id.name);
  7740. }
  7741. this.context.labelSet[key] = true;
  7742. var body = void 0;
  7743. if (this.matchKeyword('class')) {
  7744. this.tolerateUnexpectedToken(this.lookahead);
  7745. body = this.parseClassDeclaration();
  7746. }
  7747. else if (this.matchKeyword('function')) {
  7748. var token = this.lookahead;
  7749. var declaration = this.parseFunctionDeclaration();
  7750. if (this.context.strict) {
  7751. this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunction);
  7752. }
  7753. else if (declaration.generator) {
  7754. this.tolerateUnexpectedToken(token, messages_1.Messages.GeneratorInLegacyContext);
  7755. }
  7756. body = declaration;
  7757. }
  7758. else {
  7759. body = this.parseStatement();
  7760. }
  7761. delete this.context.labelSet[key];
  7762. statement = new Node.LabeledStatement(id, body);
  7763. }
  7764. else {
  7765. this.consumeSemicolon();
  7766. statement = new Node.ExpressionStatement(expr);
  7767. }
  7768. return this.finalize(node, statement);
  7769. };
  7770. // https://tc39.github.io/ecma262/#sec-throw-statement
  7771. Parser.prototype.parseThrowStatement = function () {
  7772. var node = this.createNode();
  7773. this.expectKeyword('throw');
  7774. if (this.hasLineTerminator) {
  7775. this.throwError(messages_1.Messages.NewlineAfterThrow);
  7776. }
  7777. var argument = this.parseExpression();
  7778. this.consumeSemicolon();
  7779. return this.finalize(node, new Node.ThrowStatement(argument));
  7780. };
  7781. // https://tc39.github.io/ecma262/#sec-try-statement
  7782. Parser.prototype.parseCatchClause = function () {
  7783. var node = this.createNode();
  7784. this.expectKeyword('catch');
  7785. this.expect('(');
  7786. if (this.match(')')) {
  7787. this.throwUnexpectedToken(this.lookahead);
  7788. }
  7789. var params = [];
  7790. var param = this.parsePattern(params);
  7791. var paramMap = {};
  7792. for (var i = 0; i < params.length; i++) {
  7793. var key = '$' + params[i].value;
  7794. if (Object.prototype.hasOwnProperty.call(paramMap, key)) {
  7795. this.tolerateError(messages_1.Messages.DuplicateBinding, params[i].value);
  7796. }
  7797. paramMap[key] = true;
  7798. }
  7799. if (this.context.strict && param.type === syntax_1.Syntax.Identifier) {
  7800. if (this.scanner.isRestrictedWord(param.name)) {
  7801. this.tolerateError(messages_1.Messages.StrictCatchVariable);
  7802. }
  7803. }
  7804. this.expect(')');
  7805. var body = this.parseBlock();
  7806. return this.finalize(node, new Node.CatchClause(param, body));
  7807. };
  7808. Parser.prototype.parseFinallyClause = function () {
  7809. this.expectKeyword('finally');
  7810. return this.parseBlock();
  7811. };
  7812. Parser.prototype.parseTryStatement = function () {
  7813. var node = this.createNode();
  7814. this.expectKeyword('try');
  7815. var block = this.parseBlock();
  7816. var handler = this.matchKeyword('catch') ? this.parseCatchClause() : null;
  7817. var finalizer = this.matchKeyword('finally') ? this.parseFinallyClause() : null;
  7818. if (!handler && !finalizer) {
  7819. this.throwError(messages_1.Messages.NoCatchOrFinally);
  7820. }
  7821. return this.finalize(node, new Node.TryStatement(block, handler, finalizer));
  7822. };
  7823. // https://tc39.github.io/ecma262/#sec-debugger-statement
  7824. Parser.prototype.parseDebuggerStatement = function () {
  7825. var node = this.createNode();
  7826. this.expectKeyword('debugger');
  7827. this.consumeSemicolon();
  7828. return this.finalize(node, new Node.DebuggerStatement());
  7829. };
  7830. // https://tc39.github.io/ecma262/#sec-ecmascript-language-statements-and-declarations
  7831. Parser.prototype.parseStatement = function () {
  7832. var statement;
  7833. switch (this.lookahead.type) {
  7834. case 1 /* BooleanLiteral */:
  7835. case 5 /* NullLiteral */:
  7836. case 6 /* NumericLiteral */:
  7837. case 8 /* StringLiteral */:
  7838. case 10 /* Template */:
  7839. case 9 /* RegularExpression */:
  7840. statement = this.parseExpressionStatement();
  7841. break;
  7842. case 7 /* Punctuator */:
  7843. var value = this.lookahead.value;
  7844. if (value === '{') {
  7845. statement = this.parseBlock();
  7846. }
  7847. else if (value === '(') {
  7848. statement = this.parseExpressionStatement();
  7849. }
  7850. else if (value === ';') {
  7851. statement = this.parseEmptyStatement();
  7852. }
  7853. else {
  7854. statement = this.parseExpressionStatement();
  7855. }
  7856. break;
  7857. case 3 /* Identifier */:
  7858. statement = this.matchAsyncFunction() ? this.parseFunctionDeclaration() : this.parseLabelledStatement();
  7859. break;
  7860. case 4 /* Keyword */:
  7861. switch (this.lookahead.value) {
  7862. case 'break':
  7863. statement = this.parseBreakStatement();
  7864. break;
  7865. case 'continue':
  7866. statement = this.parseContinueStatement();
  7867. break;
  7868. case 'debugger':
  7869. statement = this.parseDebuggerStatement();
  7870. break;
  7871. case 'do':
  7872. statement = this.parseDoWhileStatement();
  7873. break;
  7874. case 'for':
  7875. statement = this.parseForStatement();
  7876. break;
  7877. case 'function':
  7878. statement = this.parseFunctionDeclaration();
  7879. break;
  7880. case 'if':
  7881. statement = this.parseIfStatement();
  7882. break;
  7883. case 'return':
  7884. statement = this.parseReturnStatement();
  7885. break;
  7886. case 'switch':
  7887. statement = this.parseSwitchStatement();
  7888. break;
  7889. case 'throw':
  7890. statement = this.parseThrowStatement();
  7891. break;
  7892. case 'try':
  7893. statement = this.parseTryStatement();
  7894. break;
  7895. case 'var':
  7896. statement = this.parseVariableStatement();
  7897. break;
  7898. case 'while':
  7899. statement = this.parseWhileStatement();
  7900. break;
  7901. case 'with':
  7902. statement = this.parseWithStatement();
  7903. break;
  7904. default:
  7905. statement = this.parseExpressionStatement();
  7906. break;
  7907. }
  7908. break;
  7909. default:
  7910. statement = this.throwUnexpectedToken(this.lookahead);
  7911. }
  7912. return statement;
  7913. };
  7914. // https://tc39.github.io/ecma262/#sec-function-definitions
  7915. Parser.prototype.parseFunctionSourceElements = function () {
  7916. var node = this.createNode();
  7917. this.expect('{');
  7918. var body = this.parseDirectivePrologues();
  7919. var previousLabelSet = this.context.labelSet;
  7920. var previousInIteration = this.context.inIteration;
  7921. var previousInSwitch = this.context.inSwitch;
  7922. var previousInFunctionBody = this.context.inFunctionBody;
  7923. this.context.labelSet = {};
  7924. this.context.inIteration = false;
  7925. this.context.inSwitch = false;
  7926. this.context.inFunctionBody = true;
  7927. while (this.lookahead.type !== 2 /* EOF */) {
  7928. if (this.match('}')) {
  7929. break;
  7930. }
  7931. body.push(this.parseStatementListItem());
  7932. }
  7933. this.expect('}');
  7934. this.context.labelSet = previousLabelSet;
  7935. this.context.inIteration = previousInIteration;
  7936. this.context.inSwitch = previousInSwitch;
  7937. this.context.inFunctionBody = previousInFunctionBody;
  7938. return this.finalize(node, new Node.BlockStatement(body));
  7939. };
  7940. Parser.prototype.validateParam = function (options, param, name) {
  7941. var key = '$' + name;
  7942. if (this.context.strict) {
  7943. if (this.scanner.isRestrictedWord(name)) {
  7944. options.stricted = param;
  7945. options.message = messages_1.Messages.StrictParamName;
  7946. }
  7947. if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) {
  7948. options.stricted = param;
  7949. options.message = messages_1.Messages.StrictParamDupe;
  7950. }
  7951. }
  7952. else if (!options.firstRestricted) {
  7953. if (this.scanner.isRestrictedWord(name)) {
  7954. options.firstRestricted = param;
  7955. options.message = messages_1.Messages.StrictParamName;
  7956. }
  7957. else if (this.scanner.isStrictModeReservedWord(name)) {
  7958. options.firstRestricted = param;
  7959. options.message = messages_1.Messages.StrictReservedWord;
  7960. }
  7961. else if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) {
  7962. options.stricted = param;
  7963. options.message = messages_1.Messages.StrictParamDupe;
  7964. }
  7965. }
  7966. /* istanbul ignore next */
  7967. if (typeof Object.defineProperty === 'function') {
  7968. Object.defineProperty(options.paramSet, key, { value: true, enumerable: true, writable: true, configurable: true });
  7969. }
  7970. else {
  7971. options.paramSet[key] = true;
  7972. }
  7973. };
  7974. Parser.prototype.parseRestElement = function (params) {
  7975. var node = this.createNode();
  7976. this.expect('...');
  7977. var arg = this.parsePattern(params);
  7978. if (this.match('=')) {
  7979. this.throwError(messages_1.Messages.DefaultRestParameter);
  7980. }
  7981. if (!this.match(')')) {
  7982. this.throwError(messages_1.Messages.ParameterAfterRestParameter);
  7983. }
  7984. return this.finalize(node, new Node.RestElement(arg));
  7985. };
  7986. Parser.prototype.parseFormalParameter = function (options) {
  7987. var params = [];
  7988. var param = this.match('...') ? this.parseRestElement(params) : this.parsePatternWithDefault(params);
  7989. for (var i = 0; i < params.length; i++) {
  7990. this.validateParam(options, params[i], params[i].value);
  7991. }
  7992. options.simple = options.simple && (param instanceof Node.Identifier);
  7993. options.params.push(param);
  7994. };
  7995. Parser.prototype.parseFormalParameters = function (firstRestricted) {
  7996. var options;
  7997. options = {
  7998. simple: true,
  7999. params: [],
  8000. firstRestricted: firstRestricted
  8001. };
  8002. this.expect('(');
  8003. if (!this.match(')')) {
  8004. options.paramSet = {};
  8005. while (this.lookahead.type !== 2 /* EOF */) {
  8006. this.parseFormalParameter(options);
  8007. if (this.match(')')) {
  8008. break;
  8009. }
  8010. this.expect(',');
  8011. if (this.match(')')) {
  8012. break;
  8013. }
  8014. }
  8015. }
  8016. this.expect(')');
  8017. return {
  8018. simple: options.simple,
  8019. params: options.params,
  8020. stricted: options.stricted,
  8021. firstRestricted: options.firstRestricted,
  8022. message: options.message
  8023. };
  8024. };
  8025. Parser.prototype.matchAsyncFunction = function () {
  8026. var match = this.matchContextualKeyword('async');
  8027. if (match) {
  8028. var state = this.scanner.saveState();
  8029. this.scanner.scanComments();
  8030. var next = this.scanner.lex();
  8031. this.scanner.restoreState(state);
  8032. match = (state.lineNumber === next.lineNumber) && (next.type === 4 /* Keyword */) && (next.value === 'function');
  8033. }
  8034. return match;
  8035. };
  8036. Parser.prototype.parseFunctionDeclaration = function (identifierIsOptional) {
  8037. var node = this.createNode();
  8038. var isAsync = this.matchContextualKeyword('async');
  8039. if (isAsync) {
  8040. this.nextToken();
  8041. }
  8042. this.expectKeyword('function');
  8043. var isGenerator = isAsync ? false : this.match('*');
  8044. if (isGenerator) {
  8045. this.nextToken();
  8046. }
  8047. var message;
  8048. var id = null;
  8049. var firstRestricted = null;
  8050. if (!identifierIsOptional || !this.match('(')) {
  8051. var token = this.lookahead;
  8052. id = this.parseVariableIdentifier();
  8053. if (this.context.strict) {
  8054. if (this.scanner.isRestrictedWord(token.value)) {
  8055. this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunctionName);
  8056. }
  8057. }
  8058. else {
  8059. if (this.scanner.isRestrictedWord(token.value)) {
  8060. firstRestricted = token;
  8061. message = messages_1.Messages.StrictFunctionName;
  8062. }
  8063. else if (this.scanner.isStrictModeReservedWord(token.value)) {
  8064. firstRestricted = token;
  8065. message = messages_1.Messages.StrictReservedWord;
  8066. }
  8067. }
  8068. }
  8069. var previousAllowAwait = this.context.await;
  8070. var previousAllowYield = this.context.allowYield;
  8071. this.context.await = isAsync;
  8072. this.context.allowYield = !isGenerator;
  8073. var formalParameters = this.parseFormalParameters(firstRestricted);
  8074. var params = formalParameters.params;
  8075. var stricted = formalParameters.stricted;
  8076. firstRestricted = formalParameters.firstRestricted;
  8077. if (formalParameters.message) {
  8078. message = formalParameters.message;
  8079. }
  8080. var previousStrict = this.context.strict;
  8081. var previousAllowStrictDirective = this.context.allowStrictDirective;
  8082. this.context.allowStrictDirective = formalParameters.simple;
  8083. var body = this.parseFunctionSourceElements();
  8084. if (this.context.strict && firstRestricted) {
  8085. this.throwUnexpectedToken(firstRestricted, message);
  8086. }
  8087. if (this.context.strict && stricted) {
  8088. this.tolerateUnexpectedToken(stricted, message);
  8089. }
  8090. this.context.strict = previousStrict;
  8091. this.context.allowStrictDirective = previousAllowStrictDirective;
  8092. this.context.await = previousAllowAwait;
  8093. this.context.allowYield = previousAllowYield;
  8094. return isAsync ? this.finalize(node, new Node.AsyncFunctionDeclaration(id, params, body)) :
  8095. this.finalize(node, new Node.FunctionDeclaration(id, params, body, isGenerator));
  8096. };
  8097. Parser.prototype.parseFunctionExpression = function () {
  8098. var node = this.createNode();
  8099. var isAsync = this.matchContextualKeyword('async');
  8100. if (isAsync) {
  8101. this.nextToken();
  8102. }
  8103. this.expectKeyword('function');
  8104. var isGenerator = isAsync ? false : this.match('*');
  8105. if (isGenerator) {
  8106. this.nextToken();
  8107. }
  8108. var message;
  8109. var id = null;
  8110. var firstRestricted;
  8111. var previousAllowAwait = this.context.await;
  8112. var previousAllowYield = this.context.allowYield;
  8113. this.context.await = isAsync;
  8114. this.context.allowYield = !isGenerator;
  8115. if (!this.match('(')) {
  8116. var token = this.lookahead;
  8117. id = (!this.context.strict && !isGenerator && this.matchKeyword('yield')) ? this.parseIdentifierName() : this.parseVariableIdentifier();
  8118. if (this.context.strict) {
  8119. if (this.scanner.isRestrictedWord(token.value)) {
  8120. this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunctionName);
  8121. }
  8122. }
  8123. else {
  8124. if (this.scanner.isRestrictedWord(token.value)) {
  8125. firstRestricted = token;
  8126. message = messages_1.Messages.StrictFunctionName;
  8127. }
  8128. else if (this.scanner.isStrictModeReservedWord(token.value)) {
  8129. firstRestricted = token;
  8130. message = messages_1.Messages.StrictReservedWord;
  8131. }
  8132. }
  8133. }
  8134. var formalParameters = this.parseFormalParameters(firstRestricted);
  8135. var params = formalParameters.params;
  8136. var stricted = formalParameters.stricted;
  8137. firstRestricted = formalParameters.firstRestricted;
  8138. if (formalParameters.message) {
  8139. message = formalParameters.message;
  8140. }
  8141. var previousStrict = this.context.strict;
  8142. var previousAllowStrictDirective = this.context.allowStrictDirective;
  8143. this.context.allowStrictDirective = formalParameters.simple;
  8144. var body = this.parseFunctionSourceElements();
  8145. if (this.context.strict && firstRestricted) {
  8146. this.throwUnexpectedToken(firstRestricted, message);
  8147. }
  8148. if (this.context.strict && stricted) {
  8149. this.tolerateUnexpectedToken(stricted, message);
  8150. }
  8151. this.context.strict = previousStrict;
  8152. this.context.allowStrictDirective = previousAllowStrictDirective;
  8153. this.context.await = previousAllowAwait;
  8154. this.context.allowYield = previousAllowYield;
  8155. return isAsync ? this.finalize(node, new Node.AsyncFunctionExpression(id, params, body)) :
  8156. this.finalize(node, new Node.FunctionExpression(id, params, body, isGenerator));
  8157. };
  8158. // https://tc39.github.io/ecma262/#sec-directive-prologues-and-the-use-strict-directive
  8159. Parser.prototype.parseDirective = function () {
  8160. var token = this.lookahead;
  8161. var node = this.createNode();
  8162. var expr = this.parseExpression();
  8163. var directive = (expr.type === syntax_1.Syntax.Literal) ? this.getTokenRaw(token).slice(1, -1) : null;
  8164. this.consumeSemicolon();
  8165. return this.finalize(node, directive ? new Node.Directive(expr, directive) : new Node.ExpressionStatement(expr));
  8166. };
  8167. Parser.prototype.parseDirectivePrologues = function () {
  8168. var firstRestricted = null;
  8169. var body = [];
  8170. while (true) {
  8171. var token = this.lookahead;
  8172. if (token.type !== 8 /* StringLiteral */) {
  8173. break;
  8174. }
  8175. var statement = this.parseDirective();
  8176. body.push(statement);
  8177. var directive = statement.directive;
  8178. if (typeof directive !== 'string') {
  8179. break;
  8180. }
  8181. if (directive === 'use strict') {
  8182. this.context.strict = true;
  8183. if (firstRestricted) {
  8184. this.tolerateUnexpectedToken(firstRestricted, messages_1.Messages.StrictOctalLiteral);
  8185. }
  8186. if (!this.context.allowStrictDirective) {
  8187. this.tolerateUnexpectedToken(token, messages_1.Messages.IllegalLanguageModeDirective);
  8188. }
  8189. }
  8190. else {
  8191. if (!firstRestricted && token.octal) {
  8192. firstRestricted = token;
  8193. }
  8194. }
  8195. }
  8196. return body;
  8197. };
  8198. // https://tc39.github.io/ecma262/#sec-method-definitions
  8199. Parser.prototype.qualifiedPropertyName = function (token) {
  8200. switch (token.type) {
  8201. case 3 /* Identifier */:
  8202. case 8 /* StringLiteral */:
  8203. case 1 /* BooleanLiteral */:
  8204. case 5 /* NullLiteral */:
  8205. case 6 /* NumericLiteral */:
  8206. case 4 /* Keyword */:
  8207. return true;
  8208. case 7 /* Punctuator */:
  8209. return token.value === '[';
  8210. default:
  8211. break;
  8212. }
  8213. return false;
  8214. };
  8215. Parser.prototype.parseGetterMethod = function () {
  8216. var node = this.createNode();
  8217. var isGenerator = false;
  8218. var previousAllowYield = this.context.allowYield;
  8219. this.context.allowYield = false;
  8220. var formalParameters = this.parseFormalParameters();
  8221. if (formalParameters.params.length > 0) {
  8222. this.tolerateError(messages_1.Messages.BadGetterArity);
  8223. }
  8224. var method = this.parsePropertyMethod(formalParameters);
  8225. this.context.allowYield = previousAllowYield;
  8226. return this.finalize(node, new Node.FunctionExpression(null, formalParameters.params, method, isGenerator));
  8227. };
  8228. Parser.prototype.parseSetterMethod = function () {
  8229. var node = this.createNode();
  8230. var isGenerator = false;
  8231. var previousAllowYield = this.context.allowYield;
  8232. this.context.allowYield = false;
  8233. var formalParameters = this.parseFormalParameters();
  8234. if (formalParameters.params.length !== 1) {
  8235. this.tolerateError(messages_1.Messages.BadSetterArity);
  8236. }
  8237. else if (formalParameters.params[0] instanceof Node.RestElement) {
  8238. this.tolerateError(messages_1.Messages.BadSetterRestParameter);
  8239. }
  8240. var method = this.parsePropertyMethod(formalParameters);
  8241. this.context.allowYield = previousAllowYield;
  8242. return this.finalize(node, new Node.FunctionExpression(null, formalParameters.params, method, isGenerator));
  8243. };
  8244. Parser.prototype.parseGeneratorMethod = function () {
  8245. var node = this.createNode();
  8246. var isGenerator = true;
  8247. var previousAllowYield = this.context.allowYield;
  8248. this.context.allowYield = true;
  8249. var params = this.parseFormalParameters();
  8250. this.context.allowYield = false;
  8251. var method = this.parsePropertyMethod(params);
  8252. this.context.allowYield = previousAllowYield;
  8253. return this.finalize(node, new Node.FunctionExpression(null, params.params, method, isGenerator));
  8254. };
  8255. // https://tc39.github.io/ecma262/#sec-generator-function-definitions
  8256. Parser.prototype.isStartOfExpression = function () {
  8257. var start = true;
  8258. var value = this.lookahead.value;
  8259. switch (this.lookahead.type) {
  8260. case 7 /* Punctuator */:
  8261. start = (value === '[') || (value === '(') || (value === '{') ||
  8262. (value === '+') || (value === '-') ||
  8263. (value === '!') || (value === '~') ||
  8264. (value === '++') || (value === '--') ||
  8265. (value === '/') || (value === '/='); // regular expression literal
  8266. break;
  8267. case 4 /* Keyword */:
  8268. start = (value === 'class') || (value === 'delete') ||
  8269. (value === 'function') || (value === 'let') || (value === 'new') ||
  8270. (value === 'super') || (value === 'this') || (value === 'typeof') ||
  8271. (value === 'void') || (value === 'yield');
  8272. break;
  8273. default:
  8274. break;
  8275. }
  8276. return start;
  8277. };
  8278. Parser.prototype.parseYieldExpression = function () {
  8279. var node = this.createNode();
  8280. this.expectKeyword('yield');
  8281. var argument = null;
  8282. var delegate = false;
  8283. if (!this.hasLineTerminator) {
  8284. var previousAllowYield = this.context.allowYield;
  8285. this.context.allowYield = false;
  8286. delegate = this.match('*');
  8287. if (delegate) {
  8288. this.nextToken();
  8289. argument = this.parseAssignmentExpression();
  8290. }
  8291. else if (this.isStartOfExpression()) {
  8292. argument = this.parseAssignmentExpression();
  8293. }
  8294. this.context.allowYield = previousAllowYield;
  8295. }
  8296. return this.finalize(node, new Node.YieldExpression(argument, delegate));
  8297. };
  8298. // https://tc39.github.io/ecma262/#sec-class-definitions
  8299. Parser.prototype.parseClassElement = function (hasConstructor) {
  8300. var token = this.lookahead;
  8301. var node = this.createNode();
  8302. var kind = '';
  8303. var key = null;
  8304. var value = null;
  8305. var computed = false;
  8306. var method = false;
  8307. var isStatic = false;
  8308. var isAsync = false;
  8309. if (this.match('*')) {
  8310. this.nextToken();
  8311. }
  8312. else {
  8313. computed = this.match('[');
  8314. key = this.parseObjectPropertyKey();
  8315. var id = key;
  8316. if (id.name === 'static' && (this.qualifiedPropertyName(this.lookahead) || this.match('*'))) {
  8317. token = this.lookahead;
  8318. isStatic = true;
  8319. computed = this.match('[');
  8320. if (this.match('*')) {
  8321. this.nextToken();
  8322. }
  8323. else {
  8324. key = this.parseObjectPropertyKey();
  8325. }
  8326. }
  8327. if ((token.type === 3 /* Identifier */) && !this.hasLineTerminator && (token.value === 'async')) {
  8328. var punctuator = this.lookahead.value;
  8329. if (punctuator !== ':' && punctuator !== '(' && punctuator !== '*') {
  8330. isAsync = true;
  8331. token = this.lookahead;
  8332. key = this.parseObjectPropertyKey();
  8333. if (token.type === 3 /* Identifier */) {
  8334. if (token.value === 'get' || token.value === 'set') {
  8335. this.tolerateUnexpectedToken(token);
  8336. }
  8337. else if (token.value === 'constructor') {
  8338. this.tolerateUnexpectedToken(token, messages_1.Messages.ConstructorIsAsync);
  8339. }
  8340. }
  8341. }
  8342. }
  8343. }
  8344. var lookaheadPropertyKey = this.qualifiedPropertyName(this.lookahead);
  8345. if (token.type === 3 /* Identifier */) {
  8346. if (token.value === 'get' && lookaheadPropertyKey) {
  8347. kind = 'get';
  8348. computed = this.match('[');
  8349. key = this.parseObjectPropertyKey();
  8350. this.context.allowYield = false;
  8351. value = this.parseGetterMethod();
  8352. }
  8353. else if (token.value === 'set' && lookaheadPropertyKey) {
  8354. kind = 'set';
  8355. computed = this.match('[');
  8356. key = this.parseObjectPropertyKey();
  8357. value = this.parseSetterMethod();
  8358. }
  8359. }
  8360. else if (token.type === 7 /* Punctuator */ && token.value === '*' && lookaheadPropertyKey) {
  8361. kind = 'init';
  8362. computed = this.match('[');
  8363. key = this.parseObjectPropertyKey();
  8364. value = this.parseGeneratorMethod();
  8365. method = true;
  8366. }
  8367. if (!kind && key && this.match('(')) {
  8368. kind = 'init';
  8369. value = isAsync ? this.parsePropertyMethodAsyncFunction() : this.parsePropertyMethodFunction();
  8370. method = true;
  8371. }
  8372. if (!kind) {
  8373. this.throwUnexpectedToken(this.lookahead);
  8374. }
  8375. if (kind === 'init') {
  8376. kind = 'method';
  8377. }
  8378. if (!computed) {
  8379. if (isStatic && this.isPropertyKey(key, 'prototype')) {
  8380. this.throwUnexpectedToken(token, messages_1.Messages.StaticPrototype);
  8381. }
  8382. if (!isStatic && this.isPropertyKey(key, 'constructor')) {
  8383. if (kind !== 'method' || !method || (value && value.generator)) {
  8384. this.throwUnexpectedToken(token, messages_1.Messages.ConstructorSpecialMethod);
  8385. }
  8386. if (hasConstructor.value) {
  8387. this.throwUnexpectedToken(token, messages_1.Messages.DuplicateConstructor);
  8388. }
  8389. else {
  8390. hasConstructor.value = true;
  8391. }
  8392. kind = 'constructor';
  8393. }
  8394. }
  8395. return this.finalize(node, new Node.MethodDefinition(key, computed, value, kind, isStatic));
  8396. };
  8397. Parser.prototype.parseClassElementList = function () {
  8398. var body = [];
  8399. var hasConstructor = { value: false };
  8400. this.expect('{');
  8401. while (!this.match('}')) {
  8402. if (this.match(';')) {
  8403. this.nextToken();
  8404. }
  8405. else {
  8406. body.push(this.parseClassElement(hasConstructor));
  8407. }
  8408. }
  8409. this.expect('}');
  8410. return body;
  8411. };
  8412. Parser.prototype.parseClassBody = function () {
  8413. var node = this.createNode();
  8414. var elementList = this.parseClassElementList();
  8415. return this.finalize(node, new Node.ClassBody(elementList));
  8416. };
  8417. Parser.prototype.parseClassDeclaration = function (identifierIsOptional) {
  8418. var node = this.createNode();
  8419. var previousStrict = this.context.strict;
  8420. this.context.strict = true;
  8421. this.expectKeyword('class');
  8422. var id = (identifierIsOptional && (this.lookahead.type !== 3 /* Identifier */)) ? null : this.parseVariableIdentifier();
  8423. var superClass = null;
  8424. if (this.matchKeyword('extends')) {
  8425. this.nextToken();
  8426. superClass = this.isolateCoverGrammar(this.parseLeftHandSideExpressionAllowCall);
  8427. }
  8428. var classBody = this.parseClassBody();
  8429. this.context.strict = previousStrict;
  8430. return this.finalize(node, new Node.ClassDeclaration(id, superClass, classBody));
  8431. };
  8432. Parser.prototype.parseClassExpression = function () {
  8433. var node = this.createNode();
  8434. var previousStrict = this.context.strict;
  8435. this.context.strict = true;
  8436. this.expectKeyword('class');
  8437. var id = (this.lookahead.type === 3 /* Identifier */) ? this.parseVariableIdentifier() : null;
  8438. var superClass = null;
  8439. if (this.matchKeyword('extends')) {
  8440. this.nextToken();
  8441. superClass = this.isolateCoverGrammar(this.parseLeftHandSideExpressionAllowCall);
  8442. }
  8443. var classBody = this.parseClassBody();
  8444. this.context.strict = previousStrict;
  8445. return this.finalize(node, new Node.ClassExpression(id, superClass, classBody));
  8446. };
  8447. // https://tc39.github.io/ecma262/#sec-scripts
  8448. // https://tc39.github.io/ecma262/#sec-modules
  8449. Parser.prototype.parseModule = function () {
  8450. this.context.strict = true;
  8451. this.context.isModule = true;
  8452. var node = this.createNode();
  8453. var body = this.parseDirectivePrologues();
  8454. while (this.lookahead.type !== 2 /* EOF */) {
  8455. body.push(this.parseStatementListItem());
  8456. }
  8457. return this.finalize(node, new Node.Module(body));
  8458. };
  8459. Parser.prototype.parseScript = function () {
  8460. var node = this.createNode();
  8461. var body = this.parseDirectivePrologues();
  8462. while (this.lookahead.type !== 2 /* EOF */) {
  8463. body.push(this.parseStatementListItem());
  8464. }
  8465. return this.finalize(node, new Node.Script(body));
  8466. };
  8467. // https://tc39.github.io/ecma262/#sec-imports
  8468. Parser.prototype.parseModuleSpecifier = function () {
  8469. var node = this.createNode();
  8470. if (this.lookahead.type !== 8 /* StringLiteral */) {
  8471. this.throwError(messages_1.Messages.InvalidModuleSpecifier);
  8472. }
  8473. var token = this.nextToken();
  8474. var raw = this.getTokenRaw(token);
  8475. return this.finalize(node, new Node.Literal(token.value, raw));
  8476. };
  8477. // import {<foo as bar>} ...;
  8478. Parser.prototype.parseImportSpecifier = function () {
  8479. var node = this.createNode();
  8480. var imported;
  8481. var local;
  8482. if (this.lookahead.type === 3 /* Identifier */) {
  8483. imported = this.parseVariableIdentifier();
  8484. local = imported;
  8485. if (this.matchContextualKeyword('as')) {
  8486. this.nextToken();
  8487. local = this.parseVariableIdentifier();
  8488. }
  8489. }
  8490. else {
  8491. imported = this.parseIdentifierName();
  8492. local = imported;
  8493. if (this.matchContextualKeyword('as')) {
  8494. this.nextToken();
  8495. local = this.parseVariableIdentifier();
  8496. }
  8497. else {
  8498. this.throwUnexpectedToken(this.nextToken());
  8499. }
  8500. }
  8501. return this.finalize(node, new Node.ImportSpecifier(local, imported));
  8502. };
  8503. // {foo, bar as bas}
  8504. Parser.prototype.parseNamedImports = function () {
  8505. this.expect('{');
  8506. var specifiers = [];
  8507. while (!this.match('}')) {
  8508. specifiers.push(this.parseImportSpecifier());
  8509. if (!this.match('}')) {
  8510. this.expect(',');
  8511. }
  8512. }
  8513. this.expect('}');
  8514. return specifiers;
  8515. };
  8516. // import <foo> ...;
  8517. Parser.prototype.parseImportDefaultSpecifier = function () {
  8518. var node = this.createNode();
  8519. var local = this.parseIdentifierName();
  8520. return this.finalize(node, new Node.ImportDefaultSpecifier(local));
  8521. };
  8522. // import <* as foo> ...;
  8523. Parser.prototype.parseImportNamespaceSpecifier = function () {
  8524. var node = this.createNode();
  8525. this.expect('*');
  8526. if (!this.matchContextualKeyword('as')) {
  8527. this.throwError(messages_1.Messages.NoAsAfterImportNamespace);
  8528. }
  8529. this.nextToken();
  8530. var local = this.parseIdentifierName();
  8531. return this.finalize(node, new Node.ImportNamespaceSpecifier(local));
  8532. };
  8533. Parser.prototype.parseImportDeclaration = function () {
  8534. if (this.context.inFunctionBody) {
  8535. this.throwError(messages_1.Messages.IllegalImportDeclaration);
  8536. }
  8537. var node = this.createNode();
  8538. this.expectKeyword('import');
  8539. var src;
  8540. var specifiers = [];
  8541. if (this.lookahead.type === 8 /* StringLiteral */) {
  8542. // import 'foo';
  8543. src = this.parseModuleSpecifier();
  8544. }
  8545. else {
  8546. if (this.match('{')) {
  8547. // import {bar}
  8548. specifiers = specifiers.concat(this.parseNamedImports());
  8549. }
  8550. else if (this.match('*')) {
  8551. // import * as foo
  8552. specifiers.push(this.parseImportNamespaceSpecifier());
  8553. }
  8554. else if (this.isIdentifierName(this.lookahead) && !this.matchKeyword('default')) {
  8555. // import foo
  8556. specifiers.push(this.parseImportDefaultSpecifier());
  8557. if (this.match(',')) {
  8558. this.nextToken();
  8559. if (this.match('*')) {
  8560. // import foo, * as foo
  8561. specifiers.push(this.parseImportNamespaceSpecifier());
  8562. }
  8563. else if (this.match('{')) {
  8564. // import foo, {bar}
  8565. specifiers = specifiers.concat(this.parseNamedImports());
  8566. }
  8567. else {
  8568. this.throwUnexpectedToken(this.lookahead);
  8569. }
  8570. }
  8571. }
  8572. else {
  8573. this.throwUnexpectedToken(this.nextToken());
  8574. }
  8575. if (!this.matchContextualKeyword('from')) {
  8576. var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause;
  8577. this.throwError(message, this.lookahead.value);
  8578. }
  8579. this.nextToken();
  8580. src = this.parseModuleSpecifier();
  8581. }
  8582. this.consumeSemicolon();
  8583. return this.finalize(node, new Node.ImportDeclaration(specifiers, src));
  8584. };
  8585. // https://tc39.github.io/ecma262/#sec-exports
  8586. Parser.prototype.parseExportSpecifier = function () {
  8587. var node = this.createNode();
  8588. var local = this.parseIdentifierName();
  8589. var exported = local;
  8590. if (this.matchContextualKeyword('as')) {
  8591. this.nextToken();
  8592. exported = this.parseIdentifierName();
  8593. }
  8594. return this.finalize(node, new Node.ExportSpecifier(local, exported));
  8595. };
  8596. Parser.prototype.parseExportDeclaration = function () {
  8597. if (this.context.inFunctionBody) {
  8598. this.throwError(messages_1.Messages.IllegalExportDeclaration);
  8599. }
  8600. var node = this.createNode();
  8601. this.expectKeyword('export');
  8602. var exportDeclaration;
  8603. if (this.matchKeyword('default')) {
  8604. // export default ...
  8605. this.nextToken();
  8606. if (this.matchKeyword('function')) {
  8607. // export default function foo () {}
  8608. // export default function () {}
  8609. var declaration = this.parseFunctionDeclaration(true);
  8610. exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration));
  8611. }
  8612. else if (this.matchKeyword('class')) {
  8613. // export default class foo {}
  8614. var declaration = this.parseClassDeclaration(true);
  8615. exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration));
  8616. }
  8617. else if (this.matchContextualKeyword('async')) {
  8618. // export default async function f () {}
  8619. // export default async function () {}
  8620. // export default async x => x
  8621. var declaration = this.matchAsyncFunction() ? this.parseFunctionDeclaration(true) : this.parseAssignmentExpression();
  8622. exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration));
  8623. }
  8624. else {
  8625. if (this.matchContextualKeyword('from')) {
  8626. this.throwError(messages_1.Messages.UnexpectedToken, this.lookahead.value);
  8627. }
  8628. // export default {};
  8629. // export default [];
  8630. // export default (1 + 2);
  8631. var declaration = this.match('{') ? this.parseObjectInitializer() :
  8632. this.match('[') ? this.parseArrayInitializer() : this.parseAssignmentExpression();
  8633. this.consumeSemicolon();
  8634. exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration));
  8635. }
  8636. }
  8637. else if (this.match('*')) {
  8638. // export * from 'foo';
  8639. this.nextToken();
  8640. if (!this.matchContextualKeyword('from')) {
  8641. var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause;
  8642. this.throwError(message, this.lookahead.value);
  8643. }
  8644. this.nextToken();
  8645. var src = this.parseModuleSpecifier();
  8646. this.consumeSemicolon();
  8647. exportDeclaration = this.finalize(node, new Node.ExportAllDeclaration(src));
  8648. }
  8649. else if (this.lookahead.type === 4 /* Keyword */) {
  8650. // export var f = 1;
  8651. var declaration = void 0;
  8652. switch (this.lookahead.value) {
  8653. case 'let':
  8654. case 'const':
  8655. declaration = this.parseLexicalDeclaration({ inFor: false });
  8656. break;
  8657. case 'var':
  8658. case 'class':
  8659. case 'function':
  8660. declaration = this.parseStatementListItem();
  8661. break;
  8662. default:
  8663. this.throwUnexpectedToken(this.lookahead);
  8664. }
  8665. exportDeclaration = this.finalize(node, new Node.ExportNamedDeclaration(declaration, [], null));
  8666. }
  8667. else if (this.matchAsyncFunction()) {
  8668. var declaration = this.parseFunctionDeclaration();
  8669. exportDeclaration = this.finalize(node, new Node.ExportNamedDeclaration(declaration, [], null));
  8670. }
  8671. else {
  8672. var specifiers = [];
  8673. var source = null;
  8674. var isExportFromIdentifier = false;
  8675. this.expect('{');
  8676. while (!this.match('}')) {
  8677. isExportFromIdentifier = isExportFromIdentifier || this.matchKeyword('default');
  8678. specifiers.push(this.parseExportSpecifier());
  8679. if (!this.match('}')) {
  8680. this.expect(',');
  8681. }
  8682. }
  8683. this.expect('}');
  8684. if (this.matchContextualKeyword('from')) {
  8685. // export {default} from 'foo';
  8686. // export {foo} from 'foo';
  8687. this.nextToken();
  8688. source = this.parseModuleSpecifier();
  8689. this.consumeSemicolon();
  8690. }
  8691. else if (isExportFromIdentifier) {
  8692. // export {default}; // missing fromClause
  8693. var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause;
  8694. this.throwError(message, this.lookahead.value);
  8695. }
  8696. else {
  8697. // export {foo};
  8698. this.consumeSemicolon();
  8699. }
  8700. exportDeclaration = this.finalize(node, new Node.ExportNamedDeclaration(null, specifiers, source));
  8701. }
  8702. return exportDeclaration;
  8703. };
  8704. return Parser;
  8705. }());
  8706. exports.Parser = Parser;
  8707. /***/ },
  8708. /* 9 */
  8709. /***/ function(module, exports) {
  8710. "use strict";
  8711. // Ensure the condition is true, otherwise throw an error.
  8712. // This is only to have a better contract semantic, i.e. another safety net
  8713. // to catch a logic error. The condition shall be fulfilled in normal case.
  8714. // Do NOT use this to enforce a certain condition on any user input.
  8715. Object.defineProperty(exports, "__esModule", { value: true });
  8716. function assert(condition, message) {
  8717. /* istanbul ignore if */
  8718. if (!condition) {
  8719. throw new Error('ASSERT: ' + message);
  8720. }
  8721. }
  8722. exports.assert = assert;
  8723. /***/ },
  8724. /* 10 */
  8725. /***/ function(module, exports) {
  8726. "use strict";
  8727. /* tslint:disable:max-classes-per-file */
  8728. Object.defineProperty(exports, "__esModule", { value: true });
  8729. var ErrorHandler = (function () {
  8730. function ErrorHandler() {
  8731. this.errors = [];
  8732. this.tolerant = false;
  8733. }
  8734. ErrorHandler.prototype.recordError = function (error) {
  8735. this.errors.push(error);
  8736. };
  8737. ErrorHandler.prototype.tolerate = function (error) {
  8738. if (this.tolerant) {
  8739. this.recordError(error);
  8740. }
  8741. else {
  8742. throw error;
  8743. }
  8744. };
  8745. ErrorHandler.prototype.constructError = function (msg, column) {
  8746. var error = new Error(msg);
  8747. try {
  8748. throw error;
  8749. }
  8750. catch (base) {
  8751. /* istanbul ignore else */
  8752. if (Object.create && Object.defineProperty) {
  8753. error = Object.create(base);
  8754. Object.defineProperty(error, 'column', { value: column });
  8755. }
  8756. }
  8757. /* istanbul ignore next */
  8758. return error;
  8759. };
  8760. ErrorHandler.prototype.createError = function (index, line, col, description) {
  8761. var msg = 'Line ' + line + ': ' + description;
  8762. var error = this.constructError(msg, col);
  8763. error.index = index;
  8764. error.lineNumber = line;
  8765. error.description = description;
  8766. return error;
  8767. };
  8768. ErrorHandler.prototype.throwError = function (index, line, col, description) {
  8769. throw this.createError(index, line, col, description);
  8770. };
  8771. ErrorHandler.prototype.tolerateError = function (index, line, col, description) {
  8772. var error = this.createError(index, line, col, description);
  8773. if (this.tolerant) {
  8774. this.recordError(error);
  8775. }
  8776. else {
  8777. throw error;
  8778. }
  8779. };
  8780. return ErrorHandler;
  8781. }());
  8782. exports.ErrorHandler = ErrorHandler;
  8783. /***/ },
  8784. /* 11 */
  8785. /***/ function(module, exports) {
  8786. "use strict";
  8787. Object.defineProperty(exports, "__esModule", { value: true });
  8788. // Error messages should be identical to V8.
  8789. exports.Messages = {
  8790. BadGetterArity: 'Getter must not have any formal parameters',
  8791. BadSetterArity: 'Setter must have exactly one formal parameter',
  8792. BadSetterRestParameter: 'Setter function argument must not be a rest parameter',
  8793. ConstructorIsAsync: 'Class constructor may not be an async method',
  8794. ConstructorSpecialMethod: 'Class constructor may not be an accessor',
  8795. DeclarationMissingInitializer: 'Missing initializer in %0 declaration',
  8796. DefaultRestParameter: 'Unexpected token =',
  8797. DuplicateBinding: 'Duplicate binding %0',
  8798. DuplicateConstructor: 'A class may only have one constructor',
  8799. DuplicateProtoProperty: 'Duplicate __proto__ fields are not allowed in object literals',
  8800. ForInOfLoopInitializer: '%0 loop variable declaration may not have an initializer',
  8801. GeneratorInLegacyContext: 'Generator declarations are not allowed in legacy contexts',
  8802. IllegalBreak: 'Illegal break statement',
  8803. IllegalContinue: 'Illegal continue statement',
  8804. IllegalExportDeclaration: 'Unexpected token',
  8805. IllegalImportDeclaration: 'Unexpected token',
  8806. IllegalLanguageModeDirective: 'Illegal \'use strict\' directive in function with non-simple parameter list',
  8807. IllegalReturn: 'Illegal return statement',
  8808. InvalidEscapedReservedWord: 'Keyword must not contain escaped characters',
  8809. InvalidHexEscapeSequence: 'Invalid hexadecimal escape sequence',
  8810. InvalidLHSInAssignment: 'Invalid left-hand side in assignment',
  8811. InvalidLHSInForIn: 'Invalid left-hand side in for-in',
  8812. InvalidLHSInForLoop: 'Invalid left-hand side in for-loop',
  8813. InvalidModuleSpecifier: 'Unexpected token',
  8814. InvalidRegExp: 'Invalid regular expression',
  8815. LetInLexicalBinding: 'let is disallowed as a lexically bound name',
  8816. MissingFromClause: 'Unexpected token',
  8817. MultipleDefaultsInSwitch: 'More than one default clause in switch statement',
  8818. NewlineAfterThrow: 'Illegal newline after throw',
  8819. NoAsAfterImportNamespace: 'Unexpected token',
  8820. NoCatchOrFinally: 'Missing catch or finally after try',
  8821. ParameterAfterRestParameter: 'Rest parameter must be last formal parameter',
  8822. Redeclaration: '%0 \'%1\' has already been declared',
  8823. StaticPrototype: 'Classes may not have static property named prototype',
  8824. StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode',
  8825. StrictDelete: 'Delete of an unqualified identifier in strict mode.',
  8826. StrictFunction: 'In strict mode code, functions can only be declared at top level or inside a block',
  8827. StrictFunctionName: 'Function name may not be eval or arguments in strict mode',
  8828. StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode',
  8829. StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode',
  8830. StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode',
  8831. StrictModeWith: 'Strict mode code may not include a with statement',
  8832. StrictOctalLiteral: 'Octal literals are not allowed in strict mode.',
  8833. StrictParamDupe: 'Strict mode function may not have duplicate parameter names',
  8834. StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode',
  8835. StrictReservedWord: 'Use of future reserved word in strict mode',
  8836. StrictVarName: 'Variable name may not be eval or arguments in strict mode',
  8837. TemplateOctalLiteral: 'Octal literals are not allowed in template strings.',
  8838. UnexpectedEOS: 'Unexpected end of input',
  8839. UnexpectedIdentifier: 'Unexpected identifier',
  8840. UnexpectedNumber: 'Unexpected number',
  8841. UnexpectedReserved: 'Unexpected reserved word',
  8842. UnexpectedString: 'Unexpected string',
  8843. UnexpectedTemplate: 'Unexpected quasi %0',
  8844. UnexpectedToken: 'Unexpected token %0',
  8845. UnexpectedTokenIllegal: 'Unexpected token ILLEGAL',
  8846. UnknownLabel: 'Undefined label \'%0\'',
  8847. UnterminatedRegExp: 'Invalid regular expression: missing /'
  8848. };
  8849. /***/ },
  8850. /* 12 */
  8851. /***/ function(module, exports, __webpack_require__) {
  8852. "use strict";
  8853. Object.defineProperty(exports, "__esModule", { value: true });
  8854. var assert_1 = __webpack_require__(9);
  8855. var character_1 = __webpack_require__(4);
  8856. var messages_1 = __webpack_require__(11);
  8857. function hexValue(ch) {
  8858. return '0123456789abcdef'.indexOf(ch.toLowerCase());
  8859. }
  8860. function octalValue(ch) {
  8861. return '01234567'.indexOf(ch);
  8862. }
  8863. var Scanner = (function () {
  8864. function Scanner(code, handler) {
  8865. this.source = code;
  8866. this.errorHandler = handler;
  8867. this.trackComment = false;
  8868. this.length = code.length;
  8869. this.index = 0;
  8870. this.lineNumber = (code.length > 0) ? 1 : 0;
  8871. this.lineStart = 0;
  8872. this.curlyStack = [];
  8873. }
  8874. Scanner.prototype.saveState = function () {
  8875. return {
  8876. index: this.index,
  8877. lineNumber: this.lineNumber,
  8878. lineStart: this.lineStart
  8879. };
  8880. };
  8881. Scanner.prototype.restoreState = function (state) {
  8882. this.index = state.index;
  8883. this.lineNumber = state.lineNumber;
  8884. this.lineStart = state.lineStart;
  8885. };
  8886. Scanner.prototype.eof = function () {
  8887. return this.index >= this.length;
  8888. };
  8889. Scanner.prototype.throwUnexpectedToken = function (message) {
  8890. if (message === void 0) { message = messages_1.Messages.UnexpectedTokenIllegal; }
  8891. return this.errorHandler.throwError(this.index, this.lineNumber, this.index - this.lineStart + 1, message);
  8892. };
  8893. Scanner.prototype.tolerateUnexpectedToken = function (message) {
  8894. if (message === void 0) { message = messages_1.Messages.UnexpectedTokenIllegal; }
  8895. this.errorHandler.tolerateError(this.index, this.lineNumber, this.index - this.lineStart + 1, message);
  8896. };
  8897. // https://tc39.github.io/ecma262/#sec-comments
  8898. Scanner.prototype.skipSingleLineComment = function (offset) {
  8899. var comments = [];
  8900. var start, loc;
  8901. if (this.trackComment) {
  8902. comments = [];
  8903. start = this.index - offset;
  8904. loc = {
  8905. start: {
  8906. line: this.lineNumber,
  8907. column: this.index - this.lineStart - offset
  8908. },
  8909. end: {}
  8910. };
  8911. }
  8912. while (!this.eof()) {
  8913. var ch = this.source.charCodeAt(this.index);
  8914. ++this.index;
  8915. if (character_1.Character.isLineTerminator(ch)) {
  8916. if (this.trackComment) {
  8917. loc.end = {
  8918. line: this.lineNumber,
  8919. column: this.index - this.lineStart - 1
  8920. };
  8921. var entry = {
  8922. multiLine: false,
  8923. slice: [start + offset, this.index - 1],
  8924. range: [start, this.index - 1],
  8925. loc: loc
  8926. };
  8927. comments.push(entry);
  8928. }
  8929. if (ch === 13 && this.source.charCodeAt(this.index) === 10) {
  8930. ++this.index;
  8931. }
  8932. ++this.lineNumber;
  8933. this.lineStart = this.index;
  8934. return comments;
  8935. }
  8936. }
  8937. if (this.trackComment) {
  8938. loc.end = {
  8939. line: this.lineNumber,
  8940. column: this.index - this.lineStart
  8941. };
  8942. var entry = {
  8943. multiLine: false,
  8944. slice: [start + offset, this.index],
  8945. range: [start, this.index],
  8946. loc: loc
  8947. };
  8948. comments.push(entry);
  8949. }
  8950. return comments;
  8951. };
  8952. Scanner.prototype.skipMultiLineComment = function () {
  8953. var comments = [];
  8954. var start, loc;
  8955. if (this.trackComment) {
  8956. comments = [];
  8957. start = this.index - 2;
  8958. loc = {
  8959. start: {
  8960. line: this.lineNumber,
  8961. column: this.index - this.lineStart - 2
  8962. },
  8963. end: {}
  8964. };
  8965. }
  8966. while (!this.eof()) {
  8967. var ch = this.source.charCodeAt(this.index);
  8968. if (character_1.Character.isLineTerminator(ch)) {
  8969. if (ch === 0x0D && this.source.charCodeAt(this.index + 1) === 0x0A) {
  8970. ++this.index;
  8971. }
  8972. ++this.lineNumber;
  8973. ++this.index;
  8974. this.lineStart = this.index;
  8975. }
  8976. else if (ch === 0x2A) {
  8977. // Block comment ends with '*/'.
  8978. if (this.source.charCodeAt(this.index + 1) === 0x2F) {
  8979. this.index += 2;
  8980. if (this.trackComment) {
  8981. loc.end = {
  8982. line: this.lineNumber,
  8983. column: this.index - this.lineStart
  8984. };
  8985. var entry = {
  8986. multiLine: true,
  8987. slice: [start + 2, this.index - 2],
  8988. range: [start, this.index],
  8989. loc: loc
  8990. };
  8991. comments.push(entry);
  8992. }
  8993. return comments;
  8994. }
  8995. ++this.index;
  8996. }
  8997. else {
  8998. ++this.index;
  8999. }
  9000. }
  9001. // Ran off the end of the file - the whole thing is a comment
  9002. if (this.trackComment) {
  9003. loc.end = {
  9004. line: this.lineNumber,
  9005. column: this.index - this.lineStart
  9006. };
  9007. var entry = {
  9008. multiLine: true,
  9009. slice: [start + 2, this.index],
  9010. range: [start, this.index],
  9011. loc: loc
  9012. };
  9013. comments.push(entry);
  9014. }
  9015. this.tolerateUnexpectedToken();
  9016. return comments;
  9017. };
  9018. Scanner.prototype.scanComments = function () {
  9019. var comments;
  9020. if (this.trackComment) {
  9021. comments = [];
  9022. }
  9023. var start = (this.index === 0);
  9024. while (!this.eof()) {
  9025. var ch = this.source.charCodeAt(this.index);
  9026. if (character_1.Character.isWhiteSpace(ch)) {
  9027. ++this.index;
  9028. }
  9029. else if (character_1.Character.isLineTerminator(ch)) {
  9030. ++this.index;
  9031. if (ch === 0x0D && this.source.charCodeAt(this.index) === 0x0A) {
  9032. ++this.index;
  9033. }
  9034. ++this.lineNumber;
  9035. this.lineStart = this.index;
  9036. start = true;
  9037. }
  9038. else if (ch === 0x2F) {
  9039. ch = this.source.charCodeAt(this.index + 1);
  9040. if (ch === 0x2F) {
  9041. this.index += 2;
  9042. var comment = this.skipSingleLineComment(2);
  9043. if (this.trackComment) {
  9044. comments = comments.concat(comment);
  9045. }
  9046. start = true;
  9047. }
  9048. else if (ch === 0x2A) {
  9049. this.index += 2;
  9050. var comment = this.skipMultiLineComment();
  9051. if (this.trackComment) {
  9052. comments = comments.concat(comment);
  9053. }
  9054. }
  9055. else {
  9056. break;
  9057. }
  9058. }
  9059. else if (start && ch === 0x2D) {
  9060. // U+003E is '>'
  9061. if ((this.source.charCodeAt(this.index + 1) === 0x2D) && (this.source.charCodeAt(this.index + 2) === 0x3E)) {
  9062. // '-->' is a single-line comment
  9063. this.index += 3;
  9064. var comment = this.skipSingleLineComment(3);
  9065. if (this.trackComment) {
  9066. comments = comments.concat(comment);
  9067. }
  9068. }
  9069. else {
  9070. break;
  9071. }
  9072. }
  9073. else if (ch === 0x3C) {
  9074. if (this.source.slice(this.index + 1, this.index + 4) === '!--') {
  9075. this.index += 4; // `<!--`
  9076. var comment = this.skipSingleLineComment(4);
  9077. if (this.trackComment) {
  9078. comments = comments.concat(comment);
  9079. }
  9080. }
  9081. else {
  9082. break;
  9083. }
  9084. }
  9085. else {
  9086. break;
  9087. }
  9088. }
  9089. return comments;
  9090. };
  9091. // https://tc39.github.io/ecma262/#sec-future-reserved-words
  9092. Scanner.prototype.isFutureReservedWord = function (id) {
  9093. switch (id) {
  9094. case 'enum':
  9095. case 'export':
  9096. case 'import':
  9097. case 'super':
  9098. return true;
  9099. default:
  9100. return false;
  9101. }
  9102. };
  9103. Scanner.prototype.isStrictModeReservedWord = function (id) {
  9104. switch (id) {
  9105. case 'implements':
  9106. case 'interface':
  9107. case 'package':
  9108. case 'private':
  9109. case 'protected':
  9110. case 'public':
  9111. case 'static':
  9112. case 'yield':
  9113. case 'let':
  9114. return true;
  9115. default:
  9116. return false;
  9117. }
  9118. };
  9119. Scanner.prototype.isRestrictedWord = function (id) {
  9120. return id === 'eval' || id === 'arguments';
  9121. };
  9122. // https://tc39.github.io/ecma262/#sec-keywords
  9123. Scanner.prototype.isKeyword = function (id) {
  9124. switch (id.length) {
  9125. case 2:
  9126. return (id === 'if') || (id === 'in') || (id === 'do');
  9127. case 3:
  9128. return (id === 'var') || (id === 'for') || (id === 'new') ||
  9129. (id === 'try') || (id === 'let');
  9130. case 4:
  9131. return (id === 'this') || (id === 'else') || (id === 'case') ||
  9132. (id === 'void') || (id === 'with') || (id === 'enum');
  9133. case 5:
  9134. return (id === 'while') || (id === 'break') || (id === 'catch') ||
  9135. (id === 'throw') || (id === 'const') || (id === 'yield') ||
  9136. (id === 'class') || (id === 'super');
  9137. case 6:
  9138. return (id === 'return') || (id === 'typeof') || (id === 'delete') ||
  9139. (id === 'switch') || (id === 'export') || (id === 'import');
  9140. case 7:
  9141. return (id === 'default') || (id === 'finally') || (id === 'extends');
  9142. case 8:
  9143. return (id === 'function') || (id === 'continue') || (id === 'debugger');
  9144. case 10:
  9145. return (id === 'instanceof');
  9146. default:
  9147. return false;
  9148. }
  9149. };
  9150. Scanner.prototype.codePointAt = function (i) {
  9151. var cp = this.source.charCodeAt(i);
  9152. if (cp >= 0xD800 && cp <= 0xDBFF) {
  9153. var second = this.source.charCodeAt(i + 1);
  9154. if (second >= 0xDC00 && second <= 0xDFFF) {
  9155. var first = cp;
  9156. cp = (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
  9157. }
  9158. }
  9159. return cp;
  9160. };
  9161. Scanner.prototype.scanHexEscape = function (prefix) {
  9162. var len = (prefix === 'u') ? 4 : 2;
  9163. var code = 0;
  9164. for (var i = 0; i < len; ++i) {
  9165. if (!this.eof() && character_1.Character.isHexDigit(this.source.charCodeAt(this.index))) {
  9166. code = code * 16 + hexValue(this.source[this.index++]);
  9167. }
  9168. else {
  9169. return null;
  9170. }
  9171. }
  9172. return String.fromCharCode(code);
  9173. };
  9174. Scanner.prototype.scanUnicodeCodePointEscape = function () {
  9175. var ch = this.source[this.index];
  9176. var code = 0;
  9177. // At least, one hex digit is required.
  9178. if (ch === '}') {
  9179. this.throwUnexpectedToken();
  9180. }
  9181. while (!this.eof()) {
  9182. ch = this.source[this.index++];
  9183. if (!character_1.Character.isHexDigit(ch.charCodeAt(0))) {
  9184. break;
  9185. }
  9186. code = code * 16 + hexValue(ch);
  9187. }
  9188. if (code > 0x10FFFF || ch !== '}') {
  9189. this.throwUnexpectedToken();
  9190. }
  9191. return character_1.Character.fromCodePoint(code);
  9192. };
  9193. Scanner.prototype.getIdentifier = function () {
  9194. var start = this.index++;
  9195. while (!this.eof()) {
  9196. var ch = this.source.charCodeAt(this.index);
  9197. if (ch === 0x5C) {
  9198. // Blackslash (U+005C) marks Unicode escape sequence.
  9199. this.index = start;
  9200. return this.getComplexIdentifier();
  9201. }
  9202. else if (ch >= 0xD800 && ch < 0xDFFF) {
  9203. // Need to handle surrogate pairs.
  9204. this.index = start;
  9205. return this.getComplexIdentifier();
  9206. }
  9207. if (character_1.Character.isIdentifierPart(ch)) {
  9208. ++this.index;
  9209. }
  9210. else {
  9211. break;
  9212. }
  9213. }
  9214. return this.source.slice(start, this.index);
  9215. };
  9216. Scanner.prototype.getComplexIdentifier = function () {
  9217. var cp = this.codePointAt(this.index);
  9218. var id = character_1.Character.fromCodePoint(cp);
  9219. this.index += id.length;
  9220. // '\u' (U+005C, U+0075) denotes an escaped character.
  9221. var ch;
  9222. if (cp === 0x5C) {
  9223. if (this.source.charCodeAt(this.index) !== 0x75) {
  9224. this.throwUnexpectedToken();
  9225. }
  9226. ++this.index;
  9227. if (this.source[this.index] === '{') {
  9228. ++this.index;
  9229. ch = this.scanUnicodeCodePointEscape();
  9230. }
  9231. else {
  9232. ch = this.scanHexEscape('u');
  9233. if (ch === null || ch === '\\' || !character_1.Character.isIdentifierStart(ch.charCodeAt(0))) {
  9234. this.throwUnexpectedToken();
  9235. }
  9236. }
  9237. id = ch;
  9238. }
  9239. while (!this.eof()) {
  9240. cp = this.codePointAt(this.index);
  9241. if (!character_1.Character.isIdentifierPart(cp)) {
  9242. break;
  9243. }
  9244. ch = character_1.Character.fromCodePoint(cp);
  9245. id += ch;
  9246. this.index += ch.length;
  9247. // '\u' (U+005C, U+0075) denotes an escaped character.
  9248. if (cp === 0x5C) {
  9249. id = id.substr(0, id.length - 1);
  9250. if (this.source.charCodeAt(this.index) !== 0x75) {
  9251. this.throwUnexpectedToken();
  9252. }
  9253. ++this.index;
  9254. if (this.source[this.index] === '{') {
  9255. ++this.index;
  9256. ch = this.scanUnicodeCodePointEscape();
  9257. }
  9258. else {
  9259. ch = this.scanHexEscape('u');
  9260. if (ch === null || ch === '\\' || !character_1.Character.isIdentifierPart(ch.charCodeAt(0))) {
  9261. this.throwUnexpectedToken();
  9262. }
  9263. }
  9264. id += ch;
  9265. }
  9266. }
  9267. return id;
  9268. };
  9269. Scanner.prototype.octalToDecimal = function (ch) {
  9270. // \0 is not octal escape sequence
  9271. var octal = (ch !== '0');
  9272. var code = octalValue(ch);
  9273. if (!this.eof() && character_1.Character.isOctalDigit(this.source.charCodeAt(this.index))) {
  9274. octal = true;
  9275. code = code * 8 + octalValue(this.source[this.index++]);
  9276. // 3 digits are only allowed when string starts
  9277. // with 0, 1, 2, 3
  9278. if ('0123'.indexOf(ch) >= 0 && !this.eof() && character_1.Character.isOctalDigit(this.source.charCodeAt(this.index))) {
  9279. code = code * 8 + octalValue(this.source[this.index++]);
  9280. }
  9281. }
  9282. return {
  9283. code: code,
  9284. octal: octal
  9285. };
  9286. };
  9287. // https://tc39.github.io/ecma262/#sec-names-and-keywords
  9288. Scanner.prototype.scanIdentifier = function () {
  9289. var type;
  9290. var start = this.index;
  9291. // Backslash (U+005C) starts an escaped character.
  9292. var id = (this.source.charCodeAt(start) === 0x5C) ? this.getComplexIdentifier() : this.getIdentifier();
  9293. // There is no keyword or literal with only one character.
  9294. // Thus, it must be an identifier.
  9295. if (id.length === 1) {
  9296. type = 3 /* Identifier */;
  9297. }
  9298. else if (this.isKeyword(id)) {
  9299. type = 4 /* Keyword */;
  9300. }
  9301. else if (id === 'null') {
  9302. type = 5 /* NullLiteral */;
  9303. }
  9304. else if (id === 'true' || id === 'false') {
  9305. type = 1 /* BooleanLiteral */;
  9306. }
  9307. else {
  9308. type = 3 /* Identifier */;
  9309. }
  9310. if (type !== 3 /* Identifier */ && (start + id.length !== this.index)) {
  9311. var restore = this.index;
  9312. this.index = start;
  9313. this.tolerateUnexpectedToken(messages_1.Messages.InvalidEscapedReservedWord);
  9314. this.index = restore;
  9315. }
  9316. return {
  9317. type: type,
  9318. value: id,
  9319. lineNumber: this.lineNumber,
  9320. lineStart: this.lineStart,
  9321. start: start,
  9322. end: this.index
  9323. };
  9324. };
  9325. // https://tc39.github.io/ecma262/#sec-punctuators
  9326. Scanner.prototype.scanPunctuator = function () {
  9327. var start = this.index;
  9328. // Check for most common single-character punctuators.
  9329. var str = this.source[this.index];
  9330. switch (str) {
  9331. case '(':
  9332. case '{':
  9333. if (str === '{') {
  9334. this.curlyStack.push('{');
  9335. }
  9336. ++this.index;
  9337. break;
  9338. case '.':
  9339. ++this.index;
  9340. if (this.source[this.index] === '.' && this.source[this.index + 1] === '.') {
  9341. // Spread operator: ...
  9342. this.index += 2;
  9343. str = '...';
  9344. }
  9345. break;
  9346. case '}':
  9347. ++this.index;
  9348. this.curlyStack.pop();
  9349. break;
  9350. case ')':
  9351. case ';':
  9352. case ',':
  9353. case '[':
  9354. case ']':
  9355. case ':':
  9356. case '?':
  9357. case '~':
  9358. ++this.index;
  9359. break;
  9360. default:
  9361. // 4-character punctuator.
  9362. str = this.source.substr(this.index, 4);
  9363. if (str === '>>>=') {
  9364. this.index += 4;
  9365. }
  9366. else {
  9367. // 3-character punctuators.
  9368. str = str.substr(0, 3);
  9369. if (str === '===' || str === '!==' || str === '>>>' ||
  9370. str === '<<=' || str === '>>=' || str === '**=') {
  9371. this.index += 3;
  9372. }
  9373. else {
  9374. // 2-character punctuators.
  9375. str = str.substr(0, 2);
  9376. if (str === '&&' || str === '||' || str === '==' || str === '!=' ||
  9377. str === '+=' || str === '-=' || str === '*=' || str === '/=' ||
  9378. str === '++' || str === '--' || str === '<<' || str === '>>' ||
  9379. str === '&=' || str === '|=' || str === '^=' || str === '%=' ||
  9380. str === '<=' || str === '>=' || str === '=>' || str === '**') {
  9381. this.index += 2;
  9382. }
  9383. else {
  9384. // 1-character punctuators.
  9385. str = this.source[this.index];
  9386. if ('<>=!+-*%&|^/'.indexOf(str) >= 0) {
  9387. ++this.index;
  9388. }
  9389. }
  9390. }
  9391. }
  9392. }
  9393. if (this.index === start) {
  9394. this.throwUnexpectedToken();
  9395. }
  9396. return {
  9397. type: 7 /* Punctuator */,
  9398. value: str,
  9399. lineNumber: this.lineNumber,
  9400. lineStart: this.lineStart,
  9401. start: start,
  9402. end: this.index
  9403. };
  9404. };
  9405. // https://tc39.github.io/ecma262/#sec-literals-numeric-literals
  9406. Scanner.prototype.scanHexLiteral = function (start) {
  9407. var num = '';
  9408. while (!this.eof()) {
  9409. if (!character_1.Character.isHexDigit(this.source.charCodeAt(this.index))) {
  9410. break;
  9411. }
  9412. num += this.source[this.index++];
  9413. }
  9414. if (num.length === 0) {
  9415. this.throwUnexpectedToken();
  9416. }
  9417. if (character_1.Character.isIdentifierStart(this.source.charCodeAt(this.index))) {
  9418. this.throwUnexpectedToken();
  9419. }
  9420. return {
  9421. type: 6 /* NumericLiteral */,
  9422. value: parseInt('0x' + num, 16),
  9423. lineNumber: this.lineNumber,
  9424. lineStart: this.lineStart,
  9425. start: start,
  9426. end: this.index
  9427. };
  9428. };
  9429. Scanner.prototype.scanBinaryLiteral = function (start) {
  9430. var num = '';
  9431. var ch;
  9432. while (!this.eof()) {
  9433. ch = this.source[this.index];
  9434. if (ch !== '0' && ch !== '1') {
  9435. break;
  9436. }
  9437. num += this.source[this.index++];
  9438. }
  9439. if (num.length === 0) {
  9440. // only 0b or 0B
  9441. this.throwUnexpectedToken();
  9442. }
  9443. if (!this.eof()) {
  9444. ch = this.source.charCodeAt(this.index);
  9445. /* istanbul ignore else */
  9446. if (character_1.Character.isIdentifierStart(ch) || character_1.Character.isDecimalDigit(ch)) {
  9447. this.throwUnexpectedToken();
  9448. }
  9449. }
  9450. return {
  9451. type: 6 /* NumericLiteral */,
  9452. value: parseInt(num, 2),
  9453. lineNumber: this.lineNumber,
  9454. lineStart: this.lineStart,
  9455. start: start,
  9456. end: this.index
  9457. };
  9458. };
  9459. Scanner.prototype.scanOctalLiteral = function (prefix, start) {
  9460. var num = '';
  9461. var octal = false;
  9462. if (character_1.Character.isOctalDigit(prefix.charCodeAt(0))) {
  9463. octal = true;
  9464. num = '0' + this.source[this.index++];
  9465. }
  9466. else {
  9467. ++this.index;
  9468. }
  9469. while (!this.eof()) {
  9470. if (!character_1.Character.isOctalDigit(this.source.charCodeAt(this.index))) {
  9471. break;
  9472. }
  9473. num += this.source[this.index++];
  9474. }
  9475. if (!octal && num.length === 0) {
  9476. // only 0o or 0O
  9477. this.throwUnexpectedToken();
  9478. }
  9479. if (character_1.Character.isIdentifierStart(this.source.charCodeAt(this.index)) || character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
  9480. this.throwUnexpectedToken();
  9481. }
  9482. return {
  9483. type: 6 /* NumericLiteral */,
  9484. value: parseInt(num, 8),
  9485. octal: octal,
  9486. lineNumber: this.lineNumber,
  9487. lineStart: this.lineStart,
  9488. start: start,
  9489. end: this.index
  9490. };
  9491. };
  9492. Scanner.prototype.isImplicitOctalLiteral = function () {
  9493. // Implicit octal, unless there is a non-octal digit.
  9494. // (Annex B.1.1 on Numeric Literals)
  9495. for (var i = this.index + 1; i < this.length; ++i) {
  9496. var ch = this.source[i];
  9497. if (ch === '8' || ch === '9') {
  9498. return false;
  9499. }
  9500. if (!character_1.Character.isOctalDigit(ch.charCodeAt(0))) {
  9501. return true;
  9502. }
  9503. }
  9504. return true;
  9505. };
  9506. Scanner.prototype.scanNumericLiteral = function () {
  9507. var start = this.index;
  9508. var ch = this.source[start];
  9509. assert_1.assert(character_1.Character.isDecimalDigit(ch.charCodeAt(0)) || (ch === '.'), 'Numeric literal must start with a decimal digit or a decimal point');
  9510. var num = '';
  9511. if (ch !== '.') {
  9512. num = this.source[this.index++];
  9513. ch = this.source[this.index];
  9514. // Hex number starts with '0x'.
  9515. // Octal number starts with '0'.
  9516. // Octal number in ES6 starts with '0o'.
  9517. // Binary number in ES6 starts with '0b'.
  9518. if (num === '0') {
  9519. if (ch === 'x' || ch === 'X') {
  9520. ++this.index;
  9521. return this.scanHexLiteral(start);
  9522. }
  9523. if (ch === 'b' || ch === 'B') {
  9524. ++this.index;
  9525. return this.scanBinaryLiteral(start);
  9526. }
  9527. if (ch === 'o' || ch === 'O') {
  9528. return this.scanOctalLiteral(ch, start);
  9529. }
  9530. if (ch && character_1.Character.isOctalDigit(ch.charCodeAt(0))) {
  9531. if (this.isImplicitOctalLiteral()) {
  9532. return this.scanOctalLiteral(ch, start);
  9533. }
  9534. }
  9535. }
  9536. while (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
  9537. num += this.source[this.index++];
  9538. }
  9539. ch = this.source[this.index];
  9540. }
  9541. if (ch === '.') {
  9542. num += this.source[this.index++];
  9543. while (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
  9544. num += this.source[this.index++];
  9545. }
  9546. ch = this.source[this.index];
  9547. }
  9548. if (ch === 'e' || ch === 'E') {
  9549. num += this.source[this.index++];
  9550. ch = this.source[this.index];
  9551. if (ch === '+' || ch === '-') {
  9552. num += this.source[this.index++];
  9553. }
  9554. if (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
  9555. while (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
  9556. num += this.source[this.index++];
  9557. }
  9558. }
  9559. else {
  9560. this.throwUnexpectedToken();
  9561. }
  9562. }
  9563. if (character_1.Character.isIdentifierStart(this.source.charCodeAt(this.index))) {
  9564. this.throwUnexpectedToken();
  9565. }
  9566. return {
  9567. type: 6 /* NumericLiteral */,
  9568. value: parseFloat(num),
  9569. lineNumber: this.lineNumber,
  9570. lineStart: this.lineStart,
  9571. start: start,
  9572. end: this.index
  9573. };
  9574. };
  9575. // https://tc39.github.io/ecma262/#sec-literals-string-literals
  9576. Scanner.prototype.scanStringLiteral = function () {
  9577. var start = this.index;
  9578. var quote = this.source[start];
  9579. assert_1.assert((quote === '\'' || quote === '"'), 'String literal must starts with a quote');
  9580. ++this.index;
  9581. var octal = false;
  9582. var str = '';
  9583. while (!this.eof()) {
  9584. var ch = this.source[this.index++];
  9585. if (ch === quote) {
  9586. quote = '';
  9587. break;
  9588. }
  9589. else if (ch === '\\') {
  9590. ch = this.source[this.index++];
  9591. if (!ch || !character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
  9592. switch (ch) {
  9593. case 'u':
  9594. if (this.source[this.index] === '{') {
  9595. ++this.index;
  9596. str += this.scanUnicodeCodePointEscape();
  9597. }
  9598. else {
  9599. var unescaped_1 = this.scanHexEscape(ch);
  9600. if (unescaped_1 === null) {
  9601. this.throwUnexpectedToken();
  9602. }
  9603. str += unescaped_1;
  9604. }
  9605. break;
  9606. case 'x':
  9607. var unescaped = this.scanHexEscape(ch);
  9608. if (unescaped === null) {
  9609. this.throwUnexpectedToken(messages_1.Messages.InvalidHexEscapeSequence);
  9610. }
  9611. str += unescaped;
  9612. break;
  9613. case 'n':
  9614. str += '\n';
  9615. break;
  9616. case 'r':
  9617. str += '\r';
  9618. break;
  9619. case 't':
  9620. str += '\t';
  9621. break;
  9622. case 'b':
  9623. str += '\b';
  9624. break;
  9625. case 'f':
  9626. str += '\f';
  9627. break;
  9628. case 'v':
  9629. str += '\x0B';
  9630. break;
  9631. case '8':
  9632. case '9':
  9633. str += ch;
  9634. this.tolerateUnexpectedToken();
  9635. break;
  9636. default:
  9637. if (ch && character_1.Character.isOctalDigit(ch.charCodeAt(0))) {
  9638. var octToDec = this.octalToDecimal(ch);
  9639. octal = octToDec.octal || octal;
  9640. str += String.fromCharCode(octToDec.code);
  9641. }
  9642. else {
  9643. str += ch;
  9644. }
  9645. break;
  9646. }
  9647. }
  9648. else {
  9649. ++this.lineNumber;
  9650. if (ch === '\r' && this.source[this.index] === '\n') {
  9651. ++this.index;
  9652. }
  9653. this.lineStart = this.index;
  9654. }
  9655. }
  9656. else if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
  9657. break;
  9658. }
  9659. else {
  9660. str += ch;
  9661. }
  9662. }
  9663. if (quote !== '') {
  9664. this.index = start;
  9665. this.throwUnexpectedToken();
  9666. }
  9667. return {
  9668. type: 8 /* StringLiteral */,
  9669. value: str,
  9670. octal: octal,
  9671. lineNumber: this.lineNumber,
  9672. lineStart: this.lineStart,
  9673. start: start,
  9674. end: this.index
  9675. };
  9676. };
  9677. // https://tc39.github.io/ecma262/#sec-template-literal-lexical-components
  9678. Scanner.prototype.scanTemplate = function () {
  9679. var cooked = '';
  9680. var terminated = false;
  9681. var start = this.index;
  9682. var head = (this.source[start] === '`');
  9683. var tail = false;
  9684. var rawOffset = 2;
  9685. ++this.index;
  9686. while (!this.eof()) {
  9687. var ch = this.source[this.index++];
  9688. if (ch === '`') {
  9689. rawOffset = 1;
  9690. tail = true;
  9691. terminated = true;
  9692. break;
  9693. }
  9694. else if (ch === '$') {
  9695. if (this.source[this.index] === '{') {
  9696. this.curlyStack.push('${');
  9697. ++this.index;
  9698. terminated = true;
  9699. break;
  9700. }
  9701. cooked += ch;
  9702. }
  9703. else if (ch === '\\') {
  9704. ch = this.source[this.index++];
  9705. if (!character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
  9706. switch (ch) {
  9707. case 'n':
  9708. cooked += '\n';
  9709. break;
  9710. case 'r':
  9711. cooked += '\r';
  9712. break;
  9713. case 't':
  9714. cooked += '\t';
  9715. break;
  9716. case 'u':
  9717. if (this.source[this.index] === '{') {
  9718. ++this.index;
  9719. cooked += this.scanUnicodeCodePointEscape();
  9720. }
  9721. else {
  9722. var restore = this.index;
  9723. var unescaped_2 = this.scanHexEscape(ch);
  9724. if (unescaped_2 !== null) {
  9725. cooked += unescaped_2;
  9726. }
  9727. else {
  9728. this.index = restore;
  9729. cooked += ch;
  9730. }
  9731. }
  9732. break;
  9733. case 'x':
  9734. var unescaped = this.scanHexEscape(ch);
  9735. if (unescaped === null) {
  9736. this.throwUnexpectedToken(messages_1.Messages.InvalidHexEscapeSequence);
  9737. }
  9738. cooked += unescaped;
  9739. break;
  9740. case 'b':
  9741. cooked += '\b';
  9742. break;
  9743. case 'f':
  9744. cooked += '\f';
  9745. break;
  9746. case 'v':
  9747. cooked += '\v';
  9748. break;
  9749. default:
  9750. if (ch === '0') {
  9751. if (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
  9752. // Illegal: \01 \02 and so on
  9753. this.throwUnexpectedToken(messages_1.Messages.TemplateOctalLiteral);
  9754. }
  9755. cooked += '\0';
  9756. }
  9757. else if (character_1.Character.isOctalDigit(ch.charCodeAt(0))) {
  9758. // Illegal: \1 \2
  9759. this.throwUnexpectedToken(messages_1.Messages.TemplateOctalLiteral);
  9760. }
  9761. else {
  9762. cooked += ch;
  9763. }
  9764. break;
  9765. }
  9766. }
  9767. else {
  9768. ++this.lineNumber;
  9769. if (ch === '\r' && this.source[this.index] === '\n') {
  9770. ++this.index;
  9771. }
  9772. this.lineStart = this.index;
  9773. }
  9774. }
  9775. else if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
  9776. ++this.lineNumber;
  9777. if (ch === '\r' && this.source[this.index] === '\n') {
  9778. ++this.index;
  9779. }
  9780. this.lineStart = this.index;
  9781. cooked += '\n';
  9782. }
  9783. else {
  9784. cooked += ch;
  9785. }
  9786. }
  9787. if (!terminated) {
  9788. this.throwUnexpectedToken();
  9789. }
  9790. if (!head) {
  9791. this.curlyStack.pop();
  9792. }
  9793. return {
  9794. type: 10 /* Template */,
  9795. value: this.source.slice(start + 1, this.index - rawOffset),
  9796. cooked: cooked,
  9797. head: head,
  9798. tail: tail,
  9799. lineNumber: this.lineNumber,
  9800. lineStart: this.lineStart,
  9801. start: start,
  9802. end: this.index
  9803. };
  9804. };
  9805. // https://tc39.github.io/ecma262/#sec-literals-regular-expression-literals
  9806. Scanner.prototype.testRegExp = function (pattern, flags) {
  9807. // The BMP character to use as a replacement for astral symbols when
  9808. // translating an ES6 "u"-flagged pattern to an ES5-compatible
  9809. // approximation.
  9810. // Note: replacing with '\uFFFF' enables false positives in unlikely
  9811. // scenarios. For example, `[\u{1044f}-\u{10440}]` is an invalid
  9812. // pattern that would not be detected by this substitution.
  9813. var astralSubstitute = '\uFFFF';
  9814. var tmp = pattern;
  9815. var self = this;
  9816. if (flags.indexOf('u') >= 0) {
  9817. tmp = tmp
  9818. .replace(/\\u\{([0-9a-fA-F]+)\}|\\u([a-fA-F0-9]{4})/g, function ($0, $1, $2) {
  9819. var codePoint = parseInt($1 || $2, 16);
  9820. if (codePoint > 0x10FFFF) {
  9821. self.throwUnexpectedToken(messages_1.Messages.InvalidRegExp);
  9822. }
  9823. if (codePoint <= 0xFFFF) {
  9824. return String.fromCharCode(codePoint);
  9825. }
  9826. return astralSubstitute;
  9827. })
  9828. .replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, astralSubstitute);
  9829. }
  9830. // First, detect invalid regular expressions.
  9831. try {
  9832. RegExp(tmp);
  9833. }
  9834. catch (e) {
  9835. this.throwUnexpectedToken(messages_1.Messages.InvalidRegExp);
  9836. }
  9837. // Return a regular expression object for this pattern-flag pair, or
  9838. // `null` in case the current environment doesn't support the flags it
  9839. // uses.
  9840. try {
  9841. return new RegExp(pattern, flags);
  9842. }
  9843. catch (exception) {
  9844. /* istanbul ignore next */
  9845. return null;
  9846. }
  9847. };
  9848. Scanner.prototype.scanRegExpBody = function () {
  9849. var ch = this.source[this.index];
  9850. assert_1.assert(ch === '/', 'Regular expression literal must start with a slash');
  9851. var str = this.source[this.index++];
  9852. var classMarker = false;
  9853. var terminated = false;
  9854. while (!this.eof()) {
  9855. ch = this.source[this.index++];
  9856. str += ch;
  9857. if (ch === '\\') {
  9858. ch = this.source[this.index++];
  9859. // https://tc39.github.io/ecma262/#sec-literals-regular-expression-literals
  9860. if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
  9861. this.throwUnexpectedToken(messages_1.Messages.UnterminatedRegExp);
  9862. }
  9863. str += ch;
  9864. }
  9865. else if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
  9866. this.throwUnexpectedToken(messages_1.Messages.UnterminatedRegExp);
  9867. }
  9868. else if (classMarker) {
  9869. if (ch === ']') {
  9870. classMarker = false;
  9871. }
  9872. }
  9873. else {
  9874. if (ch === '/') {
  9875. terminated = true;
  9876. break;
  9877. }
  9878. else if (ch === '[') {
  9879. classMarker = true;
  9880. }
  9881. }
  9882. }
  9883. if (!terminated) {
  9884. this.throwUnexpectedToken(messages_1.Messages.UnterminatedRegExp);
  9885. }
  9886. // Exclude leading and trailing slash.
  9887. return str.substr(1, str.length - 2);
  9888. };
  9889. Scanner.prototype.scanRegExpFlags = function () {
  9890. var str = '';
  9891. var flags = '';
  9892. while (!this.eof()) {
  9893. var ch = this.source[this.index];
  9894. if (!character_1.Character.isIdentifierPart(ch.charCodeAt(0))) {
  9895. break;
  9896. }
  9897. ++this.index;
  9898. if (ch === '\\' && !this.eof()) {
  9899. ch = this.source[this.index];
  9900. if (ch === 'u') {
  9901. ++this.index;
  9902. var restore = this.index;
  9903. var char = this.scanHexEscape('u');
  9904. if (char !== null) {
  9905. flags += char;
  9906. for (str += '\\u'; restore < this.index; ++restore) {
  9907. str += this.source[restore];
  9908. }
  9909. }
  9910. else {
  9911. this.index = restore;
  9912. flags += 'u';
  9913. str += '\\u';
  9914. }
  9915. this.tolerateUnexpectedToken();
  9916. }
  9917. else {
  9918. str += '\\';
  9919. this.tolerateUnexpectedToken();
  9920. }
  9921. }
  9922. else {
  9923. flags += ch;
  9924. str += ch;
  9925. }
  9926. }
  9927. return flags;
  9928. };
  9929. Scanner.prototype.scanRegExp = function () {
  9930. var start = this.index;
  9931. var pattern = this.scanRegExpBody();
  9932. var flags = this.scanRegExpFlags();
  9933. var value = this.testRegExp(pattern, flags);
  9934. return {
  9935. type: 9 /* RegularExpression */,
  9936. value: '',
  9937. pattern: pattern,
  9938. flags: flags,
  9939. regex: value,
  9940. lineNumber: this.lineNumber,
  9941. lineStart: this.lineStart,
  9942. start: start,
  9943. end: this.index
  9944. };
  9945. };
  9946. Scanner.prototype.lex = function () {
  9947. if (this.eof()) {
  9948. return {
  9949. type: 2 /* EOF */,
  9950. value: '',
  9951. lineNumber: this.lineNumber,
  9952. lineStart: this.lineStart,
  9953. start: this.index,
  9954. end: this.index
  9955. };
  9956. }
  9957. var cp = this.source.charCodeAt(this.index);
  9958. if (character_1.Character.isIdentifierStart(cp)) {
  9959. return this.scanIdentifier();
  9960. }
  9961. // Very common: ( and ) and ;
  9962. if (cp === 0x28 || cp === 0x29 || cp === 0x3B) {
  9963. return this.scanPunctuator();
  9964. }
  9965. // String literal starts with single quote (U+0027) or double quote (U+0022).
  9966. if (cp === 0x27 || cp === 0x22) {
  9967. return this.scanStringLiteral();
  9968. }
  9969. // Dot (.) U+002E can also start a floating-point number, hence the need
  9970. // to check the next character.
  9971. if (cp === 0x2E) {
  9972. if (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index + 1))) {
  9973. return this.scanNumericLiteral();
  9974. }
  9975. return this.scanPunctuator();
  9976. }
  9977. if (character_1.Character.isDecimalDigit(cp)) {
  9978. return this.scanNumericLiteral();
  9979. }
  9980. // Template literals start with ` (U+0060) for template head
  9981. // or } (U+007D) for template middle or template tail.
  9982. if (cp === 0x60 || (cp === 0x7D && this.curlyStack[this.curlyStack.length - 1] === '${')) {
  9983. return this.scanTemplate();
  9984. }
  9985. // Possible identifier start in a surrogate pair.
  9986. if (cp >= 0xD800 && cp < 0xDFFF) {
  9987. if (character_1.Character.isIdentifierStart(this.codePointAt(this.index))) {
  9988. return this.scanIdentifier();
  9989. }
  9990. }
  9991. return this.scanPunctuator();
  9992. };
  9993. return Scanner;
  9994. }());
  9995. exports.Scanner = Scanner;
  9996. /***/ },
  9997. /* 13 */
  9998. /***/ function(module, exports) {
  9999. "use strict";
  10000. Object.defineProperty(exports, "__esModule", { value: true });
  10001. exports.TokenName = {};
  10002. exports.TokenName[1 /* BooleanLiteral */] = 'Boolean';
  10003. exports.TokenName[2 /* EOF */] = '<end>';
  10004. exports.TokenName[3 /* Identifier */] = 'Identifier';
  10005. exports.TokenName[4 /* Keyword */] = 'Keyword';
  10006. exports.TokenName[5 /* NullLiteral */] = 'Null';
  10007. exports.TokenName[6 /* NumericLiteral */] = 'Numeric';
  10008. exports.TokenName[7 /* Punctuator */] = 'Punctuator';
  10009. exports.TokenName[8 /* StringLiteral */] = 'String';
  10010. exports.TokenName[9 /* RegularExpression */] = 'RegularExpression';
  10011. exports.TokenName[10 /* Template */] = 'Template';
  10012. /***/ },
  10013. /* 14 */
  10014. /***/ function(module, exports) {
  10015. "use strict";
  10016. // Generated by generate-xhtml-entities.js. DO NOT MODIFY!
  10017. Object.defineProperty(exports, "__esModule", { value: true });
  10018. exports.XHTMLEntities = {
  10019. quot: '\u0022',
  10020. amp: '\u0026',
  10021. apos: '\u0027',
  10022. gt: '\u003E',
  10023. nbsp: '\u00A0',
  10024. iexcl: '\u00A1',
  10025. cent: '\u00A2',
  10026. pound: '\u00A3',
  10027. curren: '\u00A4',
  10028. yen: '\u00A5',
  10029. brvbar: '\u00A6',
  10030. sect: '\u00A7',
  10031. uml: '\u00A8',
  10032. copy: '\u00A9',
  10033. ordf: '\u00AA',
  10034. laquo: '\u00AB',
  10035. not: '\u00AC',
  10036. shy: '\u00AD',
  10037. reg: '\u00AE',
  10038. macr: '\u00AF',
  10039. deg: '\u00B0',
  10040. plusmn: '\u00B1',
  10041. sup2: '\u00B2',
  10042. sup3: '\u00B3',
  10043. acute: '\u00B4',
  10044. micro: '\u00B5',
  10045. para: '\u00B6',
  10046. middot: '\u00B7',
  10047. cedil: '\u00B8',
  10048. sup1: '\u00B9',
  10049. ordm: '\u00BA',
  10050. raquo: '\u00BB',
  10051. frac14: '\u00BC',
  10052. frac12: '\u00BD',
  10053. frac34: '\u00BE',
  10054. iquest: '\u00BF',
  10055. Agrave: '\u00C0',
  10056. Aacute: '\u00C1',
  10057. Acirc: '\u00C2',
  10058. Atilde: '\u00C3',
  10059. Auml: '\u00C4',
  10060. Aring: '\u00C5',
  10061. AElig: '\u00C6',
  10062. Ccedil: '\u00C7',
  10063. Egrave: '\u00C8',
  10064. Eacute: '\u00C9',
  10065. Ecirc: '\u00CA',
  10066. Euml: '\u00CB',
  10067. Igrave: '\u00CC',
  10068. Iacute: '\u00CD',
  10069. Icirc: '\u00CE',
  10070. Iuml: '\u00CF',
  10071. ETH: '\u00D0',
  10072. Ntilde: '\u00D1',
  10073. Ograve: '\u00D2',
  10074. Oacute: '\u00D3',
  10075. Ocirc: '\u00D4',
  10076. Otilde: '\u00D5',
  10077. Ouml: '\u00D6',
  10078. times: '\u00D7',
  10079. Oslash: '\u00D8',
  10080. Ugrave: '\u00D9',
  10081. Uacute: '\u00DA',
  10082. Ucirc: '\u00DB',
  10083. Uuml: '\u00DC',
  10084. Yacute: '\u00DD',
  10085. THORN: '\u00DE',
  10086. szlig: '\u00DF',
  10087. agrave: '\u00E0',
  10088. aacute: '\u00E1',
  10089. acirc: '\u00E2',
  10090. atilde: '\u00E3',
  10091. auml: '\u00E4',
  10092. aring: '\u00E5',
  10093. aelig: '\u00E6',
  10094. ccedil: '\u00E7',
  10095. egrave: '\u00E8',
  10096. eacute: '\u00E9',
  10097. ecirc: '\u00EA',
  10098. euml: '\u00EB',
  10099. igrave: '\u00EC',
  10100. iacute: '\u00ED',
  10101. icirc: '\u00EE',
  10102. iuml: '\u00EF',
  10103. eth: '\u00F0',
  10104. ntilde: '\u00F1',
  10105. ograve: '\u00F2',
  10106. oacute: '\u00F3',
  10107. ocirc: '\u00F4',
  10108. otilde: '\u00F5',
  10109. ouml: '\u00F6',
  10110. divide: '\u00F7',
  10111. oslash: '\u00F8',
  10112. ugrave: '\u00F9',
  10113. uacute: '\u00FA',
  10114. ucirc: '\u00FB',
  10115. uuml: '\u00FC',
  10116. yacute: '\u00FD',
  10117. thorn: '\u00FE',
  10118. yuml: '\u00FF',
  10119. OElig: '\u0152',
  10120. oelig: '\u0153',
  10121. Scaron: '\u0160',
  10122. scaron: '\u0161',
  10123. Yuml: '\u0178',
  10124. fnof: '\u0192',
  10125. circ: '\u02C6',
  10126. tilde: '\u02DC',
  10127. Alpha: '\u0391',
  10128. Beta: '\u0392',
  10129. Gamma: '\u0393',
  10130. Delta: '\u0394',
  10131. Epsilon: '\u0395',
  10132. Zeta: '\u0396',
  10133. Eta: '\u0397',
  10134. Theta: '\u0398',
  10135. Iota: '\u0399',
  10136. Kappa: '\u039A',
  10137. Lambda: '\u039B',
  10138. Mu: '\u039C',
  10139. Nu: '\u039D',
  10140. Xi: '\u039E',
  10141. Omicron: '\u039F',
  10142. Pi: '\u03A0',
  10143. Rho: '\u03A1',
  10144. Sigma: '\u03A3',
  10145. Tau: '\u03A4',
  10146. Upsilon: '\u03A5',
  10147. Phi: '\u03A6',
  10148. Chi: '\u03A7',
  10149. Psi: '\u03A8',
  10150. Omega: '\u03A9',
  10151. alpha: '\u03B1',
  10152. beta: '\u03B2',
  10153. gamma: '\u03B3',
  10154. delta: '\u03B4',
  10155. epsilon: '\u03B5',
  10156. zeta: '\u03B6',
  10157. eta: '\u03B7',
  10158. theta: '\u03B8',
  10159. iota: '\u03B9',
  10160. kappa: '\u03BA',
  10161. lambda: '\u03BB',
  10162. mu: '\u03BC',
  10163. nu: '\u03BD',
  10164. xi: '\u03BE',
  10165. omicron: '\u03BF',
  10166. pi: '\u03C0',
  10167. rho: '\u03C1',
  10168. sigmaf: '\u03C2',
  10169. sigma: '\u03C3',
  10170. tau: '\u03C4',
  10171. upsilon: '\u03C5',
  10172. phi: '\u03C6',
  10173. chi: '\u03C7',
  10174. psi: '\u03C8',
  10175. omega: '\u03C9',
  10176. thetasym: '\u03D1',
  10177. upsih: '\u03D2',
  10178. piv: '\u03D6',
  10179. ensp: '\u2002',
  10180. emsp: '\u2003',
  10181. thinsp: '\u2009',
  10182. zwnj: '\u200C',
  10183. zwj: '\u200D',
  10184. lrm: '\u200E',
  10185. rlm: '\u200F',
  10186. ndash: '\u2013',
  10187. mdash: '\u2014',
  10188. lsquo: '\u2018',
  10189. rsquo: '\u2019',
  10190. sbquo: '\u201A',
  10191. ldquo: '\u201C',
  10192. rdquo: '\u201D',
  10193. bdquo: '\u201E',
  10194. dagger: '\u2020',
  10195. Dagger: '\u2021',
  10196. bull: '\u2022',
  10197. hellip: '\u2026',
  10198. permil: '\u2030',
  10199. prime: '\u2032',
  10200. Prime: '\u2033',
  10201. lsaquo: '\u2039',
  10202. rsaquo: '\u203A',
  10203. oline: '\u203E',
  10204. frasl: '\u2044',
  10205. euro: '\u20AC',
  10206. image: '\u2111',
  10207. weierp: '\u2118',
  10208. real: '\u211C',
  10209. trade: '\u2122',
  10210. alefsym: '\u2135',
  10211. larr: '\u2190',
  10212. uarr: '\u2191',
  10213. rarr: '\u2192',
  10214. darr: '\u2193',
  10215. harr: '\u2194',
  10216. crarr: '\u21B5',
  10217. lArr: '\u21D0',
  10218. uArr: '\u21D1',
  10219. rArr: '\u21D2',
  10220. dArr: '\u21D3',
  10221. hArr: '\u21D4',
  10222. forall: '\u2200',
  10223. part: '\u2202',
  10224. exist: '\u2203',
  10225. empty: '\u2205',
  10226. nabla: '\u2207',
  10227. isin: '\u2208',
  10228. notin: '\u2209',
  10229. ni: '\u220B',
  10230. prod: '\u220F',
  10231. sum: '\u2211',
  10232. minus: '\u2212',
  10233. lowast: '\u2217',
  10234. radic: '\u221A',
  10235. prop: '\u221D',
  10236. infin: '\u221E',
  10237. ang: '\u2220',
  10238. and: '\u2227',
  10239. or: '\u2228',
  10240. cap: '\u2229',
  10241. cup: '\u222A',
  10242. int: '\u222B',
  10243. there4: '\u2234',
  10244. sim: '\u223C',
  10245. cong: '\u2245',
  10246. asymp: '\u2248',
  10247. ne: '\u2260',
  10248. equiv: '\u2261',
  10249. le: '\u2264',
  10250. ge: '\u2265',
  10251. sub: '\u2282',
  10252. sup: '\u2283',
  10253. nsub: '\u2284',
  10254. sube: '\u2286',
  10255. supe: '\u2287',
  10256. oplus: '\u2295',
  10257. otimes: '\u2297',
  10258. perp: '\u22A5',
  10259. sdot: '\u22C5',
  10260. lceil: '\u2308',
  10261. rceil: '\u2309',
  10262. lfloor: '\u230A',
  10263. rfloor: '\u230B',
  10264. loz: '\u25CA',
  10265. spades: '\u2660',
  10266. clubs: '\u2663',
  10267. hearts: '\u2665',
  10268. diams: '\u2666',
  10269. lang: '\u27E8',
  10270. rang: '\u27E9'
  10271. };
  10272. /***/ },
  10273. /* 15 */
  10274. /***/ function(module, exports, __webpack_require__) {
  10275. "use strict";
  10276. Object.defineProperty(exports, "__esModule", { value: true });
  10277. var error_handler_1 = __webpack_require__(10);
  10278. var scanner_1 = __webpack_require__(12);
  10279. var token_1 = __webpack_require__(13);
  10280. var Reader = (function () {
  10281. function Reader() {
  10282. this.values = [];
  10283. this.curly = this.paren = -1;
  10284. }
  10285. // A function following one of those tokens is an expression.
  10286. Reader.prototype.beforeFunctionExpression = function (t) {
  10287. return ['(', '{', '[', 'in', 'typeof', 'instanceof', 'new',
  10288. 'return', 'case', 'delete', 'throw', 'void',
  10289. // assignment operators
  10290. '=', '+=', '-=', '*=', '**=', '/=', '%=', '<<=', '>>=', '>>>=',
  10291. '&=', '|=', '^=', ',',
  10292. // binary/unary operators
  10293. '+', '-', '*', '**', '/', '%', '++', '--', '<<', '>>', '>>>', '&',
  10294. '|', '^', '!', '~', '&&', '||', '?', ':', '===', '==', '>=',
  10295. '<=', '<', '>', '!=', '!=='].indexOf(t) >= 0;
  10296. };
  10297. // Determine if forward slash (/) is an operator or part of a regular expression
  10298. // https://github.com/mozilla/sweet.js/wiki/design
  10299. Reader.prototype.isRegexStart = function () {
  10300. var previous = this.values[this.values.length - 1];
  10301. var regex = (previous !== null);
  10302. switch (previous) {
  10303. case 'this':
  10304. case ']':
  10305. regex = false;
  10306. break;
  10307. case ')':
  10308. var keyword = this.values[this.paren - 1];
  10309. regex = (keyword === 'if' || keyword === 'while' || keyword === 'for' || keyword === 'with');
  10310. break;
  10311. case '}':
  10312. // Dividing a function by anything makes little sense,
  10313. // but we have to check for that.
  10314. regex = false;
  10315. if (this.values[this.curly - 3] === 'function') {
  10316. // Anonymous function, e.g. function(){} /42
  10317. var check = this.values[this.curly - 4];
  10318. regex = check ? !this.beforeFunctionExpression(check) : false;
  10319. }
  10320. else if (this.values[this.curly - 4] === 'function') {
  10321. // Named function, e.g. function f(){} /42/
  10322. var check = this.values[this.curly - 5];
  10323. regex = check ? !this.beforeFunctionExpression(check) : true;
  10324. }
  10325. break;
  10326. default:
  10327. break;
  10328. }
  10329. return regex;
  10330. };
  10331. Reader.prototype.push = function (token) {
  10332. if (token.type === 7 /* Punctuator */ || token.type === 4 /* Keyword */) {
  10333. if (token.value === '{') {
  10334. this.curly = this.values.length;
  10335. }
  10336. else if (token.value === '(') {
  10337. this.paren = this.values.length;
  10338. }
  10339. this.values.push(token.value);
  10340. }
  10341. else {
  10342. this.values.push(null);
  10343. }
  10344. };
  10345. return Reader;
  10346. }());
  10347. var Tokenizer = (function () {
  10348. function Tokenizer(code, config) {
  10349. this.errorHandler = new error_handler_1.ErrorHandler();
  10350. this.errorHandler.tolerant = config ? (typeof config.tolerant === 'boolean' && config.tolerant) : false;
  10351. this.scanner = new scanner_1.Scanner(code, this.errorHandler);
  10352. this.scanner.trackComment = config ? (typeof config.comment === 'boolean' && config.comment) : false;
  10353. this.trackRange = config ? (typeof config.range === 'boolean' && config.range) : false;
  10354. this.trackLoc = config ? (typeof config.loc === 'boolean' && config.loc) : false;
  10355. this.buffer = [];
  10356. this.reader = new Reader();
  10357. }
  10358. Tokenizer.prototype.errors = function () {
  10359. return this.errorHandler.errors;
  10360. };
  10361. Tokenizer.prototype.getNextToken = function () {
  10362. if (this.buffer.length === 0) {
  10363. var comments = this.scanner.scanComments();
  10364. if (this.scanner.trackComment) {
  10365. for (var i = 0; i < comments.length; ++i) {
  10366. var e = comments[i];
  10367. var value = this.scanner.source.slice(e.slice[0], e.slice[1]);
  10368. var comment = {
  10369. type: e.multiLine ? 'BlockComment' : 'LineComment',
  10370. value: value
  10371. };
  10372. if (this.trackRange) {
  10373. comment.range = e.range;
  10374. }
  10375. if (this.trackLoc) {
  10376. comment.loc = e.loc;
  10377. }
  10378. this.buffer.push(comment);
  10379. }
  10380. }
  10381. if (!this.scanner.eof()) {
  10382. var loc = void 0;
  10383. if (this.trackLoc) {
  10384. loc = {
  10385. start: {
  10386. line: this.scanner.lineNumber,
  10387. column: this.scanner.index - this.scanner.lineStart
  10388. },
  10389. end: {}
  10390. };
  10391. }
  10392. var startRegex = (this.scanner.source[this.scanner.index] === '/') && this.reader.isRegexStart();
  10393. var token = startRegex ? this.scanner.scanRegExp() : this.scanner.lex();
  10394. this.reader.push(token);
  10395. var entry = {
  10396. type: token_1.TokenName[token.type],
  10397. value: this.scanner.source.slice(token.start, token.end)
  10398. };
  10399. if (this.trackRange) {
  10400. entry.range = [token.start, token.end];
  10401. }
  10402. if (this.trackLoc) {
  10403. loc.end = {
  10404. line: this.scanner.lineNumber,
  10405. column: this.scanner.index - this.scanner.lineStart
  10406. };
  10407. entry.loc = loc;
  10408. }
  10409. if (token.type === 9 /* RegularExpression */) {
  10410. var pattern = token.pattern;
  10411. var flags = token.flags;
  10412. entry.regex = { pattern: pattern, flags: flags };
  10413. }
  10414. this.buffer.push(entry);
  10415. }
  10416. }
  10417. return this.buffer.shift();
  10418. };
  10419. return Tokenizer;
  10420. }());
  10421. exports.Tokenizer = Tokenizer;
  10422. /***/ }
  10423. /******/ ])
  10424. });
  10425. ;
  10426. /*global define, Reflect */
  10427. /*
  10428. * xpcshell has a smaller stack on linux and windows (1MB vs 9MB on mac),
  10429. * and the recursive nature of esprima can cause it to overflow pretty
  10430. * quickly. So favor it built in Reflect parser:
  10431. * https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API
  10432. */
  10433. define('esprimaAdapter', ['./esprima', 'env'], function (esprima, env) {
  10434. if (env.get() === 'xpconnect' && typeof Reflect !== 'undefined') {
  10435. return Reflect;
  10436. } else {
  10437. return esprima;
  10438. }
  10439. });
  10440. (function webpackUniversalModuleDefinition(root, factory) {
  10441. var exports, module;
  10442. if(typeof exports === 'object' && typeof module === 'object')
  10443. module.exports = factory();
  10444. else if(typeof define === 'function' && define.amd)
  10445. define('source-map', [], factory);
  10446. else if(typeof exports === 'object')
  10447. exports["sourceMap"] = factory();
  10448. else
  10449. root["sourceMap"] = factory();
  10450. })(this, function() {
  10451. return /******/ (function(modules) { // webpackBootstrap
  10452. /******/ // The module cache
  10453. /******/ var installedModules = {};
  10454. /******/ // The require function
  10455. /******/ function __webpack_require__(moduleId) {
  10456. /******/ // Check if module is in cache
  10457. /******/ if(installedModules[moduleId])
  10458. /******/ return installedModules[moduleId].exports;
  10459. /******/ // Create a new module (and put it into the cache)
  10460. /******/ var module = installedModules[moduleId] = {
  10461. /******/ exports: {},
  10462. /******/ id: moduleId,
  10463. /******/ loaded: false
  10464. /******/ };
  10465. /******/ // Execute the module function
  10466. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  10467. /******/ // Flag the module as loaded
  10468. /******/ module.loaded = true;
  10469. /******/ // Return the exports of the module
  10470. /******/ return module.exports;
  10471. /******/ }
  10472. /******/ // expose the modules object (__webpack_modules__)
  10473. /******/ __webpack_require__.m = modules;
  10474. /******/ // expose the module cache
  10475. /******/ __webpack_require__.c = installedModules;
  10476. /******/ // __webpack_public_path__
  10477. /******/ __webpack_require__.p = "";
  10478. /******/ // Load entry module and return exports
  10479. /******/ return __webpack_require__(0);
  10480. /******/ })
  10481. /************************************************************************/
  10482. /******/ ([
  10483. /* 0 */
  10484. /***/ function(module, exports, __webpack_require__) {
  10485. /*
  10486. * Copyright 2009-2011 Mozilla Foundation and contributors
  10487. * Licensed under the New BSD license. See LICENSE.txt or:
  10488. * http://opensource.org/licenses/BSD-3-Clause
  10489. */
  10490. exports.SourceMapGenerator = __webpack_require__(1).SourceMapGenerator;
  10491. exports.SourceMapConsumer = __webpack_require__(7).SourceMapConsumer;
  10492. exports.SourceNode = __webpack_require__(10).SourceNode;
  10493. /***/ },
  10494. /* 1 */
  10495. /***/ function(module, exports, __webpack_require__) {
  10496. /* -*- Mode: js; js-indent-level: 2; -*- */
  10497. /*
  10498. * Copyright 2011 Mozilla Foundation and contributors
  10499. * Licensed under the New BSD license. See LICENSE or:
  10500. * http://opensource.org/licenses/BSD-3-Clause
  10501. */
  10502. var base64VLQ = __webpack_require__(2);
  10503. var util = __webpack_require__(4);
  10504. var ArraySet = __webpack_require__(5).ArraySet;
  10505. var MappingList = __webpack_require__(6).MappingList;
  10506. /**
  10507. * An instance of the SourceMapGenerator represents a source map which is
  10508. * being built incrementally. You may pass an object with the following
  10509. * properties:
  10510. *
  10511. * - file: The filename of the generated source.
  10512. * - sourceRoot: A root for all relative URLs in this source map.
  10513. */
  10514. function SourceMapGenerator(aArgs) {
  10515. if (!aArgs) {
  10516. aArgs = {};
  10517. }
  10518. this._file = util.getArg(aArgs, 'file', null);
  10519. this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
  10520. this._skipValidation = util.getArg(aArgs, 'skipValidation', false);
  10521. this._sources = new ArraySet();
  10522. this._names = new ArraySet();
  10523. this._mappings = new MappingList();
  10524. this._sourcesContents = null;
  10525. }
  10526. SourceMapGenerator.prototype._version = 3;
  10527. /**
  10528. * Creates a new SourceMapGenerator based on a SourceMapConsumer
  10529. *
  10530. * @param aSourceMapConsumer The SourceMap.
  10531. */
  10532. SourceMapGenerator.fromSourceMap =
  10533. function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
  10534. var sourceRoot = aSourceMapConsumer.sourceRoot;
  10535. var generator = new SourceMapGenerator({
  10536. file: aSourceMapConsumer.file,
  10537. sourceRoot: sourceRoot
  10538. });
  10539. aSourceMapConsumer.eachMapping(function (mapping) {
  10540. var newMapping = {
  10541. generated: {
  10542. line: mapping.generatedLine,
  10543. column: mapping.generatedColumn
  10544. }
  10545. };
  10546. if (mapping.source != null) {
  10547. newMapping.source = mapping.source;
  10548. if (sourceRoot != null) {
  10549. newMapping.source = util.relative(sourceRoot, newMapping.source);
  10550. }
  10551. newMapping.original = {
  10552. line: mapping.originalLine,
  10553. column: mapping.originalColumn
  10554. };
  10555. if (mapping.name != null) {
  10556. newMapping.name = mapping.name;
  10557. }
  10558. }
  10559. generator.addMapping(newMapping);
  10560. });
  10561. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  10562. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  10563. if (content != null) {
  10564. generator.setSourceContent(sourceFile, content);
  10565. }
  10566. });
  10567. return generator;
  10568. };
  10569. /**
  10570. * Add a single mapping from original source line and column to the generated
  10571. * source's line and column for this source map being created. The mapping
  10572. * object should have the following properties:
  10573. *
  10574. * - generated: An object with the generated line and column positions.
  10575. * - original: An object with the original line and column positions.
  10576. * - source: The original source file (relative to the sourceRoot).
  10577. * - name: An optional original token name for this mapping.
  10578. */
  10579. SourceMapGenerator.prototype.addMapping =
  10580. function SourceMapGenerator_addMapping(aArgs) {
  10581. var generated = util.getArg(aArgs, 'generated');
  10582. var original = util.getArg(aArgs, 'original', null);
  10583. var source = util.getArg(aArgs, 'source', null);
  10584. var name = util.getArg(aArgs, 'name', null);
  10585. if (!this._skipValidation) {
  10586. this._validateMapping(generated, original, source, name);
  10587. }
  10588. if (source != null) {
  10589. source = String(source);
  10590. if (!this._sources.has(source)) {
  10591. this._sources.add(source);
  10592. }
  10593. }
  10594. if (name != null) {
  10595. name = String(name);
  10596. if (!this._names.has(name)) {
  10597. this._names.add(name);
  10598. }
  10599. }
  10600. this._mappings.add({
  10601. generatedLine: generated.line,
  10602. generatedColumn: generated.column,
  10603. originalLine: original != null && original.line,
  10604. originalColumn: original != null && original.column,
  10605. source: source,
  10606. name: name
  10607. });
  10608. };
  10609. /**
  10610. * Set the source content for a source file.
  10611. */
  10612. SourceMapGenerator.prototype.setSourceContent =
  10613. function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
  10614. var source = aSourceFile;
  10615. if (this._sourceRoot != null) {
  10616. source = util.relative(this._sourceRoot, source);
  10617. }
  10618. if (aSourceContent != null) {
  10619. // Add the source content to the _sourcesContents map.
  10620. // Create a new _sourcesContents map if the property is null.
  10621. if (!this._sourcesContents) {
  10622. this._sourcesContents = Object.create(null);
  10623. }
  10624. this._sourcesContents[util.toSetString(source)] = aSourceContent;
  10625. } else if (this._sourcesContents) {
  10626. // Remove the source file from the _sourcesContents map.
  10627. // If the _sourcesContents map is empty, set the property to null.
  10628. delete this._sourcesContents[util.toSetString(source)];
  10629. if (Object.keys(this._sourcesContents).length === 0) {
  10630. this._sourcesContents = null;
  10631. }
  10632. }
  10633. };
  10634. /**
  10635. * Applies the mappings of a sub-source-map for a specific source file to the
  10636. * source map being generated. Each mapping to the supplied source file is
  10637. * rewritten using the supplied source map. Note: The resolution for the
  10638. * resulting mappings is the minimium of this map and the supplied map.
  10639. *
  10640. * @param aSourceMapConsumer The source map to be applied.
  10641. * @param aSourceFile Optional. The filename of the source file.
  10642. * If omitted, SourceMapConsumer's file property will be used.
  10643. * @param aSourceMapPath Optional. The dirname of the path to the source map
  10644. * to be applied. If relative, it is relative to the SourceMapConsumer.
  10645. * This parameter is needed when the two source maps aren't in the same
  10646. * directory, and the source map to be applied contains relative source
  10647. * paths. If so, those relative source paths need to be rewritten
  10648. * relative to the SourceMapGenerator.
  10649. */
  10650. SourceMapGenerator.prototype.applySourceMap =
  10651. function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
  10652. var sourceFile = aSourceFile;
  10653. // If aSourceFile is omitted, we will use the file property of the SourceMap
  10654. if (aSourceFile == null) {
  10655. if (aSourceMapConsumer.file == null) {
  10656. throw new Error(
  10657. 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
  10658. 'or the source map\'s "file" property. Both were omitted.'
  10659. );
  10660. }
  10661. sourceFile = aSourceMapConsumer.file;
  10662. }
  10663. var sourceRoot = this._sourceRoot;
  10664. // Make "sourceFile" relative if an absolute Url is passed.
  10665. if (sourceRoot != null) {
  10666. sourceFile = util.relative(sourceRoot, sourceFile);
  10667. }
  10668. // Applying the SourceMap can add and remove items from the sources and
  10669. // the names array.
  10670. var newSources = new ArraySet();
  10671. var newNames = new ArraySet();
  10672. // Find mappings for the "sourceFile"
  10673. this._mappings.unsortedForEach(function (mapping) {
  10674. if (mapping.source === sourceFile && mapping.originalLine != null) {
  10675. // Check if it can be mapped by the source map, then update the mapping.
  10676. var original = aSourceMapConsumer.originalPositionFor({
  10677. line: mapping.originalLine,
  10678. column: mapping.originalColumn
  10679. });
  10680. if (original.source != null) {
  10681. // Copy mapping
  10682. mapping.source = original.source;
  10683. if (aSourceMapPath != null) {
  10684. mapping.source = util.join(aSourceMapPath, mapping.source)
  10685. }
  10686. if (sourceRoot != null) {
  10687. mapping.source = util.relative(sourceRoot, mapping.source);
  10688. }
  10689. mapping.originalLine = original.line;
  10690. mapping.originalColumn = original.column;
  10691. if (original.name != null) {
  10692. mapping.name = original.name;
  10693. }
  10694. }
  10695. }
  10696. var source = mapping.source;
  10697. if (source != null && !newSources.has(source)) {
  10698. newSources.add(source);
  10699. }
  10700. var name = mapping.name;
  10701. if (name != null && !newNames.has(name)) {
  10702. newNames.add(name);
  10703. }
  10704. }, this);
  10705. this._sources = newSources;
  10706. this._names = newNames;
  10707. // Copy sourcesContents of applied map.
  10708. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  10709. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  10710. if (content != null) {
  10711. if (aSourceMapPath != null) {
  10712. sourceFile = util.join(aSourceMapPath, sourceFile);
  10713. }
  10714. if (sourceRoot != null) {
  10715. sourceFile = util.relative(sourceRoot, sourceFile);
  10716. }
  10717. this.setSourceContent(sourceFile, content);
  10718. }
  10719. }, this);
  10720. };
  10721. /**
  10722. * A mapping can have one of the three levels of data:
  10723. *
  10724. * 1. Just the generated position.
  10725. * 2. The Generated position, original position, and original source.
  10726. * 3. Generated and original position, original source, as well as a name
  10727. * token.
  10728. *
  10729. * To maintain consistency, we validate that any new mapping being added falls
  10730. * in to one of these categories.
  10731. */
  10732. SourceMapGenerator.prototype._validateMapping =
  10733. function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
  10734. aName) {
  10735. if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  10736. && aGenerated.line > 0 && aGenerated.column >= 0
  10737. && !aOriginal && !aSource && !aName) {
  10738. // Case 1.
  10739. return;
  10740. }
  10741. else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  10742. && aOriginal && 'line' in aOriginal && 'column' in aOriginal
  10743. && aGenerated.line > 0 && aGenerated.column >= 0
  10744. && aOriginal.line > 0 && aOriginal.column >= 0
  10745. && aSource) {
  10746. // Cases 2 and 3.
  10747. return;
  10748. }
  10749. else {
  10750. throw new Error('Invalid mapping: ' + JSON.stringify({
  10751. generated: aGenerated,
  10752. source: aSource,
  10753. original: aOriginal,
  10754. name: aName
  10755. }));
  10756. }
  10757. };
  10758. /**
  10759. * Serialize the accumulated mappings in to the stream of base 64 VLQs
  10760. * specified by the source map format.
  10761. */
  10762. SourceMapGenerator.prototype._serializeMappings =
  10763. function SourceMapGenerator_serializeMappings() {
  10764. var previousGeneratedColumn = 0;
  10765. var previousGeneratedLine = 1;
  10766. var previousOriginalColumn = 0;
  10767. var previousOriginalLine = 0;
  10768. var previousName = 0;
  10769. var previousSource = 0;
  10770. var result = '';
  10771. var next;
  10772. var mapping;
  10773. var nameIdx;
  10774. var sourceIdx;
  10775. var mappings = this._mappings.toArray();
  10776. for (var i = 0, len = mappings.length; i < len; i++) {
  10777. mapping = mappings[i];
  10778. next = ''
  10779. if (mapping.generatedLine !== previousGeneratedLine) {
  10780. previousGeneratedColumn = 0;
  10781. while (mapping.generatedLine !== previousGeneratedLine) {
  10782. next += ';';
  10783. previousGeneratedLine++;
  10784. }
  10785. }
  10786. else {
  10787. if (i > 0) {
  10788. if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
  10789. continue;
  10790. }
  10791. next += ',';
  10792. }
  10793. }
  10794. next += base64VLQ.encode(mapping.generatedColumn
  10795. - previousGeneratedColumn);
  10796. previousGeneratedColumn = mapping.generatedColumn;
  10797. if (mapping.source != null) {
  10798. sourceIdx = this._sources.indexOf(mapping.source);
  10799. next += base64VLQ.encode(sourceIdx - previousSource);
  10800. previousSource = sourceIdx;
  10801. // lines are stored 0-based in SourceMap spec version 3
  10802. next += base64VLQ.encode(mapping.originalLine - 1
  10803. - previousOriginalLine);
  10804. previousOriginalLine = mapping.originalLine - 1;
  10805. next += base64VLQ.encode(mapping.originalColumn
  10806. - previousOriginalColumn);
  10807. previousOriginalColumn = mapping.originalColumn;
  10808. if (mapping.name != null) {
  10809. nameIdx = this._names.indexOf(mapping.name);
  10810. next += base64VLQ.encode(nameIdx - previousName);
  10811. previousName = nameIdx;
  10812. }
  10813. }
  10814. result += next;
  10815. }
  10816. return result;
  10817. };
  10818. SourceMapGenerator.prototype._generateSourcesContent =
  10819. function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
  10820. return aSources.map(function (source) {
  10821. if (!this._sourcesContents) {
  10822. return null;
  10823. }
  10824. if (aSourceRoot != null) {
  10825. source = util.relative(aSourceRoot, source);
  10826. }
  10827. var key = util.toSetString(source);
  10828. return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
  10829. ? this._sourcesContents[key]
  10830. : null;
  10831. }, this);
  10832. };
  10833. /**
  10834. * Externalize the source map.
  10835. */
  10836. SourceMapGenerator.prototype.toJSON =
  10837. function SourceMapGenerator_toJSON() {
  10838. var map = {
  10839. version: this._version,
  10840. sources: this._sources.toArray(),
  10841. names: this._names.toArray(),
  10842. mappings: this._serializeMappings()
  10843. };
  10844. if (this._file != null) {
  10845. map.file = this._file;
  10846. }
  10847. if (this._sourceRoot != null) {
  10848. map.sourceRoot = this._sourceRoot;
  10849. }
  10850. if (this._sourcesContents) {
  10851. map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
  10852. }
  10853. return map;
  10854. };
  10855. /**
  10856. * Render the source map being generated to a string.
  10857. */
  10858. SourceMapGenerator.prototype.toString =
  10859. function SourceMapGenerator_toString() {
  10860. return JSON.stringify(this.toJSON());
  10861. };
  10862. exports.SourceMapGenerator = SourceMapGenerator;
  10863. /***/ },
  10864. /* 2 */
  10865. /***/ function(module, exports, __webpack_require__) {
  10866. /* -*- Mode: js; js-indent-level: 2; -*- */
  10867. /*
  10868. * Copyright 2011 Mozilla Foundation and contributors
  10869. * Licensed under the New BSD license. See LICENSE or:
  10870. * http://opensource.org/licenses/BSD-3-Clause
  10871. *
  10872. * Based on the Base 64 VLQ implementation in Closure Compiler:
  10873. * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
  10874. *
  10875. * Copyright 2011 The Closure Compiler Authors. All rights reserved.
  10876. * Redistribution and use in source and binary forms, with or without
  10877. * modification, are permitted provided that the following conditions are
  10878. * met:
  10879. *
  10880. * * Redistributions of source code must retain the above copyright
  10881. * notice, this list of conditions and the following disclaimer.
  10882. * * Redistributions in binary form must reproduce the above
  10883. * copyright notice, this list of conditions and the following
  10884. * disclaimer in the documentation and/or other materials provided
  10885. * with the distribution.
  10886. * * Neither the name of Google Inc. nor the names of its
  10887. * contributors may be used to endorse or promote products derived
  10888. * from this software without specific prior written permission.
  10889. *
  10890. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  10891. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  10892. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  10893. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  10894. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  10895. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  10896. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  10897. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  10898. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  10899. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  10900. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  10901. */
  10902. var base64 = __webpack_require__(3);
  10903. // A single base 64 digit can contain 6 bits of data. For the base 64 variable
  10904. // length quantities we use in the source map spec, the first bit is the sign,
  10905. // the next four bits are the actual value, and the 6th bit is the
  10906. // continuation bit. The continuation bit tells us whether there are more
  10907. // digits in this value following this digit.
  10908. //
  10909. // Continuation
  10910. // | Sign
  10911. // | |
  10912. // V V
  10913. // 101011
  10914. var VLQ_BASE_SHIFT = 5;
  10915. // binary: 100000
  10916. var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
  10917. // binary: 011111
  10918. var VLQ_BASE_MASK = VLQ_BASE - 1;
  10919. // binary: 100000
  10920. var VLQ_CONTINUATION_BIT = VLQ_BASE;
  10921. /**
  10922. * Converts from a two-complement value to a value where the sign bit is
  10923. * placed in the least significant bit. For example, as decimals:
  10924. * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
  10925. * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
  10926. */
  10927. function toVLQSigned(aValue) {
  10928. return aValue < 0
  10929. ? ((-aValue) << 1) + 1
  10930. : (aValue << 1) + 0;
  10931. }
  10932. /**
  10933. * Converts to a two-complement value from a value where the sign bit is
  10934. * placed in the least significant bit. For example, as decimals:
  10935. * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
  10936. * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
  10937. */
  10938. function fromVLQSigned(aValue) {
  10939. var isNegative = (aValue & 1) === 1;
  10940. var shifted = aValue >> 1;
  10941. return isNegative
  10942. ? -shifted
  10943. : shifted;
  10944. }
  10945. /**
  10946. * Returns the base 64 VLQ encoded value.
  10947. */
  10948. exports.encode = function base64VLQ_encode(aValue) {
  10949. var encoded = "";
  10950. var digit;
  10951. var vlq = toVLQSigned(aValue);
  10952. do {
  10953. digit = vlq & VLQ_BASE_MASK;
  10954. vlq >>>= VLQ_BASE_SHIFT;
  10955. if (vlq > 0) {
  10956. // There are still more digits in this value, so we must make sure the
  10957. // continuation bit is marked.
  10958. digit |= VLQ_CONTINUATION_BIT;
  10959. }
  10960. encoded += base64.encode(digit);
  10961. } while (vlq > 0);
  10962. return encoded;
  10963. };
  10964. /**
  10965. * Decodes the next base 64 VLQ value from the given string and returns the
  10966. * value and the rest of the string via the out parameter.
  10967. */
  10968. exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) {
  10969. var strLen = aStr.length;
  10970. var result = 0;
  10971. var shift = 0;
  10972. var continuation, digit;
  10973. do {
  10974. if (aIndex >= strLen) {
  10975. throw new Error("Expected more digits in base 64 VLQ value.");
  10976. }
  10977. digit = base64.decode(aStr.charCodeAt(aIndex++));
  10978. if (digit === -1) {
  10979. throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
  10980. }
  10981. continuation = !!(digit & VLQ_CONTINUATION_BIT);
  10982. digit &= VLQ_BASE_MASK;
  10983. result = result + (digit << shift);
  10984. shift += VLQ_BASE_SHIFT;
  10985. } while (continuation);
  10986. aOutParam.value = fromVLQSigned(result);
  10987. aOutParam.rest = aIndex;
  10988. };
  10989. /***/ },
  10990. /* 3 */
  10991. /***/ function(module, exports) {
  10992. /* -*- Mode: js; js-indent-level: 2; -*- */
  10993. /*
  10994. * Copyright 2011 Mozilla Foundation and contributors
  10995. * Licensed under the New BSD license. See LICENSE or:
  10996. * http://opensource.org/licenses/BSD-3-Clause
  10997. */
  10998. var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
  10999. /**
  11000. * Encode an integer in the range of 0 to 63 to a single base 64 digit.
  11001. */
  11002. exports.encode = function (number) {
  11003. if (0 <= number && number < intToCharMap.length) {
  11004. return intToCharMap[number];
  11005. }
  11006. throw new TypeError("Must be between 0 and 63: " + number);
  11007. };
  11008. /**
  11009. * Decode a single base 64 character code digit to an integer. Returns -1 on
  11010. * failure.
  11011. */
  11012. exports.decode = function (charCode) {
  11013. var bigA = 65; // 'A'
  11014. var bigZ = 90; // 'Z'
  11015. var littleA = 97; // 'a'
  11016. var littleZ = 122; // 'z'
  11017. var zero = 48; // '0'
  11018. var nine = 57; // '9'
  11019. var plus = 43; // '+'
  11020. var slash = 47; // '/'
  11021. var littleOffset = 26;
  11022. var numberOffset = 52;
  11023. // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
  11024. if (bigA <= charCode && charCode <= bigZ) {
  11025. return (charCode - bigA);
  11026. }
  11027. // 26 - 51: abcdefghijklmnopqrstuvwxyz
  11028. if (littleA <= charCode && charCode <= littleZ) {
  11029. return (charCode - littleA + littleOffset);
  11030. }
  11031. // 52 - 61: 0123456789
  11032. if (zero <= charCode && charCode <= nine) {
  11033. return (charCode - zero + numberOffset);
  11034. }
  11035. // 62: +
  11036. if (charCode == plus) {
  11037. return 62;
  11038. }
  11039. // 63: /
  11040. if (charCode == slash) {
  11041. return 63;
  11042. }
  11043. // Invalid base64 digit.
  11044. return -1;
  11045. };
  11046. /***/ },
  11047. /* 4 */
  11048. /***/ function(module, exports) {
  11049. /* -*- Mode: js; js-indent-level: 2; -*- */
  11050. /*
  11051. * Copyright 2011 Mozilla Foundation and contributors
  11052. * Licensed under the New BSD license. See LICENSE or:
  11053. * http://opensource.org/licenses/BSD-3-Clause
  11054. */
  11055. /**
  11056. * This is a helper function for getting values from parameter/options
  11057. * objects.
  11058. *
  11059. * @param args The object we are extracting values from
  11060. * @param name The name of the property we are getting.
  11061. * @param defaultValue An optional value to return if the property is missing
  11062. * from the object. If this is not specified and the property is missing, an
  11063. * error will be thrown.
  11064. */
  11065. function getArg(aArgs, aName, aDefaultValue) {
  11066. if (aName in aArgs) {
  11067. return aArgs[aName];
  11068. } else if (arguments.length === 3) {
  11069. return aDefaultValue;
  11070. } else {
  11071. throw new Error('"' + aName + '" is a required argument.');
  11072. }
  11073. }
  11074. exports.getArg = getArg;
  11075. var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/;
  11076. var dataUrlRegexp = /^data:.+\,.+$/;
  11077. function urlParse(aUrl) {
  11078. var match = aUrl.match(urlRegexp);
  11079. if (!match) {
  11080. return null;
  11081. }
  11082. return {
  11083. scheme: match[1],
  11084. auth: match[2],
  11085. host: match[3],
  11086. port: match[4],
  11087. path: match[5]
  11088. };
  11089. }
  11090. exports.urlParse = urlParse;
  11091. function urlGenerate(aParsedUrl) {
  11092. var url = '';
  11093. if (aParsedUrl.scheme) {
  11094. url += aParsedUrl.scheme + ':';
  11095. }
  11096. url += '//';
  11097. if (aParsedUrl.auth) {
  11098. url += aParsedUrl.auth + '@';
  11099. }
  11100. if (aParsedUrl.host) {
  11101. url += aParsedUrl.host;
  11102. }
  11103. if (aParsedUrl.port) {
  11104. url += ":" + aParsedUrl.port
  11105. }
  11106. if (aParsedUrl.path) {
  11107. url += aParsedUrl.path;
  11108. }
  11109. return url;
  11110. }
  11111. exports.urlGenerate = urlGenerate;
  11112. /**
  11113. * Normalizes a path, or the path portion of a URL:
  11114. *
  11115. * - Replaces consequtive slashes with one slash.
  11116. * - Removes unnecessary '.' parts.
  11117. * - Removes unnecessary '<dir>/..' parts.
  11118. *
  11119. * Based on code in the Node.js 'path' core module.
  11120. *
  11121. * @param aPath The path or url to normalize.
  11122. */
  11123. function normalize(aPath) {
  11124. var path = aPath;
  11125. var url = urlParse(aPath);
  11126. if (url) {
  11127. if (!url.path) {
  11128. return aPath;
  11129. }
  11130. path = url.path;
  11131. }
  11132. var isAbsolute = exports.isAbsolute(path);
  11133. var parts = path.split(/\/+/);
  11134. for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
  11135. part = parts[i];
  11136. if (part === '.') {
  11137. parts.splice(i, 1);
  11138. } else if (part === '..') {
  11139. up++;
  11140. } else if (up > 0) {
  11141. if (part === '') {
  11142. // The first part is blank if the path is absolute. Trying to go
  11143. // above the root is a no-op. Therefore we can remove all '..' parts
  11144. // directly after the root.
  11145. parts.splice(i + 1, up);
  11146. up = 0;
  11147. } else {
  11148. parts.splice(i, 2);
  11149. up--;
  11150. }
  11151. }
  11152. }
  11153. path = parts.join('/');
  11154. if (path === '') {
  11155. path = isAbsolute ? '/' : '.';
  11156. }
  11157. if (url) {
  11158. url.path = path;
  11159. return urlGenerate(url);
  11160. }
  11161. return path;
  11162. }
  11163. exports.normalize = normalize;
  11164. /**
  11165. * Joins two paths/URLs.
  11166. *
  11167. * @param aRoot The root path or URL.
  11168. * @param aPath The path or URL to be joined with the root.
  11169. *
  11170. * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
  11171. * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
  11172. * first.
  11173. * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
  11174. * is updated with the result and aRoot is returned. Otherwise the result
  11175. * is returned.
  11176. * - If aPath is absolute, the result is aPath.
  11177. * - Otherwise the two paths are joined with a slash.
  11178. * - Joining for example 'http://' and 'www.example.com' is also supported.
  11179. */
  11180. function join(aRoot, aPath) {
  11181. if (aRoot === "") {
  11182. aRoot = ".";
  11183. }
  11184. if (aPath === "") {
  11185. aPath = ".";
  11186. }
  11187. var aPathUrl = urlParse(aPath);
  11188. var aRootUrl = urlParse(aRoot);
  11189. if (aRootUrl) {
  11190. aRoot = aRootUrl.path || '/';
  11191. }
  11192. // `join(foo, '//www.example.org')`
  11193. if (aPathUrl && !aPathUrl.scheme) {
  11194. if (aRootUrl) {
  11195. aPathUrl.scheme = aRootUrl.scheme;
  11196. }
  11197. return urlGenerate(aPathUrl);
  11198. }
  11199. if (aPathUrl || aPath.match(dataUrlRegexp)) {
  11200. return aPath;
  11201. }
  11202. // `join('http://', 'www.example.com')`
  11203. if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
  11204. aRootUrl.host = aPath;
  11205. return urlGenerate(aRootUrl);
  11206. }
  11207. var joined = aPath.charAt(0) === '/'
  11208. ? aPath
  11209. : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
  11210. if (aRootUrl) {
  11211. aRootUrl.path = joined;
  11212. return urlGenerate(aRootUrl);
  11213. }
  11214. return joined;
  11215. }
  11216. exports.join = join;
  11217. exports.isAbsolute = function (aPath) {
  11218. return aPath.charAt(0) === '/' || !!aPath.match(urlRegexp);
  11219. };
  11220. /**
  11221. * Make a path relative to a URL or another path.
  11222. *
  11223. * @param aRoot The root path or URL.
  11224. * @param aPath The path or URL to be made relative to aRoot.
  11225. */
  11226. function relative(aRoot, aPath) {
  11227. if (aRoot === "") {
  11228. aRoot = ".";
  11229. }
  11230. aRoot = aRoot.replace(/\/$/, '');
  11231. // It is possible for the path to be above the root. In this case, simply
  11232. // checking whether the root is a prefix of the path won't work. Instead, we
  11233. // need to remove components from the root one by one, until either we find
  11234. // a prefix that fits, or we run out of components to remove.
  11235. var level = 0;
  11236. while (aPath.indexOf(aRoot + '/') !== 0) {
  11237. var index = aRoot.lastIndexOf("/");
  11238. if (index < 0) {
  11239. return aPath;
  11240. }
  11241. // If the only part of the root that is left is the scheme (i.e. http://,
  11242. // file:///, etc.), one or more slashes (/), or simply nothing at all, we
  11243. // have exhausted all components, so the path is not relative to the root.
  11244. aRoot = aRoot.slice(0, index);
  11245. if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
  11246. return aPath;
  11247. }
  11248. ++level;
  11249. }
  11250. // Make sure we add a "../" for each component we removed from the root.
  11251. return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
  11252. }
  11253. exports.relative = relative;
  11254. var supportsNullProto = (function () {
  11255. var obj = Object.create(null);
  11256. return !('__proto__' in obj);
  11257. }());
  11258. function identity (s) {
  11259. return s;
  11260. }
  11261. /**
  11262. * Because behavior goes wacky when you set `__proto__` on objects, we
  11263. * have to prefix all the strings in our set with an arbitrary character.
  11264. *
  11265. * See https://github.com/mozilla/source-map/pull/31 and
  11266. * https://github.com/mozilla/source-map/issues/30
  11267. *
  11268. * @param String aStr
  11269. */
  11270. function toSetString(aStr) {
  11271. if (isProtoString(aStr)) {
  11272. return '$' + aStr;
  11273. }
  11274. return aStr;
  11275. }
  11276. exports.toSetString = supportsNullProto ? identity : toSetString;
  11277. function fromSetString(aStr) {
  11278. if (isProtoString(aStr)) {
  11279. return aStr.slice(1);
  11280. }
  11281. return aStr;
  11282. }
  11283. exports.fromSetString = supportsNullProto ? identity : fromSetString;
  11284. function isProtoString(s) {
  11285. if (!s) {
  11286. return false;
  11287. }
  11288. var length = s.length;
  11289. if (length < 9 /* "__proto__".length */) {
  11290. return false;
  11291. }
  11292. if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
  11293. s.charCodeAt(length - 2) !== 95 /* '_' */ ||
  11294. s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
  11295. s.charCodeAt(length - 4) !== 116 /* 't' */ ||
  11296. s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
  11297. s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
  11298. s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
  11299. s.charCodeAt(length - 8) !== 95 /* '_' */ ||
  11300. s.charCodeAt(length - 9) !== 95 /* '_' */) {
  11301. return false;
  11302. }
  11303. for (var i = length - 10; i >= 0; i--) {
  11304. if (s.charCodeAt(i) !== 36 /* '$' */) {
  11305. return false;
  11306. }
  11307. }
  11308. return true;
  11309. }
  11310. /**
  11311. * Comparator between two mappings where the original positions are compared.
  11312. *
  11313. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  11314. * mappings with the same original source/line/column, but different generated
  11315. * line and column the same. Useful when searching for a mapping with a
  11316. * stubbed out mapping.
  11317. */
  11318. function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
  11319. var cmp = mappingA.source - mappingB.source;
  11320. if (cmp !== 0) {
  11321. return cmp;
  11322. }
  11323. cmp = mappingA.originalLine - mappingB.originalLine;
  11324. if (cmp !== 0) {
  11325. return cmp;
  11326. }
  11327. cmp = mappingA.originalColumn - mappingB.originalColumn;
  11328. if (cmp !== 0 || onlyCompareOriginal) {
  11329. return cmp;
  11330. }
  11331. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  11332. if (cmp !== 0) {
  11333. return cmp;
  11334. }
  11335. cmp = mappingA.generatedLine - mappingB.generatedLine;
  11336. if (cmp !== 0) {
  11337. return cmp;
  11338. }
  11339. return mappingA.name - mappingB.name;
  11340. }
  11341. exports.compareByOriginalPositions = compareByOriginalPositions;
  11342. /**
  11343. * Comparator between two mappings with deflated source and name indices where
  11344. * the generated positions are compared.
  11345. *
  11346. * Optionally pass in `true` as `onlyCompareGenerated` to consider two
  11347. * mappings with the same generated line and column, but different
  11348. * source/name/original line and column the same. Useful when searching for a
  11349. * mapping with a stubbed out mapping.
  11350. */
  11351. function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
  11352. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  11353. if (cmp !== 0) {
  11354. return cmp;
  11355. }
  11356. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  11357. if (cmp !== 0 || onlyCompareGenerated) {
  11358. return cmp;
  11359. }
  11360. cmp = mappingA.source - mappingB.source;
  11361. if (cmp !== 0) {
  11362. return cmp;
  11363. }
  11364. cmp = mappingA.originalLine - mappingB.originalLine;
  11365. if (cmp !== 0) {
  11366. return cmp;
  11367. }
  11368. cmp = mappingA.originalColumn - mappingB.originalColumn;
  11369. if (cmp !== 0) {
  11370. return cmp;
  11371. }
  11372. return mappingA.name - mappingB.name;
  11373. }
  11374. exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
  11375. function strcmp(aStr1, aStr2) {
  11376. if (aStr1 === aStr2) {
  11377. return 0;
  11378. }
  11379. if (aStr1 > aStr2) {
  11380. return 1;
  11381. }
  11382. return -1;
  11383. }
  11384. /**
  11385. * Comparator between two mappings with inflated source and name strings where
  11386. * the generated positions are compared.
  11387. */
  11388. function compareByGeneratedPositionsInflated(mappingA, mappingB) {
  11389. var cmp = mappingA.generatedLine - mappingB.generatedLine;
  11390. if (cmp !== 0) {
  11391. return cmp;
  11392. }
  11393. cmp = mappingA.generatedColumn - mappingB.generatedColumn;
  11394. if (cmp !== 0) {
  11395. return cmp;
  11396. }
  11397. cmp = strcmp(mappingA.source, mappingB.source);
  11398. if (cmp !== 0) {
  11399. return cmp;
  11400. }
  11401. cmp = mappingA.originalLine - mappingB.originalLine;
  11402. if (cmp !== 0) {
  11403. return cmp;
  11404. }
  11405. cmp = mappingA.originalColumn - mappingB.originalColumn;
  11406. if (cmp !== 0) {
  11407. return cmp;
  11408. }
  11409. return strcmp(mappingA.name, mappingB.name);
  11410. }
  11411. exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
  11412. /***/ },
  11413. /* 5 */
  11414. /***/ function(module, exports, __webpack_require__) {
  11415. /* -*- Mode: js; js-indent-level: 2; -*- */
  11416. /*
  11417. * Copyright 2011 Mozilla Foundation and contributors
  11418. * Licensed under the New BSD license. See LICENSE or:
  11419. * http://opensource.org/licenses/BSD-3-Clause
  11420. */
  11421. var util = __webpack_require__(4);
  11422. var has = Object.prototype.hasOwnProperty;
  11423. /**
  11424. * A data structure which is a combination of an array and a set. Adding a new
  11425. * member is O(1), testing for membership is O(1), and finding the index of an
  11426. * element is O(1). Removing elements from the set is not supported. Only
  11427. * strings are supported for membership.
  11428. */
  11429. function ArraySet() {
  11430. this._array = [];
  11431. this._set = Object.create(null);
  11432. }
  11433. /**
  11434. * Static method for creating ArraySet instances from an existing array.
  11435. */
  11436. ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
  11437. var set = new ArraySet();
  11438. for (var i = 0, len = aArray.length; i < len; i++) {
  11439. set.add(aArray[i], aAllowDuplicates);
  11440. }
  11441. return set;
  11442. };
  11443. /**
  11444. * Return how many unique items are in this ArraySet. If duplicates have been
  11445. * added, than those do not count towards the size.
  11446. *
  11447. * @returns Number
  11448. */
  11449. ArraySet.prototype.size = function ArraySet_size() {
  11450. return Object.getOwnPropertyNames(this._set).length;
  11451. };
  11452. /**
  11453. * Add the given string to this set.
  11454. *
  11455. * @param String aStr
  11456. */
  11457. ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
  11458. var sStr = util.toSetString(aStr);
  11459. var isDuplicate = has.call(this._set, sStr);
  11460. var idx = this._array.length;
  11461. if (!isDuplicate || aAllowDuplicates) {
  11462. this._array.push(aStr);
  11463. }
  11464. if (!isDuplicate) {
  11465. this._set[sStr] = idx;
  11466. }
  11467. };
  11468. /**
  11469. * Is the given string a member of this set?
  11470. *
  11471. * @param String aStr
  11472. */
  11473. ArraySet.prototype.has = function ArraySet_has(aStr) {
  11474. var sStr = util.toSetString(aStr);
  11475. return has.call(this._set, sStr);
  11476. };
  11477. /**
  11478. * What is the index of the given string in the array?
  11479. *
  11480. * @param String aStr
  11481. */
  11482. ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
  11483. var sStr = util.toSetString(aStr);
  11484. if (has.call(this._set, sStr)) {
  11485. return this._set[sStr];
  11486. }
  11487. throw new Error('"' + aStr + '" is not in the set.');
  11488. };
  11489. /**
  11490. * What is the element at the given index?
  11491. *
  11492. * @param Number aIdx
  11493. */
  11494. ArraySet.prototype.at = function ArraySet_at(aIdx) {
  11495. if (aIdx >= 0 && aIdx < this._array.length) {
  11496. return this._array[aIdx];
  11497. }
  11498. throw new Error('No element indexed by ' + aIdx);
  11499. };
  11500. /**
  11501. * Returns the array representation of this set (which has the proper indices
  11502. * indicated by indexOf). Note that this is a copy of the internal array used
  11503. * for storing the members so that no one can mess with internal state.
  11504. */
  11505. ArraySet.prototype.toArray = function ArraySet_toArray() {
  11506. return this._array.slice();
  11507. };
  11508. exports.ArraySet = ArraySet;
  11509. /***/ },
  11510. /* 6 */
  11511. /***/ function(module, exports, __webpack_require__) {
  11512. /* -*- Mode: js; js-indent-level: 2; -*- */
  11513. /*
  11514. * Copyright 2014 Mozilla Foundation and contributors
  11515. * Licensed under the New BSD license. See LICENSE or:
  11516. * http://opensource.org/licenses/BSD-3-Clause
  11517. */
  11518. var util = __webpack_require__(4);
  11519. /**
  11520. * Determine whether mappingB is after mappingA with respect to generated
  11521. * position.
  11522. */
  11523. function generatedPositionAfter(mappingA, mappingB) {
  11524. // Optimized for most common case
  11525. var lineA = mappingA.generatedLine;
  11526. var lineB = mappingB.generatedLine;
  11527. var columnA = mappingA.generatedColumn;
  11528. var columnB = mappingB.generatedColumn;
  11529. return lineB > lineA || lineB == lineA && columnB >= columnA ||
  11530. util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
  11531. }
  11532. /**
  11533. * A data structure to provide a sorted view of accumulated mappings in a
  11534. * performance conscious manner. It trades a neglibable overhead in general
  11535. * case for a large speedup in case of mappings being added in order.
  11536. */
  11537. function MappingList() {
  11538. this._array = [];
  11539. this._sorted = true;
  11540. // Serves as infimum
  11541. this._last = {generatedLine: -1, generatedColumn: 0};
  11542. }
  11543. /**
  11544. * Iterate through internal items. This method takes the same arguments that
  11545. * `Array.prototype.forEach` takes.
  11546. *
  11547. * NOTE: The order of the mappings is NOT guaranteed.
  11548. */
  11549. MappingList.prototype.unsortedForEach =
  11550. function MappingList_forEach(aCallback, aThisArg) {
  11551. this._array.forEach(aCallback, aThisArg);
  11552. };
  11553. /**
  11554. * Add the given source mapping.
  11555. *
  11556. * @param Object aMapping
  11557. */
  11558. MappingList.prototype.add = function MappingList_add(aMapping) {
  11559. if (generatedPositionAfter(this._last, aMapping)) {
  11560. this._last = aMapping;
  11561. this._array.push(aMapping);
  11562. } else {
  11563. this._sorted = false;
  11564. this._array.push(aMapping);
  11565. }
  11566. };
  11567. /**
  11568. * Returns the flat, sorted array of mappings. The mappings are sorted by
  11569. * generated position.
  11570. *
  11571. * WARNING: This method returns internal data without copying, for
  11572. * performance. The return value must NOT be mutated, and should be treated as
  11573. * an immutable borrow. If you want to take ownership, you must make your own
  11574. * copy.
  11575. */
  11576. MappingList.prototype.toArray = function MappingList_toArray() {
  11577. if (!this._sorted) {
  11578. this._array.sort(util.compareByGeneratedPositionsInflated);
  11579. this._sorted = true;
  11580. }
  11581. return this._array;
  11582. };
  11583. exports.MappingList = MappingList;
  11584. /***/ },
  11585. /* 7 */
  11586. /***/ function(module, exports, __webpack_require__) {
  11587. /* -*- Mode: js; js-indent-level: 2; -*- */
  11588. /*
  11589. * Copyright 2011 Mozilla Foundation and contributors
  11590. * Licensed under the New BSD license. See LICENSE or:
  11591. * http://opensource.org/licenses/BSD-3-Clause
  11592. */
  11593. var util = __webpack_require__(4);
  11594. var binarySearch = __webpack_require__(8);
  11595. var ArraySet = __webpack_require__(5).ArraySet;
  11596. var base64VLQ = __webpack_require__(2);
  11597. var quickSort = __webpack_require__(9).quickSort;
  11598. function SourceMapConsumer(aSourceMap) {
  11599. var sourceMap = aSourceMap;
  11600. if (typeof aSourceMap === 'string') {
  11601. sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
  11602. }
  11603. return sourceMap.sections != null
  11604. ? new IndexedSourceMapConsumer(sourceMap)
  11605. : new BasicSourceMapConsumer(sourceMap);
  11606. }
  11607. SourceMapConsumer.fromSourceMap = function(aSourceMap) {
  11608. return BasicSourceMapConsumer.fromSourceMap(aSourceMap);
  11609. }
  11610. /**
  11611. * The version of the source mapping spec that we are consuming.
  11612. */
  11613. SourceMapConsumer.prototype._version = 3;
  11614. // `__generatedMappings` and `__originalMappings` are arrays that hold the
  11615. // parsed mapping coordinates from the source map's "mappings" attribute. They
  11616. // are lazily instantiated, accessed via the `_generatedMappings` and
  11617. // `_originalMappings` getters respectively, and we only parse the mappings
  11618. // and create these arrays once queried for a source location. We jump through
  11619. // these hoops because there can be many thousands of mappings, and parsing
  11620. // them is expensive, so we only want to do it if we must.
  11621. //
  11622. // Each object in the arrays is of the form:
  11623. //
  11624. // {
  11625. // generatedLine: The line number in the generated code,
  11626. // generatedColumn: The column number in the generated code,
  11627. // source: The path to the original source file that generated this
  11628. // chunk of code,
  11629. // originalLine: The line number in the original source that
  11630. // corresponds to this chunk of generated code,
  11631. // originalColumn: The column number in the original source that
  11632. // corresponds to this chunk of generated code,
  11633. // name: The name of the original symbol which generated this chunk of
  11634. // code.
  11635. // }
  11636. //
  11637. // All properties except for `generatedLine` and `generatedColumn` can be
  11638. // `null`.
  11639. //
  11640. // `_generatedMappings` is ordered by the generated positions.
  11641. //
  11642. // `_originalMappings` is ordered by the original positions.
  11643. SourceMapConsumer.prototype.__generatedMappings = null;
  11644. Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
  11645. get: function () {
  11646. if (!this.__generatedMappings) {
  11647. this._parseMappings(this._mappings, this.sourceRoot);
  11648. }
  11649. return this.__generatedMappings;
  11650. }
  11651. });
  11652. SourceMapConsumer.prototype.__originalMappings = null;
  11653. Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
  11654. get: function () {
  11655. if (!this.__originalMappings) {
  11656. this._parseMappings(this._mappings, this.sourceRoot);
  11657. }
  11658. return this.__originalMappings;
  11659. }
  11660. });
  11661. SourceMapConsumer.prototype._charIsMappingSeparator =
  11662. function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
  11663. var c = aStr.charAt(index);
  11664. return c === ";" || c === ",";
  11665. };
  11666. /**
  11667. * Parse the mappings in a string in to a data structure which we can easily
  11668. * query (the ordered arrays in the `this.__generatedMappings` and
  11669. * `this.__originalMappings` properties).
  11670. */
  11671. SourceMapConsumer.prototype._parseMappings =
  11672. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  11673. throw new Error("Subclasses must implement _parseMappings");
  11674. };
  11675. SourceMapConsumer.GENERATED_ORDER = 1;
  11676. SourceMapConsumer.ORIGINAL_ORDER = 2;
  11677. SourceMapConsumer.GREATEST_LOWER_BOUND = 1;
  11678. SourceMapConsumer.LEAST_UPPER_BOUND = 2;
  11679. /**
  11680. * Iterate over each mapping between an original source/line/column and a
  11681. * generated line/column in this source map.
  11682. *
  11683. * @param Function aCallback
  11684. * The function that is called with each mapping.
  11685. * @param Object aContext
  11686. * Optional. If specified, this object will be the value of `this` every
  11687. * time that `aCallback` is called.
  11688. * @param aOrder
  11689. * Either `SourceMapConsumer.GENERATED_ORDER` or
  11690. * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
  11691. * iterate over the mappings sorted by the generated file's line/column
  11692. * order or the original's source/line/column order, respectively. Defaults to
  11693. * `SourceMapConsumer.GENERATED_ORDER`.
  11694. */
  11695. SourceMapConsumer.prototype.eachMapping =
  11696. function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
  11697. var context = aContext || null;
  11698. var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
  11699. var mappings;
  11700. switch (order) {
  11701. case SourceMapConsumer.GENERATED_ORDER:
  11702. mappings = this._generatedMappings;
  11703. break;
  11704. case SourceMapConsumer.ORIGINAL_ORDER:
  11705. mappings = this._originalMappings;
  11706. break;
  11707. default:
  11708. throw new Error("Unknown order of iteration.");
  11709. }
  11710. var sourceRoot = this.sourceRoot;
  11711. mappings.map(function (mapping) {
  11712. var source = mapping.source === null ? null : this._sources.at(mapping.source);
  11713. if (source != null && sourceRoot != null) {
  11714. source = util.join(sourceRoot, source);
  11715. }
  11716. return {
  11717. source: source,
  11718. generatedLine: mapping.generatedLine,
  11719. generatedColumn: mapping.generatedColumn,
  11720. originalLine: mapping.originalLine,
  11721. originalColumn: mapping.originalColumn,
  11722. name: mapping.name === null ? null : this._names.at(mapping.name)
  11723. };
  11724. }, this).forEach(aCallback, context);
  11725. };
  11726. /**
  11727. * Returns all generated line and column information for the original source,
  11728. * line, and column provided. If no column is provided, returns all mappings
  11729. * corresponding to a either the line we are searching for or the next
  11730. * closest line that has any mappings. Otherwise, returns all mappings
  11731. * corresponding to the given line and either the column we are searching for
  11732. * or the next closest column that has any offsets.
  11733. *
  11734. * The only argument is an object with the following properties:
  11735. *
  11736. * - source: The filename of the original source.
  11737. * - line: The line number in the original source.
  11738. * - column: Optional. the column number in the original source.
  11739. *
  11740. * and an array of objects is returned, each with the following properties:
  11741. *
  11742. * - line: The line number in the generated source, or null.
  11743. * - column: The column number in the generated source, or null.
  11744. */
  11745. SourceMapConsumer.prototype.allGeneratedPositionsFor =
  11746. function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
  11747. var line = util.getArg(aArgs, 'line');
  11748. // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
  11749. // returns the index of the closest mapping less than the needle. By
  11750. // setting needle.originalColumn to 0, we thus find the last mapping for
  11751. // the given line, provided such a mapping exists.
  11752. var needle = {
  11753. source: util.getArg(aArgs, 'source'),
  11754. originalLine: line,
  11755. originalColumn: util.getArg(aArgs, 'column', 0)
  11756. };
  11757. if (this.sourceRoot != null) {
  11758. needle.source = util.relative(this.sourceRoot, needle.source);
  11759. }
  11760. if (!this._sources.has(needle.source)) {
  11761. return [];
  11762. }
  11763. needle.source = this._sources.indexOf(needle.source);
  11764. var mappings = [];
  11765. var index = this._findMapping(needle,
  11766. this._originalMappings,
  11767. "originalLine",
  11768. "originalColumn",
  11769. util.compareByOriginalPositions,
  11770. binarySearch.LEAST_UPPER_BOUND);
  11771. if (index >= 0) {
  11772. var mapping = this._originalMappings[index];
  11773. if (aArgs.column === undefined) {
  11774. var originalLine = mapping.originalLine;
  11775. // Iterate until either we run out of mappings, or we run into
  11776. // a mapping for a different line than the one we found. Since
  11777. // mappings are sorted, this is guaranteed to find all mappings for
  11778. // the line we found.
  11779. while (mapping && mapping.originalLine === originalLine) {
  11780. mappings.push({
  11781. line: util.getArg(mapping, 'generatedLine', null),
  11782. column: util.getArg(mapping, 'generatedColumn', null),
  11783. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  11784. });
  11785. mapping = this._originalMappings[++index];
  11786. }
  11787. } else {
  11788. var originalColumn = mapping.originalColumn;
  11789. // Iterate until either we run out of mappings, or we run into
  11790. // a mapping for a different line than the one we were searching for.
  11791. // Since mappings are sorted, this is guaranteed to find all mappings for
  11792. // the line we are searching for.
  11793. while (mapping &&
  11794. mapping.originalLine === line &&
  11795. mapping.originalColumn == originalColumn) {
  11796. mappings.push({
  11797. line: util.getArg(mapping, 'generatedLine', null),
  11798. column: util.getArg(mapping, 'generatedColumn', null),
  11799. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  11800. });
  11801. mapping = this._originalMappings[++index];
  11802. }
  11803. }
  11804. }
  11805. return mappings;
  11806. };
  11807. exports.SourceMapConsumer = SourceMapConsumer;
  11808. /**
  11809. * A BasicSourceMapConsumer instance represents a parsed source map which we can
  11810. * query for information about the original file positions by giving it a file
  11811. * position in the generated source.
  11812. *
  11813. * The only parameter is the raw source map (either as a JSON string, or
  11814. * already parsed to an object). According to the spec, source maps have the
  11815. * following attributes:
  11816. *
  11817. * - version: Which version of the source map spec this map is following.
  11818. * - sources: An array of URLs to the original source files.
  11819. * - names: An array of identifiers which can be referrenced by individual mappings.
  11820. * - sourceRoot: Optional. The URL root from which all sources are relative.
  11821. * - sourcesContent: Optional. An array of contents of the original source files.
  11822. * - mappings: A string of base64 VLQs which contain the actual mappings.
  11823. * - file: Optional. The generated file this source map is associated with.
  11824. *
  11825. * Here is an example source map, taken from the source map spec[0]:
  11826. *
  11827. * {
  11828. * version : 3,
  11829. * file: "out.js",
  11830. * sourceRoot : "",
  11831. * sources: ["foo.js", "bar.js"],
  11832. * names: ["src", "maps", "are", "fun"],
  11833. * mappings: "AA,AB;;ABCDE;"
  11834. * }
  11835. *
  11836. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
  11837. */
  11838. function BasicSourceMapConsumer(aSourceMap) {
  11839. var sourceMap = aSourceMap;
  11840. if (typeof aSourceMap === 'string') {
  11841. sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
  11842. }
  11843. var version = util.getArg(sourceMap, 'version');
  11844. var sources = util.getArg(sourceMap, 'sources');
  11845. // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
  11846. // requires the array) to play nice here.
  11847. var names = util.getArg(sourceMap, 'names', []);
  11848. var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
  11849. var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
  11850. var mappings = util.getArg(sourceMap, 'mappings');
  11851. var file = util.getArg(sourceMap, 'file', null);
  11852. // Once again, Sass deviates from the spec and supplies the version as a
  11853. // string rather than a number, so we use loose equality checking here.
  11854. if (version != this._version) {
  11855. throw new Error('Unsupported version: ' + version);
  11856. }
  11857. sources = sources
  11858. .map(String)
  11859. // Some source maps produce relative source paths like "./foo.js" instead of
  11860. // "foo.js". Normalize these first so that future comparisons will succeed.
  11861. // See bugzil.la/1090768.
  11862. .map(util.normalize)
  11863. // Always ensure that absolute sources are internally stored relative to
  11864. // the source root, if the source root is absolute. Not doing this would
  11865. // be particularly problematic when the source root is a prefix of the
  11866. // source (valid, but why??). See github issue #199 and bugzil.la/1188982.
  11867. .map(function (source) {
  11868. return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source)
  11869. ? util.relative(sourceRoot, source)
  11870. : source;
  11871. });
  11872. // Pass `true` below to allow duplicate names and sources. While source maps
  11873. // are intended to be compressed and deduplicated, the TypeScript compiler
  11874. // sometimes generates source maps with duplicates in them. See Github issue
  11875. // #72 and bugzil.la/889492.
  11876. this._names = ArraySet.fromArray(names.map(String), true);
  11877. this._sources = ArraySet.fromArray(sources, true);
  11878. this.sourceRoot = sourceRoot;
  11879. this.sourcesContent = sourcesContent;
  11880. this._mappings = mappings;
  11881. this.file = file;
  11882. }
  11883. BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  11884. BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
  11885. /**
  11886. * Create a BasicSourceMapConsumer from a SourceMapGenerator.
  11887. *
  11888. * @param SourceMapGenerator aSourceMap
  11889. * The source map that will be consumed.
  11890. * @returns BasicSourceMapConsumer
  11891. */
  11892. BasicSourceMapConsumer.fromSourceMap =
  11893. function SourceMapConsumer_fromSourceMap(aSourceMap) {
  11894. var smc = Object.create(BasicSourceMapConsumer.prototype);
  11895. var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
  11896. var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
  11897. smc.sourceRoot = aSourceMap._sourceRoot;
  11898. smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
  11899. smc.sourceRoot);
  11900. smc.file = aSourceMap._file;
  11901. // Because we are modifying the entries (by converting string sources and
  11902. // names to indices into the sources and names ArraySets), we have to make
  11903. // a copy of the entry or else bad things happen. Shared mutable state
  11904. // strikes again! See github issue #191.
  11905. var generatedMappings = aSourceMap._mappings.toArray().slice();
  11906. var destGeneratedMappings = smc.__generatedMappings = [];
  11907. var destOriginalMappings = smc.__originalMappings = [];
  11908. for (var i = 0, length = generatedMappings.length; i < length; i++) {
  11909. var srcMapping = generatedMappings[i];
  11910. var destMapping = new Mapping;
  11911. destMapping.generatedLine = srcMapping.generatedLine;
  11912. destMapping.generatedColumn = srcMapping.generatedColumn;
  11913. if (srcMapping.source) {
  11914. destMapping.source = sources.indexOf(srcMapping.source);
  11915. destMapping.originalLine = srcMapping.originalLine;
  11916. destMapping.originalColumn = srcMapping.originalColumn;
  11917. if (srcMapping.name) {
  11918. destMapping.name = names.indexOf(srcMapping.name);
  11919. }
  11920. destOriginalMappings.push(destMapping);
  11921. }
  11922. destGeneratedMappings.push(destMapping);
  11923. }
  11924. quickSort(smc.__originalMappings, util.compareByOriginalPositions);
  11925. return smc;
  11926. };
  11927. /**
  11928. * The version of the source mapping spec that we are consuming.
  11929. */
  11930. BasicSourceMapConsumer.prototype._version = 3;
  11931. /**
  11932. * The list of original sources.
  11933. */
  11934. Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
  11935. get: function () {
  11936. return this._sources.toArray().map(function (s) {
  11937. return this.sourceRoot != null ? util.join(this.sourceRoot, s) : s;
  11938. }, this);
  11939. }
  11940. });
  11941. /**
  11942. * Provide the JIT with a nice shape / hidden class.
  11943. */
  11944. function Mapping() {
  11945. this.generatedLine = 0;
  11946. this.generatedColumn = 0;
  11947. this.source = null;
  11948. this.originalLine = null;
  11949. this.originalColumn = null;
  11950. this.name = null;
  11951. }
  11952. /**
  11953. * Parse the mappings in a string in to a data structure which we can easily
  11954. * query (the ordered arrays in the `this.__generatedMappings` and
  11955. * `this.__originalMappings` properties).
  11956. */
  11957. BasicSourceMapConsumer.prototype._parseMappings =
  11958. function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  11959. var generatedLine = 1;
  11960. var previousGeneratedColumn = 0;
  11961. var previousOriginalLine = 0;
  11962. var previousOriginalColumn = 0;
  11963. var previousSource = 0;
  11964. var previousName = 0;
  11965. var length = aStr.length;
  11966. var index = 0;
  11967. var cachedSegments = {};
  11968. var temp = {};
  11969. var originalMappings = [];
  11970. var generatedMappings = [];
  11971. var mapping, str, segment, end, value;
  11972. while (index < length) {
  11973. if (aStr.charAt(index) === ';') {
  11974. generatedLine++;
  11975. index++;
  11976. previousGeneratedColumn = 0;
  11977. }
  11978. else if (aStr.charAt(index) === ',') {
  11979. index++;
  11980. }
  11981. else {
  11982. mapping = new Mapping();
  11983. mapping.generatedLine = generatedLine;
  11984. // Because each offset is encoded relative to the previous one,
  11985. // many segments often have the same encoding. We can exploit this
  11986. // fact by caching the parsed variable length fields of each segment,
  11987. // allowing us to avoid a second parse if we encounter the same
  11988. // segment again.
  11989. for (end = index; end < length; end++) {
  11990. if (this._charIsMappingSeparator(aStr, end)) {
  11991. break;
  11992. }
  11993. }
  11994. str = aStr.slice(index, end);
  11995. segment = cachedSegments[str];
  11996. if (segment) {
  11997. index += str.length;
  11998. } else {
  11999. segment = [];
  12000. while (index < end) {
  12001. base64VLQ.decode(aStr, index, temp);
  12002. value = temp.value;
  12003. index = temp.rest;
  12004. segment.push(value);
  12005. }
  12006. if (segment.length === 2) {
  12007. throw new Error('Found a source, but no line and column');
  12008. }
  12009. if (segment.length === 3) {
  12010. throw new Error('Found a source and line, but no column');
  12011. }
  12012. cachedSegments[str] = segment;
  12013. }
  12014. // Generated column.
  12015. mapping.generatedColumn = previousGeneratedColumn + segment[0];
  12016. previousGeneratedColumn = mapping.generatedColumn;
  12017. if (segment.length > 1) {
  12018. // Original source.
  12019. mapping.source = previousSource + segment[1];
  12020. previousSource += segment[1];
  12021. // Original line.
  12022. mapping.originalLine = previousOriginalLine + segment[2];
  12023. previousOriginalLine = mapping.originalLine;
  12024. // Lines are stored 0-based
  12025. mapping.originalLine += 1;
  12026. // Original column.
  12027. mapping.originalColumn = previousOriginalColumn + segment[3];
  12028. previousOriginalColumn = mapping.originalColumn;
  12029. if (segment.length > 4) {
  12030. // Original name.
  12031. mapping.name = previousName + segment[4];
  12032. previousName += segment[4];
  12033. }
  12034. }
  12035. generatedMappings.push(mapping);
  12036. if (typeof mapping.originalLine === 'number') {
  12037. originalMappings.push(mapping);
  12038. }
  12039. }
  12040. }
  12041. quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated);
  12042. this.__generatedMappings = generatedMappings;
  12043. quickSort(originalMappings, util.compareByOriginalPositions);
  12044. this.__originalMappings = originalMappings;
  12045. };
  12046. /**
  12047. * Find the mapping that best matches the hypothetical "needle" mapping that
  12048. * we are searching for in the given "haystack" of mappings.
  12049. */
  12050. BasicSourceMapConsumer.prototype._findMapping =
  12051. function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
  12052. aColumnName, aComparator, aBias) {
  12053. // To return the position we are searching for, we must first find the
  12054. // mapping for the given position and then return the opposite position it
  12055. // points to. Because the mappings are sorted, we can use binary search to
  12056. // find the best mapping.
  12057. if (aNeedle[aLineName] <= 0) {
  12058. throw new TypeError('Line must be greater than or equal to 1, got '
  12059. + aNeedle[aLineName]);
  12060. }
  12061. if (aNeedle[aColumnName] < 0) {
  12062. throw new TypeError('Column must be greater than or equal to 0, got '
  12063. + aNeedle[aColumnName]);
  12064. }
  12065. return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
  12066. };
  12067. /**
  12068. * Compute the last column for each generated mapping. The last column is
  12069. * inclusive.
  12070. */
  12071. BasicSourceMapConsumer.prototype.computeColumnSpans =
  12072. function SourceMapConsumer_computeColumnSpans() {
  12073. for (var index = 0; index < this._generatedMappings.length; ++index) {
  12074. var mapping = this._generatedMappings[index];
  12075. // Mappings do not contain a field for the last generated columnt. We
  12076. // can come up with an optimistic estimate, however, by assuming that
  12077. // mappings are contiguous (i.e. given two consecutive mappings, the
  12078. // first mapping ends where the second one starts).
  12079. if (index + 1 < this._generatedMappings.length) {
  12080. var nextMapping = this._generatedMappings[index + 1];
  12081. if (mapping.generatedLine === nextMapping.generatedLine) {
  12082. mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
  12083. continue;
  12084. }
  12085. }
  12086. // The last mapping for each line spans the entire line.
  12087. mapping.lastGeneratedColumn = Infinity;
  12088. }
  12089. };
  12090. /**
  12091. * Returns the original source, line, and column information for the generated
  12092. * source's line and column positions provided. The only argument is an object
  12093. * with the following properties:
  12094. *
  12095. * - line: The line number in the generated source.
  12096. * - column: The column number in the generated source.
  12097. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  12098. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  12099. * closest element that is smaller than or greater than the one we are
  12100. * searching for, respectively, if the exact element cannot be found.
  12101. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  12102. *
  12103. * and an object is returned with the following properties:
  12104. *
  12105. * - source: The original source file, or null.
  12106. * - line: The line number in the original source, or null.
  12107. * - column: The column number in the original source, or null.
  12108. * - name: The original identifier, or null.
  12109. */
  12110. BasicSourceMapConsumer.prototype.originalPositionFor =
  12111. function SourceMapConsumer_originalPositionFor(aArgs) {
  12112. var needle = {
  12113. generatedLine: util.getArg(aArgs, 'line'),
  12114. generatedColumn: util.getArg(aArgs, 'column')
  12115. };
  12116. var index = this._findMapping(
  12117. needle,
  12118. this._generatedMappings,
  12119. "generatedLine",
  12120. "generatedColumn",
  12121. util.compareByGeneratedPositionsDeflated,
  12122. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  12123. );
  12124. if (index >= 0) {
  12125. var mapping = this._generatedMappings[index];
  12126. if (mapping.generatedLine === needle.generatedLine) {
  12127. var source = util.getArg(mapping, 'source', null);
  12128. if (source !== null) {
  12129. source = this._sources.at(source);
  12130. if (this.sourceRoot != null) {
  12131. source = util.join(this.sourceRoot, source);
  12132. }
  12133. }
  12134. var name = util.getArg(mapping, 'name', null);
  12135. if (name !== null) {
  12136. name = this._names.at(name);
  12137. }
  12138. return {
  12139. source: source,
  12140. line: util.getArg(mapping, 'originalLine', null),
  12141. column: util.getArg(mapping, 'originalColumn', null),
  12142. name: name
  12143. };
  12144. }
  12145. }
  12146. return {
  12147. source: null,
  12148. line: null,
  12149. column: null,
  12150. name: null
  12151. };
  12152. };
  12153. /**
  12154. * Return true if we have the source content for every source in the source
  12155. * map, false otherwise.
  12156. */
  12157. BasicSourceMapConsumer.prototype.hasContentsOfAllSources =
  12158. function BasicSourceMapConsumer_hasContentsOfAllSources() {
  12159. if (!this.sourcesContent) {
  12160. return false;
  12161. }
  12162. return this.sourcesContent.length >= this._sources.size() &&
  12163. !this.sourcesContent.some(function (sc) { return sc == null; });
  12164. };
  12165. /**
  12166. * Returns the original source content. The only argument is the url of the
  12167. * original source file. Returns null if no original source content is
  12168. * available.
  12169. */
  12170. BasicSourceMapConsumer.prototype.sourceContentFor =
  12171. function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  12172. if (!this.sourcesContent) {
  12173. return null;
  12174. }
  12175. if (this.sourceRoot != null) {
  12176. aSource = util.relative(this.sourceRoot, aSource);
  12177. }
  12178. if (this._sources.has(aSource)) {
  12179. return this.sourcesContent[this._sources.indexOf(aSource)];
  12180. }
  12181. var url;
  12182. if (this.sourceRoot != null
  12183. && (url = util.urlParse(this.sourceRoot))) {
  12184. // XXX: file:// URIs and absolute paths lead to unexpected behavior for
  12185. // many users. We can help them out when they expect file:// URIs to
  12186. // behave like it would if they were running a local HTTP server. See
  12187. // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
  12188. var fileUriAbsPath = aSource.replace(/^file:\/\//, "");
  12189. if (url.scheme == "file"
  12190. && this._sources.has(fileUriAbsPath)) {
  12191. return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
  12192. }
  12193. if ((!url.path || url.path == "/")
  12194. && this._sources.has("/" + aSource)) {
  12195. return this.sourcesContent[this._sources.indexOf("/" + aSource)];
  12196. }
  12197. }
  12198. // This function is used recursively from
  12199. // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
  12200. // don't want to throw if we can't find the source - we just want to
  12201. // return null, so we provide a flag to exit gracefully.
  12202. if (nullOnMissing) {
  12203. return null;
  12204. }
  12205. else {
  12206. throw new Error('"' + aSource + '" is not in the SourceMap.');
  12207. }
  12208. };
  12209. /**
  12210. * Returns the generated line and column information for the original source,
  12211. * line, and column positions provided. The only argument is an object with
  12212. * the following properties:
  12213. *
  12214. * - source: The filename of the original source.
  12215. * - line: The line number in the original source.
  12216. * - column: The column number in the original source.
  12217. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  12218. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  12219. * closest element that is smaller than or greater than the one we are
  12220. * searching for, respectively, if the exact element cannot be found.
  12221. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  12222. *
  12223. * and an object is returned with the following properties:
  12224. *
  12225. * - line: The line number in the generated source, or null.
  12226. * - column: The column number in the generated source, or null.
  12227. */
  12228. BasicSourceMapConsumer.prototype.generatedPositionFor =
  12229. function SourceMapConsumer_generatedPositionFor(aArgs) {
  12230. var source = util.getArg(aArgs, 'source');
  12231. if (this.sourceRoot != null) {
  12232. source = util.relative(this.sourceRoot, source);
  12233. }
  12234. if (!this._sources.has(source)) {
  12235. return {
  12236. line: null,
  12237. column: null,
  12238. lastColumn: null
  12239. };
  12240. }
  12241. source = this._sources.indexOf(source);
  12242. var needle = {
  12243. source: source,
  12244. originalLine: util.getArg(aArgs, 'line'),
  12245. originalColumn: util.getArg(aArgs, 'column')
  12246. };
  12247. var index = this._findMapping(
  12248. needle,
  12249. this._originalMappings,
  12250. "originalLine",
  12251. "originalColumn",
  12252. util.compareByOriginalPositions,
  12253. util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
  12254. );
  12255. if (index >= 0) {
  12256. var mapping = this._originalMappings[index];
  12257. if (mapping.source === needle.source) {
  12258. return {
  12259. line: util.getArg(mapping, 'generatedLine', null),
  12260. column: util.getArg(mapping, 'generatedColumn', null),
  12261. lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null)
  12262. };
  12263. }
  12264. }
  12265. return {
  12266. line: null,
  12267. column: null,
  12268. lastColumn: null
  12269. };
  12270. };
  12271. exports.BasicSourceMapConsumer = BasicSourceMapConsumer;
  12272. /**
  12273. * An IndexedSourceMapConsumer instance represents a parsed source map which
  12274. * we can query for information. It differs from BasicSourceMapConsumer in
  12275. * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
  12276. * input.
  12277. *
  12278. * The only parameter is a raw source map (either as a JSON string, or already
  12279. * parsed to an object). According to the spec for indexed source maps, they
  12280. * have the following attributes:
  12281. *
  12282. * - version: Which version of the source map spec this map is following.
  12283. * - file: Optional. The generated file this source map is associated with.
  12284. * - sections: A list of section definitions.
  12285. *
  12286. * Each value under the "sections" field has two fields:
  12287. * - offset: The offset into the original specified at which this section
  12288. * begins to apply, defined as an object with a "line" and "column"
  12289. * field.
  12290. * - map: A source map definition. This source map could also be indexed,
  12291. * but doesn't have to be.
  12292. *
  12293. * Instead of the "map" field, it's also possible to have a "url" field
  12294. * specifying a URL to retrieve a source map from, but that's currently
  12295. * unsupported.
  12296. *
  12297. * Here's an example source map, taken from the source map spec[0], but
  12298. * modified to omit a section which uses the "url" field.
  12299. *
  12300. * {
  12301. * version : 3,
  12302. * file: "app.js",
  12303. * sections: [{
  12304. * offset: {line:100, column:10},
  12305. * map: {
  12306. * version : 3,
  12307. * file: "section.js",
  12308. * sources: ["foo.js", "bar.js"],
  12309. * names: ["src", "maps", "are", "fun"],
  12310. * mappings: "AAAA,E;;ABCDE;"
  12311. * }
  12312. * }],
  12313. * }
  12314. *
  12315. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
  12316. */
  12317. function IndexedSourceMapConsumer(aSourceMap) {
  12318. var sourceMap = aSourceMap;
  12319. if (typeof aSourceMap === 'string') {
  12320. sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
  12321. }
  12322. var version = util.getArg(sourceMap, 'version');
  12323. var sections = util.getArg(sourceMap, 'sections');
  12324. if (version != this._version) {
  12325. throw new Error('Unsupported version: ' + version);
  12326. }
  12327. this._sources = new ArraySet();
  12328. this._names = new ArraySet();
  12329. var lastOffset = {
  12330. line: -1,
  12331. column: 0
  12332. };
  12333. this._sections = sections.map(function (s) {
  12334. if (s.url) {
  12335. // The url field will require support for asynchronicity.
  12336. // See https://github.com/mozilla/source-map/issues/16
  12337. throw new Error('Support for url field in sections not implemented.');
  12338. }
  12339. var offset = util.getArg(s, 'offset');
  12340. var offsetLine = util.getArg(offset, 'line');
  12341. var offsetColumn = util.getArg(offset, 'column');
  12342. if (offsetLine < lastOffset.line ||
  12343. (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
  12344. throw new Error('Section offsets must be ordered and non-overlapping.');
  12345. }
  12346. lastOffset = offset;
  12347. return {
  12348. generatedOffset: {
  12349. // The offset fields are 0-based, but we use 1-based indices when
  12350. // encoding/decoding from VLQ.
  12351. generatedLine: offsetLine + 1,
  12352. generatedColumn: offsetColumn + 1
  12353. },
  12354. consumer: new SourceMapConsumer(util.getArg(s, 'map'))
  12355. }
  12356. });
  12357. }
  12358. IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
  12359. IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;
  12360. /**
  12361. * The version of the source mapping spec that we are consuming.
  12362. */
  12363. IndexedSourceMapConsumer.prototype._version = 3;
  12364. /**
  12365. * The list of original sources.
  12366. */
  12367. Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
  12368. get: function () {
  12369. var sources = [];
  12370. for (var i = 0; i < this._sections.length; i++) {
  12371. for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
  12372. sources.push(this._sections[i].consumer.sources[j]);
  12373. }
  12374. }
  12375. return sources;
  12376. }
  12377. });
  12378. /**
  12379. * Returns the original source, line, and column information for the generated
  12380. * source's line and column positions provided. The only argument is an object
  12381. * with the following properties:
  12382. *
  12383. * - line: The line number in the generated source.
  12384. * - column: The column number in the generated source.
  12385. *
  12386. * and an object is returned with the following properties:
  12387. *
  12388. * - source: The original source file, or null.
  12389. * - line: The line number in the original source, or null.
  12390. * - column: The column number in the original source, or null.
  12391. * - name: The original identifier, or null.
  12392. */
  12393. IndexedSourceMapConsumer.prototype.originalPositionFor =
  12394. function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
  12395. var needle = {
  12396. generatedLine: util.getArg(aArgs, 'line'),
  12397. generatedColumn: util.getArg(aArgs, 'column')
  12398. };
  12399. // Find the section containing the generated position we're trying to map
  12400. // to an original position.
  12401. var sectionIndex = binarySearch.search(needle, this._sections,
  12402. function(needle, section) {
  12403. var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
  12404. if (cmp) {
  12405. return cmp;
  12406. }
  12407. return (needle.generatedColumn -
  12408. section.generatedOffset.generatedColumn);
  12409. });
  12410. var section = this._sections[sectionIndex];
  12411. if (!section) {
  12412. return {
  12413. source: null,
  12414. line: null,
  12415. column: null,
  12416. name: null
  12417. };
  12418. }
  12419. return section.consumer.originalPositionFor({
  12420. line: needle.generatedLine -
  12421. (section.generatedOffset.generatedLine - 1),
  12422. column: needle.generatedColumn -
  12423. (section.generatedOffset.generatedLine === needle.generatedLine
  12424. ? section.generatedOffset.generatedColumn - 1
  12425. : 0),
  12426. bias: aArgs.bias
  12427. });
  12428. };
  12429. /**
  12430. * Return true if we have the source content for every source in the source
  12431. * map, false otherwise.
  12432. */
  12433. IndexedSourceMapConsumer.prototype.hasContentsOfAllSources =
  12434. function IndexedSourceMapConsumer_hasContentsOfAllSources() {
  12435. return this._sections.every(function (s) {
  12436. return s.consumer.hasContentsOfAllSources();
  12437. });
  12438. };
  12439. /**
  12440. * Returns the original source content. The only argument is the url of the
  12441. * original source file. Returns null if no original source content is
  12442. * available.
  12443. */
  12444. IndexedSourceMapConsumer.prototype.sourceContentFor =
  12445. function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
  12446. for (var i = 0; i < this._sections.length; i++) {
  12447. var section = this._sections[i];
  12448. var content = section.consumer.sourceContentFor(aSource, true);
  12449. if (content) {
  12450. return content;
  12451. }
  12452. }
  12453. if (nullOnMissing) {
  12454. return null;
  12455. }
  12456. else {
  12457. throw new Error('"' + aSource + '" is not in the SourceMap.');
  12458. }
  12459. };
  12460. /**
  12461. * Returns the generated line and column information for the original source,
  12462. * line, and column positions provided. The only argument is an object with
  12463. * the following properties:
  12464. *
  12465. * - source: The filename of the original source.
  12466. * - line: The line number in the original source.
  12467. * - column: The column number in the original source.
  12468. *
  12469. * and an object is returned with the following properties:
  12470. *
  12471. * - line: The line number in the generated source, or null.
  12472. * - column: The column number in the generated source, or null.
  12473. */
  12474. IndexedSourceMapConsumer.prototype.generatedPositionFor =
  12475. function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
  12476. for (var i = 0; i < this._sections.length; i++) {
  12477. var section = this._sections[i];
  12478. // Only consider this section if the requested source is in the list of
  12479. // sources of the consumer.
  12480. if (section.consumer.sources.indexOf(util.getArg(aArgs, 'source')) === -1) {
  12481. continue;
  12482. }
  12483. var generatedPosition = section.consumer.generatedPositionFor(aArgs);
  12484. if (generatedPosition) {
  12485. var ret = {
  12486. line: generatedPosition.line +
  12487. (section.generatedOffset.generatedLine - 1),
  12488. column: generatedPosition.column +
  12489. (section.generatedOffset.generatedLine === generatedPosition.line
  12490. ? section.generatedOffset.generatedColumn - 1
  12491. : 0)
  12492. };
  12493. return ret;
  12494. }
  12495. }
  12496. return {
  12497. line: null,
  12498. column: null
  12499. };
  12500. };
  12501. /**
  12502. * Parse the mappings in a string in to a data structure which we can easily
  12503. * query (the ordered arrays in the `this.__generatedMappings` and
  12504. * `this.__originalMappings` properties).
  12505. */
  12506. IndexedSourceMapConsumer.prototype._parseMappings =
  12507. function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
  12508. this.__generatedMappings = [];
  12509. this.__originalMappings = [];
  12510. for (var i = 0; i < this._sections.length; i++) {
  12511. var section = this._sections[i];
  12512. var sectionMappings = section.consumer._generatedMappings;
  12513. for (var j = 0; j < sectionMappings.length; j++) {
  12514. var mapping = sectionMappings[j];
  12515. var source = section.consumer._sources.at(mapping.source);
  12516. if (section.consumer.sourceRoot !== null) {
  12517. source = util.join(section.consumer.sourceRoot, source);
  12518. }
  12519. this._sources.add(source);
  12520. source = this._sources.indexOf(source);
  12521. var name = section.consumer._names.at(mapping.name);
  12522. this._names.add(name);
  12523. name = this._names.indexOf(name);
  12524. // The mappings coming from the consumer for the section have
  12525. // generated positions relative to the start of the section, so we
  12526. // need to offset them to be relative to the start of the concatenated
  12527. // generated file.
  12528. var adjustedMapping = {
  12529. source: source,
  12530. generatedLine: mapping.generatedLine +
  12531. (section.generatedOffset.generatedLine - 1),
  12532. generatedColumn: mapping.generatedColumn +
  12533. (section.generatedOffset.generatedLine === mapping.generatedLine
  12534. ? section.generatedOffset.generatedColumn - 1
  12535. : 0),
  12536. originalLine: mapping.originalLine,
  12537. originalColumn: mapping.originalColumn,
  12538. name: name
  12539. };
  12540. this.__generatedMappings.push(adjustedMapping);
  12541. if (typeof adjustedMapping.originalLine === 'number') {
  12542. this.__originalMappings.push(adjustedMapping);
  12543. }
  12544. }
  12545. }
  12546. quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated);
  12547. quickSort(this.__originalMappings, util.compareByOriginalPositions);
  12548. };
  12549. exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer;
  12550. /***/ },
  12551. /* 8 */
  12552. /***/ function(module, exports) {
  12553. /* -*- Mode: js; js-indent-level: 2; -*- */
  12554. /*
  12555. * Copyright 2011 Mozilla Foundation and contributors
  12556. * Licensed under the New BSD license. See LICENSE or:
  12557. * http://opensource.org/licenses/BSD-3-Clause
  12558. */
  12559. exports.GREATEST_LOWER_BOUND = 1;
  12560. exports.LEAST_UPPER_BOUND = 2;
  12561. /**
  12562. * Recursive implementation of binary search.
  12563. *
  12564. * @param aLow Indices here and lower do not contain the needle.
  12565. * @param aHigh Indices here and higher do not contain the needle.
  12566. * @param aNeedle The element being searched for.
  12567. * @param aHaystack The non-empty array being searched.
  12568. * @param aCompare Function which takes two elements and returns -1, 0, or 1.
  12569. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  12570. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  12571. * closest element that is smaller than or greater than the one we are
  12572. * searching for, respectively, if the exact element cannot be found.
  12573. */
  12574. function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
  12575. // This function terminates when one of the following is true:
  12576. //
  12577. // 1. We find the exact element we are looking for.
  12578. //
  12579. // 2. We did not find the exact element, but we can return the index of
  12580. // the next-closest element.
  12581. //
  12582. // 3. We did not find the exact element, and there is no next-closest
  12583. // element than the one we are searching for, so we return -1.
  12584. var mid = Math.floor((aHigh - aLow) / 2) + aLow;
  12585. var cmp = aCompare(aNeedle, aHaystack[mid], true);
  12586. if (cmp === 0) {
  12587. // Found the element we are looking for.
  12588. return mid;
  12589. }
  12590. else if (cmp > 0) {
  12591. // Our needle is greater than aHaystack[mid].
  12592. if (aHigh - mid > 1) {
  12593. // The element is in the upper half.
  12594. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
  12595. }
  12596. // The exact needle element was not found in this haystack. Determine if
  12597. // we are in termination case (3) or (2) and return the appropriate thing.
  12598. if (aBias == exports.LEAST_UPPER_BOUND) {
  12599. return aHigh < aHaystack.length ? aHigh : -1;
  12600. } else {
  12601. return mid;
  12602. }
  12603. }
  12604. else {
  12605. // Our needle is less than aHaystack[mid].
  12606. if (mid - aLow > 1) {
  12607. // The element is in the lower half.
  12608. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
  12609. }
  12610. // we are in termination case (3) or (2) and return the appropriate thing.
  12611. if (aBias == exports.LEAST_UPPER_BOUND) {
  12612. return mid;
  12613. } else {
  12614. return aLow < 0 ? -1 : aLow;
  12615. }
  12616. }
  12617. }
  12618. /**
  12619. * This is an implementation of binary search which will always try and return
  12620. * the index of the closest element if there is no exact hit. This is because
  12621. * mappings between original and generated line/col pairs are single points,
  12622. * and there is an implicit region between each of them, so a miss just means
  12623. * that you aren't on the very start of a region.
  12624. *
  12625. * @param aNeedle The element you are looking for.
  12626. * @param aHaystack The array that is being searched.
  12627. * @param aCompare A function which takes the needle and an element in the
  12628. * array and returns -1, 0, or 1 depending on whether the needle is less
  12629. * than, equal to, or greater than the element, respectively.
  12630. * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
  12631. * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
  12632. * closest element that is smaller than or greater than the one we are
  12633. * searching for, respectively, if the exact element cannot be found.
  12634. * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
  12635. */
  12636. exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
  12637. if (aHaystack.length === 0) {
  12638. return -1;
  12639. }
  12640. var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
  12641. aCompare, aBias || exports.GREATEST_LOWER_BOUND);
  12642. if (index < 0) {
  12643. return -1;
  12644. }
  12645. // We have found either the exact element, or the next-closest element than
  12646. // the one we are searching for. However, there may be more than one such
  12647. // element. Make sure we always return the smallest of these.
  12648. while (index - 1 >= 0) {
  12649. if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
  12650. break;
  12651. }
  12652. --index;
  12653. }
  12654. return index;
  12655. };
  12656. /***/ },
  12657. /* 9 */
  12658. /***/ function(module, exports) {
  12659. /* -*- Mode: js; js-indent-level: 2; -*- */
  12660. /*
  12661. * Copyright 2011 Mozilla Foundation and contributors
  12662. * Licensed under the New BSD license. See LICENSE or:
  12663. * http://opensource.org/licenses/BSD-3-Clause
  12664. */
  12665. // It turns out that some (most?) JavaScript engines don't self-host
  12666. // `Array.prototype.sort`. This makes sense because C++ will likely remain
  12667. // faster than JS when doing raw CPU-intensive sorting. However, when using a
  12668. // custom comparator function, calling back and forth between the VM's C++ and
  12669. // JIT'd JS is rather slow *and* loses JIT type information, resulting in
  12670. // worse generated code for the comparator function than would be optimal. In
  12671. // fact, when sorting with a comparator, these costs outweigh the benefits of
  12672. // sorting in C++. By using our own JS-implemented Quick Sort (below), we get
  12673. // a ~3500ms mean speed-up in `bench/bench.html`.
  12674. /**
  12675. * Swap the elements indexed by `x` and `y` in the array `ary`.
  12676. *
  12677. * @param {Array} ary
  12678. * The array.
  12679. * @param {Number} x
  12680. * The index of the first item.
  12681. * @param {Number} y
  12682. * The index of the second item.
  12683. */
  12684. function swap(ary, x, y) {
  12685. var temp = ary[x];
  12686. ary[x] = ary[y];
  12687. ary[y] = temp;
  12688. }
  12689. /**
  12690. * Returns a random integer within the range `low .. high` inclusive.
  12691. *
  12692. * @param {Number} low
  12693. * The lower bound on the range.
  12694. * @param {Number} high
  12695. * The upper bound on the range.
  12696. */
  12697. function randomIntInRange(low, high) {
  12698. return Math.round(low + (Math.random() * (high - low)));
  12699. }
  12700. /**
  12701. * The Quick Sort algorithm.
  12702. *
  12703. * @param {Array} ary
  12704. * An array to sort.
  12705. * @param {function} comparator
  12706. * Function to use to compare two items.
  12707. * @param {Number} p
  12708. * Start index of the array
  12709. * @param {Number} r
  12710. * End index of the array
  12711. */
  12712. function doQuickSort(ary, comparator, p, r) {
  12713. // If our lower bound is less than our upper bound, we (1) partition the
  12714. // array into two pieces and (2) recurse on each half. If it is not, this is
  12715. // the empty array and our base case.
  12716. if (p < r) {
  12717. // (1) Partitioning.
  12718. //
  12719. // The partitioning chooses a pivot between `p` and `r` and moves all
  12720. // elements that are less than or equal to the pivot to the before it, and
  12721. // all the elements that are greater than it after it. The effect is that
  12722. // once partition is done, the pivot is in the exact place it will be when
  12723. // the array is put in sorted order, and it will not need to be moved
  12724. // again. This runs in O(n) time.
  12725. // Always choose a random pivot so that an input array which is reverse
  12726. // sorted does not cause O(n^2) running time.
  12727. var pivotIndex = randomIntInRange(p, r);
  12728. var i = p - 1;
  12729. swap(ary, pivotIndex, r);
  12730. var pivot = ary[r];
  12731. // Immediately after `j` is incremented in this loop, the following hold
  12732. // true:
  12733. //
  12734. // * Every element in `ary[p .. i]` is less than or equal to the pivot.
  12735. //
  12736. // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
  12737. for (var j = p; j < r; j++) {
  12738. if (comparator(ary[j], pivot) <= 0) {
  12739. i += 1;
  12740. swap(ary, i, j);
  12741. }
  12742. }
  12743. swap(ary, i + 1, j);
  12744. var q = i + 1;
  12745. // (2) Recurse on each half.
  12746. doQuickSort(ary, comparator, p, q - 1);
  12747. doQuickSort(ary, comparator, q + 1, r);
  12748. }
  12749. }
  12750. /**
  12751. * Sort the given array in-place with the given comparator function.
  12752. *
  12753. * @param {Array} ary
  12754. * An array to sort.
  12755. * @param {function} comparator
  12756. * Function to use to compare two items.
  12757. */
  12758. exports.quickSort = function (ary, comparator) {
  12759. doQuickSort(ary, comparator, 0, ary.length - 1);
  12760. };
  12761. /***/ },
  12762. /* 10 */
  12763. /***/ function(module, exports, __webpack_require__) {
  12764. /* -*- Mode: js; js-indent-level: 2; -*- */
  12765. /*
  12766. * Copyright 2011 Mozilla Foundation and contributors
  12767. * Licensed under the New BSD license. See LICENSE or:
  12768. * http://opensource.org/licenses/BSD-3-Clause
  12769. */
  12770. var SourceMapGenerator = __webpack_require__(1).SourceMapGenerator;
  12771. var util = __webpack_require__(4);
  12772. // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
  12773. // operating systems these days (capturing the result).
  12774. var REGEX_NEWLINE = /(\r?\n)/;
  12775. // Newline character code for charCodeAt() comparisons
  12776. var NEWLINE_CODE = 10;
  12777. // Private symbol for identifying `SourceNode`s when multiple versions of
  12778. // the source-map library are loaded. This MUST NOT CHANGE across
  12779. // versions!
  12780. var isSourceNode = "$$$isSourceNode$$$";
  12781. /**
  12782. * SourceNodes provide a way to abstract over interpolating/concatenating
  12783. * snippets of generated JavaScript source code while maintaining the line and
  12784. * column information associated with the original source code.
  12785. *
  12786. * @param aLine The original line number.
  12787. * @param aColumn The original column number.
  12788. * @param aSource The original source's filename.
  12789. * @param aChunks Optional. An array of strings which are snippets of
  12790. * generated JS, or other SourceNodes.
  12791. * @param aName The original identifier.
  12792. */
  12793. function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
  12794. this.children = [];
  12795. this.sourceContents = {};
  12796. this.line = aLine == null ? null : aLine;
  12797. this.column = aColumn == null ? null : aColumn;
  12798. this.source = aSource == null ? null : aSource;
  12799. this.name = aName == null ? null : aName;
  12800. this[isSourceNode] = true;
  12801. if (aChunks != null) this.add(aChunks);
  12802. }
  12803. /**
  12804. * Creates a SourceNode from generated code and a SourceMapConsumer.
  12805. *
  12806. * @param aGeneratedCode The generated code
  12807. * @param aSourceMapConsumer The SourceMap for the generated code
  12808. * @param aRelativePath Optional. The path that relative sources in the
  12809. * SourceMapConsumer should be relative to.
  12810. */
  12811. SourceNode.fromStringWithSourceMap =
  12812. function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
  12813. // The SourceNode we want to fill with the generated code
  12814. // and the SourceMap
  12815. var node = new SourceNode();
  12816. // All even indices of this array are one line of the generated code,
  12817. // while all odd indices are the newlines between two adjacent lines
  12818. // (since `REGEX_NEWLINE` captures its match).
  12819. // Processed fragments are removed from this array, by calling `shiftNextLine`.
  12820. var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
  12821. var shiftNextLine = function() {
  12822. var lineContents = remainingLines.shift();
  12823. // The last line of a file might not have a newline.
  12824. var newLine = remainingLines.shift() || "";
  12825. return lineContents + newLine;
  12826. };
  12827. // We need to remember the position of "remainingLines"
  12828. var lastGeneratedLine = 1, lastGeneratedColumn = 0;
  12829. // The generate SourceNodes we need a code range.
  12830. // To extract it current and last mapping is used.
  12831. // Here we store the last mapping.
  12832. var lastMapping = null;
  12833. aSourceMapConsumer.eachMapping(function (mapping) {
  12834. if (lastMapping !== null) {
  12835. // We add the code from "lastMapping" to "mapping":
  12836. // First check if there is a new line in between.
  12837. if (lastGeneratedLine < mapping.generatedLine) {
  12838. // Associate first line with "lastMapping"
  12839. addMappingWithCode(lastMapping, shiftNextLine());
  12840. lastGeneratedLine++;
  12841. lastGeneratedColumn = 0;
  12842. // The remaining code is added without mapping
  12843. } else {
  12844. // There is no new line in between.
  12845. // Associate the code between "lastGeneratedColumn" and
  12846. // "mapping.generatedColumn" with "lastMapping"
  12847. var nextLine = remainingLines[0];
  12848. var code = nextLine.substr(0, mapping.generatedColumn -
  12849. lastGeneratedColumn);
  12850. remainingLines[0] = nextLine.substr(mapping.generatedColumn -
  12851. lastGeneratedColumn);
  12852. lastGeneratedColumn = mapping.generatedColumn;
  12853. addMappingWithCode(lastMapping, code);
  12854. // No more remaining code, continue
  12855. lastMapping = mapping;
  12856. return;
  12857. }
  12858. }
  12859. // We add the generated code until the first mapping
  12860. // to the SourceNode without any mapping.
  12861. // Each line is added as separate string.
  12862. while (lastGeneratedLine < mapping.generatedLine) {
  12863. node.add(shiftNextLine());
  12864. lastGeneratedLine++;
  12865. }
  12866. if (lastGeneratedColumn < mapping.generatedColumn) {
  12867. var nextLine = remainingLines[0];
  12868. node.add(nextLine.substr(0, mapping.generatedColumn));
  12869. remainingLines[0] = nextLine.substr(mapping.generatedColumn);
  12870. lastGeneratedColumn = mapping.generatedColumn;
  12871. }
  12872. lastMapping = mapping;
  12873. }, this);
  12874. // We have processed all mappings.
  12875. if (remainingLines.length > 0) {
  12876. if (lastMapping) {
  12877. // Associate the remaining code in the current line with "lastMapping"
  12878. addMappingWithCode(lastMapping, shiftNextLine());
  12879. }
  12880. // and add the remaining lines without any mapping
  12881. node.add(remainingLines.join(""));
  12882. }
  12883. // Copy sourcesContent into SourceNode
  12884. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  12885. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  12886. if (content != null) {
  12887. if (aRelativePath != null) {
  12888. sourceFile = util.join(aRelativePath, sourceFile);
  12889. }
  12890. node.setSourceContent(sourceFile, content);
  12891. }
  12892. });
  12893. return node;
  12894. function addMappingWithCode(mapping, code) {
  12895. if (mapping === null || mapping.source === undefined) {
  12896. node.add(code);
  12897. } else {
  12898. var source = aRelativePath
  12899. ? util.join(aRelativePath, mapping.source)
  12900. : mapping.source;
  12901. node.add(new SourceNode(mapping.originalLine,
  12902. mapping.originalColumn,
  12903. source,
  12904. code,
  12905. mapping.name));
  12906. }
  12907. }
  12908. };
  12909. /**
  12910. * Add a chunk of generated JS to this source node.
  12911. *
  12912. * @param aChunk A string snippet of generated JS code, another instance of
  12913. * SourceNode, or an array where each member is one of those things.
  12914. */
  12915. SourceNode.prototype.add = function SourceNode_add(aChunk) {
  12916. if (Array.isArray(aChunk)) {
  12917. aChunk.forEach(function (chunk) {
  12918. this.add(chunk);
  12919. }, this);
  12920. }
  12921. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  12922. if (aChunk) {
  12923. this.children.push(aChunk);
  12924. }
  12925. }
  12926. else {
  12927. throw new TypeError(
  12928. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  12929. );
  12930. }
  12931. return this;
  12932. };
  12933. /**
  12934. * Add a chunk of generated JS to the beginning of this source node.
  12935. *
  12936. * @param aChunk A string snippet of generated JS code, another instance of
  12937. * SourceNode, or an array where each member is one of those things.
  12938. */
  12939. SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
  12940. if (Array.isArray(aChunk)) {
  12941. for (var i = aChunk.length-1; i >= 0; i--) {
  12942. this.prepend(aChunk[i]);
  12943. }
  12944. }
  12945. else if (aChunk[isSourceNode] || typeof aChunk === "string") {
  12946. this.children.unshift(aChunk);
  12947. }
  12948. else {
  12949. throw new TypeError(
  12950. "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
  12951. );
  12952. }
  12953. return this;
  12954. };
  12955. /**
  12956. * Walk over the tree of JS snippets in this node and its children. The
  12957. * walking function is called once for each snippet of JS and is passed that
  12958. * snippet and the its original associated source's line/column location.
  12959. *
  12960. * @param aFn The traversal function.
  12961. */
  12962. SourceNode.prototype.walk = function SourceNode_walk(aFn) {
  12963. var chunk;
  12964. for (var i = 0, len = this.children.length; i < len; i++) {
  12965. chunk = this.children[i];
  12966. if (chunk[isSourceNode]) {
  12967. chunk.walk(aFn);
  12968. }
  12969. else {
  12970. if (chunk !== '') {
  12971. aFn(chunk, { source: this.source,
  12972. line: this.line,
  12973. column: this.column,
  12974. name: this.name });
  12975. }
  12976. }
  12977. }
  12978. };
  12979. /**
  12980. * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
  12981. * each of `this.children`.
  12982. *
  12983. * @param aSep The separator.
  12984. */
  12985. SourceNode.prototype.join = function SourceNode_join(aSep) {
  12986. var newChildren;
  12987. var i;
  12988. var len = this.children.length;
  12989. if (len > 0) {
  12990. newChildren = [];
  12991. for (i = 0; i < len-1; i++) {
  12992. newChildren.push(this.children[i]);
  12993. newChildren.push(aSep);
  12994. }
  12995. newChildren.push(this.children[i]);
  12996. this.children = newChildren;
  12997. }
  12998. return this;
  12999. };
  13000. /**
  13001. * Call String.prototype.replace on the very right-most source snippet. Useful
  13002. * for trimming whitespace from the end of a source node, etc.
  13003. *
  13004. * @param aPattern The pattern to replace.
  13005. * @param aReplacement The thing to replace the pattern with.
  13006. */
  13007. SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
  13008. var lastChild = this.children[this.children.length - 1];
  13009. if (lastChild[isSourceNode]) {
  13010. lastChild.replaceRight(aPattern, aReplacement);
  13011. }
  13012. else if (typeof lastChild === 'string') {
  13013. this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
  13014. }
  13015. else {
  13016. this.children.push(''.replace(aPattern, aReplacement));
  13017. }
  13018. return this;
  13019. };
  13020. /**
  13021. * Set the source content for a source file. This will be added to the SourceMapGenerator
  13022. * in the sourcesContent field.
  13023. *
  13024. * @param aSourceFile The filename of the source file
  13025. * @param aSourceContent The content of the source file
  13026. */
  13027. SourceNode.prototype.setSourceContent =
  13028. function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
  13029. this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
  13030. };
  13031. /**
  13032. * Walk over the tree of SourceNodes. The walking function is called for each
  13033. * source file content and is passed the filename and source content.
  13034. *
  13035. * @param aFn The traversal function.
  13036. */
  13037. SourceNode.prototype.walkSourceContents =
  13038. function SourceNode_walkSourceContents(aFn) {
  13039. for (var i = 0, len = this.children.length; i < len; i++) {
  13040. if (this.children[i][isSourceNode]) {
  13041. this.children[i].walkSourceContents(aFn);
  13042. }
  13043. }
  13044. var sources = Object.keys(this.sourceContents);
  13045. for (var i = 0, len = sources.length; i < len; i++) {
  13046. aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
  13047. }
  13048. };
  13049. /**
  13050. * Return the string representation of this source node. Walks over the tree
  13051. * and concatenates all the various snippets together to one string.
  13052. */
  13053. SourceNode.prototype.toString = function SourceNode_toString() {
  13054. var str = "";
  13055. this.walk(function (chunk) {
  13056. str += chunk;
  13057. });
  13058. return str;
  13059. };
  13060. /**
  13061. * Returns the string representation of this source node along with a source
  13062. * map.
  13063. */
  13064. SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
  13065. var generated = {
  13066. code: "",
  13067. line: 1,
  13068. column: 0
  13069. };
  13070. var map = new SourceMapGenerator(aArgs);
  13071. var sourceMappingActive = false;
  13072. var lastOriginalSource = null;
  13073. var lastOriginalLine = null;
  13074. var lastOriginalColumn = null;
  13075. var lastOriginalName = null;
  13076. this.walk(function (chunk, original) {
  13077. generated.code += chunk;
  13078. if (original.source !== null
  13079. && original.line !== null
  13080. && original.column !== null) {
  13081. if(lastOriginalSource !== original.source
  13082. || lastOriginalLine !== original.line
  13083. || lastOriginalColumn !== original.column
  13084. || lastOriginalName !== original.name) {
  13085. map.addMapping({
  13086. source: original.source,
  13087. original: {
  13088. line: original.line,
  13089. column: original.column
  13090. },
  13091. generated: {
  13092. line: generated.line,
  13093. column: generated.column
  13094. },
  13095. name: original.name
  13096. });
  13097. }
  13098. lastOriginalSource = original.source;
  13099. lastOriginalLine = original.line;
  13100. lastOriginalColumn = original.column;
  13101. lastOriginalName = original.name;
  13102. sourceMappingActive = true;
  13103. } else if (sourceMappingActive) {
  13104. map.addMapping({
  13105. generated: {
  13106. line: generated.line,
  13107. column: generated.column
  13108. }
  13109. });
  13110. lastOriginalSource = null;
  13111. sourceMappingActive = false;
  13112. }
  13113. for (var idx = 0, length = chunk.length; idx < length; idx++) {
  13114. if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
  13115. generated.line++;
  13116. generated.column = 0;
  13117. // Mappings end at eol
  13118. if (idx + 1 === length) {
  13119. lastOriginalSource = null;
  13120. sourceMappingActive = false;
  13121. } else if (sourceMappingActive) {
  13122. map.addMapping({
  13123. source: original.source,
  13124. original: {
  13125. line: original.line,
  13126. column: original.column
  13127. },
  13128. generated: {
  13129. line: generated.line,
  13130. column: generated.column
  13131. },
  13132. name: original.name
  13133. });
  13134. }
  13135. } else {
  13136. generated.column++;
  13137. }
  13138. }
  13139. });
  13140. this.walkSourceContents(function (sourceFile, sourceContent) {
  13141. map.setSourceContent(sourceFile, sourceContent);
  13142. });
  13143. return { code: generated.code, map: map };
  13144. };
  13145. exports.SourceNode = SourceNode;
  13146. /***/ }
  13147. /******/ ])
  13148. });
  13149. ;//Distributed under the BSD license:
  13150. //Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  13151. define('uglifyjs', ['exports', 'source-map', 'logger', 'env!env/file'], function (exports, MOZ_SourceMap, logger, rjsFile) {
  13152. /***********************************************************************
  13153. A JavaScript tokenizer / parser / beautifier / compressor.
  13154. https://github.com/mishoo/UglifyJS2
  13155. -------------------------------- (C) ---------------------------------
  13156. Author: Mihai Bazon
  13157. <mihai.bazon@gmail.com>
  13158. http://mihai.bazon.net/blog
  13159. Distributed under the BSD license:
  13160. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  13161. Redistribution and use in source and binary forms, with or without
  13162. modification, are permitted provided that the following conditions
  13163. are met:
  13164. * Redistributions of source code must retain the above
  13165. copyright notice, this list of conditions and the following
  13166. disclaimer.
  13167. * Redistributions in binary form must reproduce the above
  13168. copyright notice, this list of conditions and the following
  13169. disclaimer in the documentation and/or other materials
  13170. provided with the distribution.
  13171. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  13172. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  13173. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  13174. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  13175. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  13176. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  13177. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  13178. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  13179. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  13180. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  13181. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  13182. SUCH DAMAGE.
  13183. ***********************************************************************/
  13184. "use strict";
  13185. function array_to_hash(a) {
  13186. var ret = Object.create(null);
  13187. for (var i = 0; i < a.length; ++i)
  13188. ret[a[i]] = true;
  13189. return ret;
  13190. };
  13191. function slice(a, start) {
  13192. return Array.prototype.slice.call(a, start || 0);
  13193. };
  13194. function characters(str) {
  13195. return str.split("");
  13196. };
  13197. function member(name, array) {
  13198. return array.indexOf(name) >= 0;
  13199. };
  13200. function find_if(func, array) {
  13201. for (var i = 0, n = array.length; i < n; ++i) {
  13202. if (func(array[i]))
  13203. return array[i];
  13204. }
  13205. };
  13206. function repeat_string(str, i) {
  13207. if (i <= 0) return "";
  13208. if (i == 1) return str;
  13209. var d = repeat_string(str, i >> 1);
  13210. d += d;
  13211. if (i & 1) d += str;
  13212. return d;
  13213. };
  13214. function configure_error_stack(fn) {
  13215. Object.defineProperty(fn.prototype, "stack", {
  13216. get: function() {
  13217. var err = new Error(this.message);
  13218. err.name = this.name;
  13219. try {
  13220. throw err;
  13221. } catch(e) {
  13222. return e.stack;
  13223. }
  13224. }
  13225. });
  13226. }
  13227. function DefaultsError(msg, defs) {
  13228. this.message = msg;
  13229. this.defs = defs;
  13230. };
  13231. DefaultsError.prototype = Object.create(Error.prototype);
  13232. DefaultsError.prototype.constructor = DefaultsError;
  13233. DefaultsError.prototype.name = "DefaultsError";
  13234. configure_error_stack(DefaultsError);
  13235. DefaultsError.croak = function(msg, defs) {
  13236. throw new DefaultsError(msg, defs);
  13237. };
  13238. function defaults(args, defs, croak) {
  13239. if (args === true)
  13240. args = {};
  13241. var ret = args || {};
  13242. if (croak) for (var i in ret) if (HOP(ret, i) && !HOP(defs, i))
  13243. DefaultsError.croak("`" + i + "` is not a supported option", defs);
  13244. for (var i in defs) if (HOP(defs, i)) {
  13245. ret[i] = (args && HOP(args, i)) ? args[i] : defs[i];
  13246. }
  13247. return ret;
  13248. };
  13249. function merge(obj, ext) {
  13250. var count = 0;
  13251. for (var i in ext) if (HOP(ext, i)) {
  13252. obj[i] = ext[i];
  13253. count++;
  13254. }
  13255. return count;
  13256. };
  13257. function noop() {}
  13258. function return_false() { return false; }
  13259. function return_true() { return true; }
  13260. function return_this() { return this; }
  13261. function return_null() { return null; }
  13262. var MAP = (function(){
  13263. function MAP(a, f, backwards) {
  13264. var ret = [], top = [], i;
  13265. function doit() {
  13266. var val = f(a[i], i);
  13267. var is_last = val instanceof Last;
  13268. if (is_last) val = val.v;
  13269. if (val instanceof AtTop) {
  13270. val = val.v;
  13271. if (val instanceof Splice) {
  13272. top.push.apply(top, backwards ? val.v.slice().reverse() : val.v);
  13273. } else {
  13274. top.push(val);
  13275. }
  13276. }
  13277. else if (val !== skip) {
  13278. if (val instanceof Splice) {
  13279. ret.push.apply(ret, backwards ? val.v.slice().reverse() : val.v);
  13280. } else {
  13281. ret.push(val);
  13282. }
  13283. }
  13284. return is_last;
  13285. };
  13286. if (a instanceof Array) {
  13287. if (backwards) {
  13288. for (i = a.length; --i >= 0;) if (doit()) break;
  13289. ret.reverse();
  13290. top.reverse();
  13291. } else {
  13292. for (i = 0; i < a.length; ++i) if (doit()) break;
  13293. }
  13294. }
  13295. else {
  13296. for (i in a) if (HOP(a, i)) if (doit()) break;
  13297. }
  13298. return top.concat(ret);
  13299. };
  13300. MAP.at_top = function(val) { return new AtTop(val) };
  13301. MAP.splice = function(val) { return new Splice(val) };
  13302. MAP.last = function(val) { return new Last(val) };
  13303. var skip = MAP.skip = {};
  13304. function AtTop(val) { this.v = val };
  13305. function Splice(val) { this.v = val };
  13306. function Last(val) { this.v = val };
  13307. return MAP;
  13308. })();
  13309. function push_uniq(array, el) {
  13310. if (array.indexOf(el) < 0)
  13311. array.push(el);
  13312. };
  13313. function string_template(text, props) {
  13314. return text.replace(/\{(.+?)\}/g, function(str, p){
  13315. return props && props[p];
  13316. });
  13317. };
  13318. function remove(array, el) {
  13319. for (var i = array.length; --i >= 0;) {
  13320. if (array[i] === el) array.splice(i, 1);
  13321. }
  13322. };
  13323. function mergeSort(array, cmp) {
  13324. if (array.length < 2) return array.slice();
  13325. function merge(a, b) {
  13326. var r = [], ai = 0, bi = 0, i = 0;
  13327. while (ai < a.length && bi < b.length) {
  13328. cmp(a[ai], b[bi]) <= 0
  13329. ? r[i++] = a[ai++]
  13330. : r[i++] = b[bi++];
  13331. }
  13332. if (ai < a.length) r.push.apply(r, a.slice(ai));
  13333. if (bi < b.length) r.push.apply(r, b.slice(bi));
  13334. return r;
  13335. };
  13336. function _ms(a) {
  13337. if (a.length <= 1)
  13338. return a;
  13339. var m = Math.floor(a.length / 2), left = a.slice(0, m), right = a.slice(m);
  13340. left = _ms(left);
  13341. right = _ms(right);
  13342. return merge(left, right);
  13343. };
  13344. return _ms(array);
  13345. };
  13346. function set_difference(a, b) {
  13347. return a.filter(function(el){
  13348. return b.indexOf(el) < 0;
  13349. });
  13350. };
  13351. function set_intersection(a, b) {
  13352. return a.filter(function(el){
  13353. return b.indexOf(el) >= 0;
  13354. });
  13355. };
  13356. // this function is taken from Acorn [1], written by Marijn Haverbeke
  13357. // [1] https://github.com/marijnh/acorn
  13358. function makePredicate(words) {
  13359. if (!(words instanceof Array)) words = words.split(" ");
  13360. var f = "", cats = [];
  13361. out: for (var i = 0; i < words.length; ++i) {
  13362. for (var j = 0; j < cats.length; ++j)
  13363. if (cats[j][0].length == words[i].length) {
  13364. cats[j].push(words[i]);
  13365. continue out;
  13366. }
  13367. cats.push([words[i]]);
  13368. }
  13369. function quote(word) {
  13370. return JSON.stringify(word).replace(/[\u2028\u2029]/g, function(s) {
  13371. switch (s) {
  13372. case "\u2028": return "\\u2028";
  13373. case "\u2029": return "\\u2029";
  13374. }
  13375. return s;
  13376. });
  13377. }
  13378. function compareTo(arr) {
  13379. if (arr.length == 1) return f += "return str === " + quote(arr[0]) + ";";
  13380. f += "switch(str){";
  13381. for (var i = 0; i < arr.length; ++i) f += "case " + quote(arr[i]) + ":";
  13382. f += "return true}return false;";
  13383. }
  13384. // When there are more than three length categories, an outer
  13385. // switch first dispatches on the lengths, to save on comparisons.
  13386. if (cats.length > 3) {
  13387. cats.sort(function(a, b) {return b.length - a.length;});
  13388. f += "switch(str.length){";
  13389. for (var i = 0; i < cats.length; ++i) {
  13390. var cat = cats[i];
  13391. f += "case " + cat[0].length + ":";
  13392. compareTo(cat);
  13393. }
  13394. f += "}";
  13395. // Otherwise, simply generate a flat `switch` statement.
  13396. } else {
  13397. compareTo(words);
  13398. }
  13399. return new Function("str", f);
  13400. };
  13401. function all(array, predicate) {
  13402. for (var i = array.length; --i >= 0;)
  13403. if (!predicate(array[i]))
  13404. return false;
  13405. return true;
  13406. };
  13407. function Dictionary() {
  13408. this._values = Object.create(null);
  13409. this._size = 0;
  13410. };
  13411. Dictionary.prototype = {
  13412. set: function(key, val) {
  13413. if (!this.has(key)) ++this._size;
  13414. this._values["$" + key] = val;
  13415. return this;
  13416. },
  13417. add: function(key, val) {
  13418. if (this.has(key)) {
  13419. this.get(key).push(val);
  13420. } else {
  13421. this.set(key, [ val ]);
  13422. }
  13423. return this;
  13424. },
  13425. get: function(key) { return this._values["$" + key] },
  13426. del: function(key) {
  13427. if (this.has(key)) {
  13428. --this._size;
  13429. delete this._values["$" + key];
  13430. }
  13431. return this;
  13432. },
  13433. has: function(key) { return ("$" + key) in this._values },
  13434. each: function(f) {
  13435. for (var i in this._values)
  13436. f(this._values[i], i.substr(1));
  13437. },
  13438. size: function() {
  13439. return this._size;
  13440. },
  13441. map: function(f) {
  13442. var ret = [];
  13443. for (var i in this._values)
  13444. ret.push(f(this._values[i], i.substr(1)));
  13445. return ret;
  13446. },
  13447. toObject: function() { return this._values }
  13448. };
  13449. Dictionary.fromObject = function(obj) {
  13450. var dict = new Dictionary();
  13451. dict._size = merge(dict._values, obj);
  13452. return dict;
  13453. };
  13454. function HOP(obj, prop) {
  13455. return Object.prototype.hasOwnProperty.call(obj, prop);
  13456. }
  13457. // return true if the node at the top of the stack (that means the
  13458. // innermost node in the current output) is lexically the first in
  13459. // a statement.
  13460. function first_in_statement(stack) {
  13461. var node = stack.parent(-1);
  13462. for (var i = 0, p; p = stack.parent(i); i++) {
  13463. if (p instanceof AST_Statement && p.body === node)
  13464. return true;
  13465. if ((p instanceof AST_Seq && p.car === node ) ||
  13466. (p instanceof AST_Call && p.expression === node && !(p instanceof AST_New) ) ||
  13467. (p instanceof AST_Dot && p.expression === node ) ||
  13468. (p instanceof AST_Sub && p.expression === node ) ||
  13469. (p instanceof AST_Conditional && p.condition === node ) ||
  13470. (p instanceof AST_Binary && p.left === node ) ||
  13471. (p instanceof AST_UnaryPostfix && p.expression === node ))
  13472. {
  13473. node = p;
  13474. } else {
  13475. return false;
  13476. }
  13477. }
  13478. }
  13479. /***********************************************************************
  13480. A JavaScript tokenizer / parser / beautifier / compressor.
  13481. https://github.com/mishoo/UglifyJS2
  13482. -------------------------------- (C) ---------------------------------
  13483. Author: Mihai Bazon
  13484. <mihai.bazon@gmail.com>
  13485. http://mihai.bazon.net/blog
  13486. Distributed under the BSD license:
  13487. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  13488. Redistribution and use in source and binary forms, with or without
  13489. modification, are permitted provided that the following conditions
  13490. are met:
  13491. * Redistributions of source code must retain the above
  13492. copyright notice, this list of conditions and the following
  13493. disclaimer.
  13494. * Redistributions in binary form must reproduce the above
  13495. copyright notice, this list of conditions and the following
  13496. disclaimer in the documentation and/or other materials
  13497. provided with the distribution.
  13498. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  13499. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  13500. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  13501. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  13502. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  13503. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  13504. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  13505. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  13506. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  13507. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  13508. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  13509. SUCH DAMAGE.
  13510. ***********************************************************************/
  13511. "use strict";
  13512. function DEFNODE(type, props, methods, base) {
  13513. if (arguments.length < 4) base = AST_Node;
  13514. if (!props) props = [];
  13515. else props = props.split(/\s+/);
  13516. var self_props = props;
  13517. if (base && base.PROPS)
  13518. props = props.concat(base.PROPS);
  13519. var code = "return function AST_" + type + "(props){ if (props) { ";
  13520. for (var i = props.length; --i >= 0;) {
  13521. code += "this." + props[i] + " = props." + props[i] + ";";
  13522. }
  13523. var proto = base && new base;
  13524. if (proto && proto.initialize || (methods && methods.initialize))
  13525. code += "this.initialize();";
  13526. code += "}}";
  13527. var ctor = new Function(code)();
  13528. if (proto) {
  13529. ctor.prototype = proto;
  13530. ctor.BASE = base;
  13531. }
  13532. if (base) base.SUBCLASSES.push(ctor);
  13533. ctor.prototype.CTOR = ctor;
  13534. ctor.PROPS = props || null;
  13535. ctor.SELF_PROPS = self_props;
  13536. ctor.SUBCLASSES = [];
  13537. if (type) {
  13538. ctor.prototype.TYPE = ctor.TYPE = type;
  13539. }
  13540. if (methods) for (i in methods) if (HOP(methods, i)) {
  13541. if (/^\$/.test(i)) {
  13542. ctor[i.substr(1)] = methods[i];
  13543. } else {
  13544. ctor.prototype[i] = methods[i];
  13545. }
  13546. }
  13547. ctor.DEFMETHOD = function(name, method) {
  13548. this.prototype[name] = method;
  13549. };
  13550. if (typeof exports !== "undefined") {
  13551. exports["AST_" + type] = ctor;
  13552. }
  13553. return ctor;
  13554. };
  13555. var AST_Token = DEFNODE("Token", "type value line col pos endline endcol endpos nlb comments_before file raw", {
  13556. }, null);
  13557. var AST_Node = DEFNODE("Node", "start end", {
  13558. _clone: function(deep) {
  13559. if (deep) {
  13560. var self = this.clone();
  13561. return self.transform(new TreeTransformer(function(node) {
  13562. if (node !== self) {
  13563. return node.clone(true);
  13564. }
  13565. }));
  13566. }
  13567. return new this.CTOR(this);
  13568. },
  13569. clone: function(deep) {
  13570. return this._clone(deep);
  13571. },
  13572. $documentation: "Base class of all AST nodes",
  13573. $propdoc: {
  13574. start: "[AST_Token] The first token of this node",
  13575. end: "[AST_Token] The last token of this node"
  13576. },
  13577. _walk: function(visitor) {
  13578. return visitor._visit(this);
  13579. },
  13580. walk: function(visitor) {
  13581. return this._walk(visitor); // not sure the indirection will be any help
  13582. }
  13583. }, null);
  13584. AST_Node.warn_function = null;
  13585. AST_Node.warn = function(txt, props) {
  13586. if (AST_Node.warn_function)
  13587. AST_Node.warn_function(string_template(txt, props));
  13588. };
  13589. /* -----[ statements ]----- */
  13590. var AST_Statement = DEFNODE("Statement", null, {
  13591. $documentation: "Base class of all statements",
  13592. });
  13593. var AST_Debugger = DEFNODE("Debugger", null, {
  13594. $documentation: "Represents a debugger statement",
  13595. }, AST_Statement);
  13596. var AST_Directive = DEFNODE("Directive", "value scope quote", {
  13597. $documentation: "Represents a directive, like \"use strict\";",
  13598. $propdoc: {
  13599. value: "[string] The value of this directive as a plain string (it's not an AST_String!)",
  13600. scope: "[AST_Scope/S] The scope that this directive affects",
  13601. quote: "[string] the original quote character"
  13602. },
  13603. }, AST_Statement);
  13604. var AST_SimpleStatement = DEFNODE("SimpleStatement", "body", {
  13605. $documentation: "A statement consisting of an expression, i.e. a = 1 + 2",
  13606. $propdoc: {
  13607. body: "[AST_Node] an expression node (should not be instanceof AST_Statement)"
  13608. },
  13609. _walk: function(visitor) {
  13610. return visitor._visit(this, function(){
  13611. this.body._walk(visitor);
  13612. });
  13613. }
  13614. }, AST_Statement);
  13615. function walk_body(node, visitor) {
  13616. var body = node.body;
  13617. if (body instanceof AST_Statement) {
  13618. body._walk(visitor);
  13619. }
  13620. else for (var i = 0, len = body.length; i < len; i++) {
  13621. body[i]._walk(visitor);
  13622. }
  13623. };
  13624. var AST_Block = DEFNODE("Block", "body", {
  13625. $documentation: "A body of statements (usually bracketed)",
  13626. $propdoc: {
  13627. body: "[AST_Statement*] an array of statements"
  13628. },
  13629. _walk: function(visitor) {
  13630. return visitor._visit(this, function(){
  13631. walk_body(this, visitor);
  13632. });
  13633. }
  13634. }, AST_Statement);
  13635. var AST_BlockStatement = DEFNODE("BlockStatement", null, {
  13636. $documentation: "A block statement",
  13637. }, AST_Block);
  13638. var AST_EmptyStatement = DEFNODE("EmptyStatement", null, {
  13639. $documentation: "The empty statement (empty block or simply a semicolon)",
  13640. _walk: function(visitor) {
  13641. return visitor._visit(this);
  13642. }
  13643. }, AST_Statement);
  13644. var AST_StatementWithBody = DEFNODE("StatementWithBody", "body", {
  13645. $documentation: "Base class for all statements that contain one nested body: `For`, `ForIn`, `Do`, `While`, `With`",
  13646. $propdoc: {
  13647. body: "[AST_Statement] the body; this should always be present, even if it's an AST_EmptyStatement"
  13648. },
  13649. _walk: function(visitor) {
  13650. return visitor._visit(this, function(){
  13651. this.body._walk(visitor);
  13652. });
  13653. }
  13654. }, AST_Statement);
  13655. var AST_LabeledStatement = DEFNODE("LabeledStatement", "label", {
  13656. $documentation: "Statement with a label",
  13657. $propdoc: {
  13658. label: "[AST_Label] a label definition"
  13659. },
  13660. _walk: function(visitor) {
  13661. return visitor._visit(this, function(){
  13662. this.label._walk(visitor);
  13663. this.body._walk(visitor);
  13664. });
  13665. },
  13666. clone: function(deep) {
  13667. var node = this._clone(deep);
  13668. if (deep) {
  13669. var label = node.label;
  13670. var def = this.label;
  13671. node.walk(new TreeWalker(function(node) {
  13672. if (node instanceof AST_LoopControl
  13673. && node.label && node.label.thedef === def) {
  13674. node.label.thedef = label;
  13675. label.references.push(node);
  13676. }
  13677. }));
  13678. }
  13679. return node;
  13680. }
  13681. }, AST_StatementWithBody);
  13682. var AST_IterationStatement = DEFNODE("IterationStatement", null, {
  13683. $documentation: "Internal class. All loops inherit from it."
  13684. }, AST_StatementWithBody);
  13685. var AST_DWLoop = DEFNODE("DWLoop", "condition", {
  13686. $documentation: "Base class for do/while statements",
  13687. $propdoc: {
  13688. condition: "[AST_Node] the loop condition. Should not be instanceof AST_Statement"
  13689. }
  13690. }, AST_IterationStatement);
  13691. var AST_Do = DEFNODE("Do", null, {
  13692. $documentation: "A `do` statement",
  13693. _walk: function(visitor) {
  13694. return visitor._visit(this, function(){
  13695. this.body._walk(visitor);
  13696. this.condition._walk(visitor);
  13697. });
  13698. }
  13699. }, AST_DWLoop);
  13700. var AST_While = DEFNODE("While", null, {
  13701. $documentation: "A `while` statement",
  13702. _walk: function(visitor) {
  13703. return visitor._visit(this, function(){
  13704. this.condition._walk(visitor);
  13705. this.body._walk(visitor);
  13706. });
  13707. }
  13708. }, AST_DWLoop);
  13709. var AST_For = DEFNODE("For", "init condition step", {
  13710. $documentation: "A `for` statement",
  13711. $propdoc: {
  13712. init: "[AST_Node?] the `for` initialization code, or null if empty",
  13713. condition: "[AST_Node?] the `for` termination clause, or null if empty",
  13714. step: "[AST_Node?] the `for` update clause, or null if empty"
  13715. },
  13716. _walk: function(visitor) {
  13717. return visitor._visit(this, function(){
  13718. if (this.init) this.init._walk(visitor);
  13719. if (this.condition) this.condition._walk(visitor);
  13720. if (this.step) this.step._walk(visitor);
  13721. this.body._walk(visitor);
  13722. });
  13723. }
  13724. }, AST_IterationStatement);
  13725. var AST_ForIn = DEFNODE("ForIn", "init name object", {
  13726. $documentation: "A `for ... in` statement",
  13727. $propdoc: {
  13728. init: "[AST_Node] the `for/in` initialization code",
  13729. name: "[AST_SymbolRef?] the loop variable, only if `init` is AST_Var",
  13730. object: "[AST_Node] the object that we're looping through"
  13731. },
  13732. _walk: function(visitor) {
  13733. return visitor._visit(this, function(){
  13734. this.init._walk(visitor);
  13735. this.object._walk(visitor);
  13736. this.body._walk(visitor);
  13737. });
  13738. }
  13739. }, AST_IterationStatement);
  13740. var AST_With = DEFNODE("With", "expression", {
  13741. $documentation: "A `with` statement",
  13742. $propdoc: {
  13743. expression: "[AST_Node] the `with` expression"
  13744. },
  13745. _walk: function(visitor) {
  13746. return visitor._visit(this, function(){
  13747. this.expression._walk(visitor);
  13748. this.body._walk(visitor);
  13749. });
  13750. }
  13751. }, AST_StatementWithBody);
  13752. /* -----[ scope and functions ]----- */
  13753. var AST_Scope = DEFNODE("Scope", "directives variables functions uses_with uses_eval parent_scope enclosed cname", {
  13754. $documentation: "Base class for all statements introducing a lexical scope",
  13755. $propdoc: {
  13756. directives: "[string*/S] an array of directives declared in this scope",
  13757. variables: "[Object/S] a map of name -> SymbolDef for all variables/functions defined in this scope",
  13758. functions: "[Object/S] like `variables`, but only lists function declarations",
  13759. uses_with: "[boolean/S] tells whether this scope uses the `with` statement",
  13760. uses_eval: "[boolean/S] tells whether this scope contains a direct call to the global `eval`",
  13761. parent_scope: "[AST_Scope?/S] link to the parent scope",
  13762. enclosed: "[SymbolDef*/S] a list of all symbol definitions that are accessed from this scope or any subscopes",
  13763. cname: "[integer/S] current index for mangling variables (used internally by the mangler)",
  13764. },
  13765. }, AST_Block);
  13766. var AST_Toplevel = DEFNODE("Toplevel", "globals", {
  13767. $documentation: "The toplevel scope",
  13768. $propdoc: {
  13769. globals: "[Object/S] a map of name -> SymbolDef for all undeclared names",
  13770. },
  13771. wrap_enclose: function(arg_parameter_pairs) {
  13772. var self = this;
  13773. var args = [];
  13774. var parameters = [];
  13775. arg_parameter_pairs.forEach(function(pair) {
  13776. var splitAt = pair.lastIndexOf(":");
  13777. args.push(pair.substr(0, splitAt));
  13778. parameters.push(pair.substr(splitAt + 1));
  13779. });
  13780. var wrapped_tl = "(function(" + parameters.join(",") + "){ '$ORIG'; })(" + args.join(",") + ")";
  13781. wrapped_tl = parse(wrapped_tl);
  13782. wrapped_tl = wrapped_tl.transform(new TreeTransformer(function before(node){
  13783. if (node instanceof AST_Directive && node.value == "$ORIG") {
  13784. return MAP.splice(self.body);
  13785. }
  13786. }));
  13787. return wrapped_tl;
  13788. },
  13789. wrap_commonjs: function(name, export_all) {
  13790. var self = this;
  13791. var to_export = [];
  13792. if (export_all) {
  13793. self.figure_out_scope();
  13794. self.walk(new TreeWalker(function(node){
  13795. if (node instanceof AST_SymbolDeclaration && node.definition().global) {
  13796. if (!find_if(function(n){ return n.name == node.name }, to_export))
  13797. to_export.push(node);
  13798. }
  13799. }));
  13800. }
  13801. var wrapped_tl = "(function(exports, global){ '$ORIG'; '$EXPORTS'; global['" + name + "'] = exports; }({}, (function(){return this}())))";
  13802. wrapped_tl = parse(wrapped_tl);
  13803. wrapped_tl = wrapped_tl.transform(new TreeTransformer(function before(node){
  13804. if (node instanceof AST_Directive) {
  13805. switch (node.value) {
  13806. case "$ORIG":
  13807. return MAP.splice(self.body);
  13808. case "$EXPORTS":
  13809. var body = [];
  13810. to_export.forEach(function(sym){
  13811. body.push(new AST_SimpleStatement({
  13812. body: new AST_Assign({
  13813. left: new AST_Sub({
  13814. expression: new AST_SymbolRef({ name: "exports" }),
  13815. property: new AST_String({ value: sym.name }),
  13816. }),
  13817. operator: "=",
  13818. right: new AST_SymbolRef(sym),
  13819. }),
  13820. }));
  13821. });
  13822. return MAP.splice(body);
  13823. }
  13824. }
  13825. }));
  13826. return wrapped_tl;
  13827. }
  13828. }, AST_Scope);
  13829. var AST_Lambda = DEFNODE("Lambda", "name argnames uses_arguments", {
  13830. $documentation: "Base class for functions",
  13831. $propdoc: {
  13832. name: "[AST_SymbolDeclaration?] the name of this function",
  13833. argnames: "[AST_SymbolFunarg*] array of function arguments",
  13834. uses_arguments: "[boolean/S] tells whether this function accesses the arguments array"
  13835. },
  13836. _walk: function(visitor) {
  13837. return visitor._visit(this, function(){
  13838. if (this.name) this.name._walk(visitor);
  13839. var argnames = this.argnames;
  13840. for (var i = 0, len = argnames.length; i < len; i++) {
  13841. argnames[i]._walk(visitor);
  13842. }
  13843. walk_body(this, visitor);
  13844. });
  13845. }
  13846. }, AST_Scope);
  13847. var AST_Accessor = DEFNODE("Accessor", null, {
  13848. $documentation: "A setter/getter function. The `name` property is always null."
  13849. }, AST_Lambda);
  13850. var AST_Function = DEFNODE("Function", null, {
  13851. $documentation: "A function expression"
  13852. }, AST_Lambda);
  13853. var AST_Defun = DEFNODE("Defun", null, {
  13854. $documentation: "A function definition"
  13855. }, AST_Lambda);
  13856. /* -----[ JUMPS ]----- */
  13857. var AST_Jump = DEFNODE("Jump", null, {
  13858. $documentation: "Base class for “jumps” (for now that's `return`, `throw`, `break` and `continue`)"
  13859. }, AST_Statement);
  13860. var AST_Exit = DEFNODE("Exit", "value", {
  13861. $documentation: "Base class for “exits” (`return` and `throw`)",
  13862. $propdoc: {
  13863. value: "[AST_Node?] the value returned or thrown by this statement; could be null for AST_Return"
  13864. },
  13865. _walk: function(visitor) {
  13866. return visitor._visit(this, this.value && function(){
  13867. this.value._walk(visitor);
  13868. });
  13869. }
  13870. }, AST_Jump);
  13871. var AST_Return = DEFNODE("Return", null, {
  13872. $documentation: "A `return` statement"
  13873. }, AST_Exit);
  13874. var AST_Throw = DEFNODE("Throw", null, {
  13875. $documentation: "A `throw` statement"
  13876. }, AST_Exit);
  13877. var AST_LoopControl = DEFNODE("LoopControl", "label", {
  13878. $documentation: "Base class for loop control statements (`break` and `continue`)",
  13879. $propdoc: {
  13880. label: "[AST_LabelRef?] the label, or null if none",
  13881. },
  13882. _walk: function(visitor) {
  13883. return visitor._visit(this, this.label && function(){
  13884. this.label._walk(visitor);
  13885. });
  13886. }
  13887. }, AST_Jump);
  13888. var AST_Break = DEFNODE("Break", null, {
  13889. $documentation: "A `break` statement"
  13890. }, AST_LoopControl);
  13891. var AST_Continue = DEFNODE("Continue", null, {
  13892. $documentation: "A `continue` statement"
  13893. }, AST_LoopControl);
  13894. /* -----[ IF ]----- */
  13895. var AST_If = DEFNODE("If", "condition alternative", {
  13896. $documentation: "A `if` statement",
  13897. $propdoc: {
  13898. condition: "[AST_Node] the `if` condition",
  13899. alternative: "[AST_Statement?] the `else` part, or null if not present"
  13900. },
  13901. _walk: function(visitor) {
  13902. return visitor._visit(this, function(){
  13903. this.condition._walk(visitor);
  13904. this.body._walk(visitor);
  13905. if (this.alternative) this.alternative._walk(visitor);
  13906. });
  13907. }
  13908. }, AST_StatementWithBody);
  13909. /* -----[ SWITCH ]----- */
  13910. var AST_Switch = DEFNODE("Switch", "expression", {
  13911. $documentation: "A `switch` statement",
  13912. $propdoc: {
  13913. expression: "[AST_Node] the `switch` “discriminant”"
  13914. },
  13915. _walk: function(visitor) {
  13916. return visitor._visit(this, function(){
  13917. this.expression._walk(visitor);
  13918. walk_body(this, visitor);
  13919. });
  13920. }
  13921. }, AST_Block);
  13922. var AST_SwitchBranch = DEFNODE("SwitchBranch", null, {
  13923. $documentation: "Base class for `switch` branches",
  13924. }, AST_Block);
  13925. var AST_Default = DEFNODE("Default", null, {
  13926. $documentation: "A `default` switch branch",
  13927. }, AST_SwitchBranch);
  13928. var AST_Case = DEFNODE("Case", "expression", {
  13929. $documentation: "A `case` switch branch",
  13930. $propdoc: {
  13931. expression: "[AST_Node] the `case` expression"
  13932. },
  13933. _walk: function(visitor) {
  13934. return visitor._visit(this, function(){
  13935. this.expression._walk(visitor);
  13936. walk_body(this, visitor);
  13937. });
  13938. }
  13939. }, AST_SwitchBranch);
  13940. /* -----[ EXCEPTIONS ]----- */
  13941. var AST_Try = DEFNODE("Try", "bcatch bfinally", {
  13942. $documentation: "A `try` statement",
  13943. $propdoc: {
  13944. bcatch: "[AST_Catch?] the catch block, or null if not present",
  13945. bfinally: "[AST_Finally?] the finally block, or null if not present"
  13946. },
  13947. _walk: function(visitor) {
  13948. return visitor._visit(this, function(){
  13949. walk_body(this, visitor);
  13950. if (this.bcatch) this.bcatch._walk(visitor);
  13951. if (this.bfinally) this.bfinally._walk(visitor);
  13952. });
  13953. }
  13954. }, AST_Block);
  13955. var AST_Catch = DEFNODE("Catch", "argname", {
  13956. $documentation: "A `catch` node; only makes sense as part of a `try` statement",
  13957. $propdoc: {
  13958. argname: "[AST_SymbolCatch] symbol for the exception"
  13959. },
  13960. _walk: function(visitor) {
  13961. return visitor._visit(this, function(){
  13962. this.argname._walk(visitor);
  13963. walk_body(this, visitor);
  13964. });
  13965. }
  13966. }, AST_Block);
  13967. var AST_Finally = DEFNODE("Finally", null, {
  13968. $documentation: "A `finally` node; only makes sense as part of a `try` statement"
  13969. }, AST_Block);
  13970. /* -----[ VAR/CONST ]----- */
  13971. var AST_Definitions = DEFNODE("Definitions", "definitions", {
  13972. $documentation: "Base class for `var` or `const` nodes (variable declarations/initializations)",
  13973. $propdoc: {
  13974. definitions: "[AST_VarDef*] array of variable definitions"
  13975. },
  13976. _walk: function(visitor) {
  13977. return visitor._visit(this, function(){
  13978. var definitions = this.definitions;
  13979. for (var i = 0, len = definitions.length; i < len; i++) {
  13980. definitions[i]._walk(visitor);
  13981. }
  13982. });
  13983. }
  13984. }, AST_Statement);
  13985. var AST_Var = DEFNODE("Var", null, {
  13986. $documentation: "A `var` statement"
  13987. }, AST_Definitions);
  13988. var AST_Const = DEFNODE("Const", null, {
  13989. $documentation: "A `const` statement"
  13990. }, AST_Definitions);
  13991. var AST_VarDef = DEFNODE("VarDef", "name value", {
  13992. $documentation: "A variable declaration; only appears in a AST_Definitions node",
  13993. $propdoc: {
  13994. name: "[AST_SymbolVar|AST_SymbolConst] name of the variable",
  13995. value: "[AST_Node?] initializer, or null of there's no initializer"
  13996. },
  13997. _walk: function(visitor) {
  13998. return visitor._visit(this, function(){
  13999. this.name._walk(visitor);
  14000. if (this.value) this.value._walk(visitor);
  14001. });
  14002. }
  14003. });
  14004. /* -----[ OTHER ]----- */
  14005. var AST_Call = DEFNODE("Call", "expression args", {
  14006. $documentation: "A function call expression",
  14007. $propdoc: {
  14008. expression: "[AST_Node] expression to invoke as function",
  14009. args: "[AST_Node*] array of arguments"
  14010. },
  14011. _walk: function(visitor) {
  14012. return visitor._visit(this, function(){
  14013. this.expression._walk(visitor);
  14014. var args = this.args;
  14015. for (var i = 0, len = args.length; i < len; i++) {
  14016. args[i]._walk(visitor);
  14017. }
  14018. });
  14019. }
  14020. });
  14021. var AST_New = DEFNODE("New", null, {
  14022. $documentation: "An object instantiation. Derives from a function call since it has exactly the same properties"
  14023. }, AST_Call);
  14024. var AST_Seq = DEFNODE("Seq", "car cdr", {
  14025. $documentation: "A sequence expression (two comma-separated expressions)",
  14026. $propdoc: {
  14027. car: "[AST_Node] first element in sequence",
  14028. cdr: "[AST_Node] second element in sequence"
  14029. },
  14030. $cons: function(x, y) {
  14031. var seq = new AST_Seq(x);
  14032. seq.car = x;
  14033. seq.cdr = y;
  14034. return seq;
  14035. },
  14036. $from_array: function(array) {
  14037. if (array.length == 0) return null;
  14038. if (array.length == 1) return array[0].clone();
  14039. var list = null;
  14040. for (var i = array.length; --i >= 0;) {
  14041. list = AST_Seq.cons(array[i], list);
  14042. }
  14043. var p = list;
  14044. while (p) {
  14045. if (p.cdr && !p.cdr.cdr) {
  14046. p.cdr = p.cdr.car;
  14047. break;
  14048. }
  14049. p = p.cdr;
  14050. }
  14051. return list;
  14052. },
  14053. to_array: function() {
  14054. var p = this, a = [];
  14055. while (p) {
  14056. a.push(p.car);
  14057. if (p.cdr && !(p.cdr instanceof AST_Seq)) {
  14058. a.push(p.cdr);
  14059. break;
  14060. }
  14061. p = p.cdr;
  14062. }
  14063. return a;
  14064. },
  14065. add: function(node) {
  14066. var p = this;
  14067. while (p) {
  14068. if (!(p.cdr instanceof AST_Seq)) {
  14069. var cell = AST_Seq.cons(p.cdr, node);
  14070. return p.cdr = cell;
  14071. }
  14072. p = p.cdr;
  14073. }
  14074. },
  14075. len: function() {
  14076. if (this.cdr instanceof AST_Seq) {
  14077. return this.cdr.len() + 1;
  14078. } else {
  14079. return 2;
  14080. }
  14081. },
  14082. _walk: function(visitor) {
  14083. return visitor._visit(this, function(){
  14084. this.car._walk(visitor);
  14085. if (this.cdr) this.cdr._walk(visitor);
  14086. });
  14087. }
  14088. });
  14089. var AST_PropAccess = DEFNODE("PropAccess", "expression property", {
  14090. $documentation: "Base class for property access expressions, i.e. `a.foo` or `a[\"foo\"]`",
  14091. $propdoc: {
  14092. expression: "[AST_Node] the “container” expression",
  14093. 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"
  14094. }
  14095. });
  14096. var AST_Dot = DEFNODE("Dot", null, {
  14097. $documentation: "A dotted property access expression",
  14098. _walk: function(visitor) {
  14099. return visitor._visit(this, function(){
  14100. this.expression._walk(visitor);
  14101. });
  14102. }
  14103. }, AST_PropAccess);
  14104. var AST_Sub = DEFNODE("Sub", null, {
  14105. $documentation: "Index-style property access, i.e. `a[\"foo\"]`",
  14106. _walk: function(visitor) {
  14107. return visitor._visit(this, function(){
  14108. this.expression._walk(visitor);
  14109. this.property._walk(visitor);
  14110. });
  14111. }
  14112. }, AST_PropAccess);
  14113. var AST_Unary = DEFNODE("Unary", "operator expression", {
  14114. $documentation: "Base class for unary expressions",
  14115. $propdoc: {
  14116. operator: "[string] the operator",
  14117. expression: "[AST_Node] expression that this unary operator applies to"
  14118. },
  14119. _walk: function(visitor) {
  14120. return visitor._visit(this, function(){
  14121. this.expression._walk(visitor);
  14122. });
  14123. }
  14124. });
  14125. var AST_UnaryPrefix = DEFNODE("UnaryPrefix", null, {
  14126. $documentation: "Unary prefix expression, i.e. `typeof i` or `++i`"
  14127. }, AST_Unary);
  14128. var AST_UnaryPostfix = DEFNODE("UnaryPostfix", null, {
  14129. $documentation: "Unary postfix expression, i.e. `i++`"
  14130. }, AST_Unary);
  14131. var AST_Binary = DEFNODE("Binary", "left operator right", {
  14132. $documentation: "Binary expression, i.e. `a + b`",
  14133. $propdoc: {
  14134. left: "[AST_Node] left-hand side expression",
  14135. operator: "[string] the operator",
  14136. right: "[AST_Node] right-hand side expression"
  14137. },
  14138. _walk: function(visitor) {
  14139. return visitor._visit(this, function(){
  14140. this.left._walk(visitor);
  14141. this.right._walk(visitor);
  14142. });
  14143. }
  14144. });
  14145. var AST_Conditional = DEFNODE("Conditional", "condition consequent alternative", {
  14146. $documentation: "Conditional expression using the ternary operator, i.e. `a ? b : c`",
  14147. $propdoc: {
  14148. condition: "[AST_Node]",
  14149. consequent: "[AST_Node]",
  14150. alternative: "[AST_Node]"
  14151. },
  14152. _walk: function(visitor) {
  14153. return visitor._visit(this, function(){
  14154. this.condition._walk(visitor);
  14155. this.consequent._walk(visitor);
  14156. this.alternative._walk(visitor);
  14157. });
  14158. }
  14159. });
  14160. var AST_Assign = DEFNODE("Assign", null, {
  14161. $documentation: "An assignment expression — `a = b + 5`",
  14162. }, AST_Binary);
  14163. /* -----[ LITERALS ]----- */
  14164. var AST_Array = DEFNODE("Array", "elements", {
  14165. $documentation: "An array literal",
  14166. $propdoc: {
  14167. elements: "[AST_Node*] array of elements"
  14168. },
  14169. _walk: function(visitor) {
  14170. return visitor._visit(this, function(){
  14171. var elements = this.elements;
  14172. for (var i = 0, len = elements.length; i < len; i++) {
  14173. elements[i]._walk(visitor);
  14174. }
  14175. });
  14176. }
  14177. });
  14178. var AST_Object = DEFNODE("Object", "properties", {
  14179. $documentation: "An object literal",
  14180. $propdoc: {
  14181. properties: "[AST_ObjectProperty*] array of properties"
  14182. },
  14183. _walk: function(visitor) {
  14184. return visitor._visit(this, function(){
  14185. var properties = this.properties;
  14186. for (var i = 0, len = properties.length; i < len; i++) {
  14187. properties[i]._walk(visitor);
  14188. }
  14189. });
  14190. }
  14191. });
  14192. var AST_ObjectProperty = DEFNODE("ObjectProperty", "key value", {
  14193. $documentation: "Base class for literal object properties",
  14194. $propdoc: {
  14195. key: "[string] the property name converted to a string for ObjectKeyVal. For setters and getters this is an AST_SymbolAccessor.",
  14196. value: "[AST_Node] property value. For setters and getters this is an AST_Accessor."
  14197. },
  14198. _walk: function(visitor) {
  14199. return visitor._visit(this, function(){
  14200. this.value._walk(visitor);
  14201. });
  14202. }
  14203. });
  14204. var AST_ObjectKeyVal = DEFNODE("ObjectKeyVal", "quote", {
  14205. $documentation: "A key: value object property",
  14206. $propdoc: {
  14207. quote: "[string] the original quote character"
  14208. }
  14209. }, AST_ObjectProperty);
  14210. var AST_ObjectSetter = DEFNODE("ObjectSetter", null, {
  14211. $documentation: "An object setter property",
  14212. }, AST_ObjectProperty);
  14213. var AST_ObjectGetter = DEFNODE("ObjectGetter", null, {
  14214. $documentation: "An object getter property",
  14215. }, AST_ObjectProperty);
  14216. var AST_Symbol = DEFNODE("Symbol", "scope name thedef", {
  14217. $propdoc: {
  14218. name: "[string] name of this symbol",
  14219. scope: "[AST_Scope/S] the current scope (not necessarily the definition scope)",
  14220. thedef: "[SymbolDef/S] the definition of this symbol"
  14221. },
  14222. $documentation: "Base class for all symbols",
  14223. });
  14224. var AST_SymbolAccessor = DEFNODE("SymbolAccessor", null, {
  14225. $documentation: "The name of a property accessor (setter/getter function)"
  14226. }, AST_Symbol);
  14227. var AST_SymbolDeclaration = DEFNODE("SymbolDeclaration", "init", {
  14228. $documentation: "A declaration symbol (symbol in var/const, function name or argument, symbol in catch)",
  14229. }, AST_Symbol);
  14230. var AST_SymbolVar = DEFNODE("SymbolVar", null, {
  14231. $documentation: "Symbol defining a variable",
  14232. }, AST_SymbolDeclaration);
  14233. var AST_SymbolConst = DEFNODE("SymbolConst", null, {
  14234. $documentation: "A constant declaration"
  14235. }, AST_SymbolDeclaration);
  14236. var AST_SymbolFunarg = DEFNODE("SymbolFunarg", null, {
  14237. $documentation: "Symbol naming a function argument",
  14238. }, AST_SymbolVar);
  14239. var AST_SymbolDefun = DEFNODE("SymbolDefun", null, {
  14240. $documentation: "Symbol defining a function",
  14241. }, AST_SymbolDeclaration);
  14242. var AST_SymbolLambda = DEFNODE("SymbolLambda", null, {
  14243. $documentation: "Symbol naming a function expression",
  14244. }, AST_SymbolDeclaration);
  14245. var AST_SymbolCatch = DEFNODE("SymbolCatch", null, {
  14246. $documentation: "Symbol naming the exception in catch",
  14247. }, AST_SymbolDeclaration);
  14248. var AST_Label = DEFNODE("Label", "references", {
  14249. $documentation: "Symbol naming a label (declaration)",
  14250. $propdoc: {
  14251. references: "[AST_LoopControl*] a list of nodes referring to this label"
  14252. },
  14253. initialize: function() {
  14254. this.references = [];
  14255. this.thedef = this;
  14256. }
  14257. }, AST_Symbol);
  14258. var AST_SymbolRef = DEFNODE("SymbolRef", null, {
  14259. $documentation: "Reference to some symbol (not definition/declaration)",
  14260. }, AST_Symbol);
  14261. var AST_LabelRef = DEFNODE("LabelRef", null, {
  14262. $documentation: "Reference to a label symbol",
  14263. }, AST_Symbol);
  14264. var AST_This = DEFNODE("This", null, {
  14265. $documentation: "The `this` symbol",
  14266. }, AST_Symbol);
  14267. var AST_Constant = DEFNODE("Constant", null, {
  14268. $documentation: "Base class for all constants",
  14269. getValue: function() {
  14270. return this.value;
  14271. }
  14272. });
  14273. var AST_String = DEFNODE("String", "value quote", {
  14274. $documentation: "A string literal",
  14275. $propdoc: {
  14276. value: "[string] the contents of this string",
  14277. quote: "[string] the original quote character"
  14278. }
  14279. }, AST_Constant);
  14280. var AST_Number = DEFNODE("Number", "value literal", {
  14281. $documentation: "A number literal",
  14282. $propdoc: {
  14283. value: "[number] the numeric value",
  14284. literal: "[string] numeric value as string (optional)"
  14285. }
  14286. }, AST_Constant);
  14287. var AST_RegExp = DEFNODE("RegExp", "value", {
  14288. $documentation: "A regexp literal",
  14289. $propdoc: {
  14290. value: "[RegExp] the actual regexp"
  14291. }
  14292. }, AST_Constant);
  14293. var AST_Atom = DEFNODE("Atom", null, {
  14294. $documentation: "Base class for atoms",
  14295. }, AST_Constant);
  14296. var AST_Null = DEFNODE("Null", null, {
  14297. $documentation: "The `null` atom",
  14298. value: null
  14299. }, AST_Atom);
  14300. var AST_NaN = DEFNODE("NaN", null, {
  14301. $documentation: "The impossible value",
  14302. value: 0/0
  14303. }, AST_Atom);
  14304. var AST_Undefined = DEFNODE("Undefined", null, {
  14305. $documentation: "The `undefined` value",
  14306. value: (function(){}())
  14307. }, AST_Atom);
  14308. var AST_Hole = DEFNODE("Hole", null, {
  14309. $documentation: "A hole in an array",
  14310. value: (function(){}())
  14311. }, AST_Atom);
  14312. var AST_Infinity = DEFNODE("Infinity", null, {
  14313. $documentation: "The `Infinity` value",
  14314. value: 1/0
  14315. }, AST_Atom);
  14316. var AST_Boolean = DEFNODE("Boolean", null, {
  14317. $documentation: "Base class for booleans",
  14318. }, AST_Atom);
  14319. var AST_False = DEFNODE("False", null, {
  14320. $documentation: "The `false` atom",
  14321. value: false
  14322. }, AST_Boolean);
  14323. var AST_True = DEFNODE("True", null, {
  14324. $documentation: "The `true` atom",
  14325. value: true
  14326. }, AST_Boolean);
  14327. /* -----[ TreeWalker ]----- */
  14328. function TreeWalker(callback) {
  14329. this.visit = callback;
  14330. this.stack = [];
  14331. this.directives = Object.create(null);
  14332. };
  14333. TreeWalker.prototype = {
  14334. _visit: function(node, descend) {
  14335. this.push(node);
  14336. var ret = this.visit(node, descend ? function(){
  14337. descend.call(node);
  14338. } : noop);
  14339. if (!ret && descend) {
  14340. descend.call(node);
  14341. }
  14342. this.pop(node);
  14343. return ret;
  14344. },
  14345. parent: function(n) {
  14346. return this.stack[this.stack.length - 2 - (n || 0)];
  14347. },
  14348. push: function (node) {
  14349. if (node instanceof AST_Lambda) {
  14350. this.directives = Object.create(this.directives);
  14351. } else if (node instanceof AST_Directive && !this.directives[node.value]) {
  14352. this.directives[node.value] = node;
  14353. }
  14354. this.stack.push(node);
  14355. },
  14356. pop: function(node) {
  14357. this.stack.pop();
  14358. if (node instanceof AST_Lambda) {
  14359. this.directives = Object.getPrototypeOf(this.directives);
  14360. }
  14361. },
  14362. self: function() {
  14363. return this.stack[this.stack.length - 1];
  14364. },
  14365. find_parent: function(type) {
  14366. var stack = this.stack;
  14367. for (var i = stack.length; --i >= 0;) {
  14368. var x = stack[i];
  14369. if (x instanceof type) return x;
  14370. }
  14371. },
  14372. has_directive: function(type) {
  14373. var dir = this.directives[type];
  14374. if (dir) return dir;
  14375. var node = this.stack[this.stack.length - 1];
  14376. if (node instanceof AST_Scope) {
  14377. for (var i = 0; i < node.body.length; ++i) {
  14378. var st = node.body[i];
  14379. if (!(st instanceof AST_Directive)) break;
  14380. if (st.value == type) return st;
  14381. }
  14382. }
  14383. },
  14384. in_boolean_context: function() {
  14385. var stack = this.stack;
  14386. var i = stack.length, self = stack[--i];
  14387. while (i > 0) {
  14388. var p = stack[--i];
  14389. if ((p instanceof AST_If && p.condition === self) ||
  14390. (p instanceof AST_Conditional && p.condition === self) ||
  14391. (p instanceof AST_DWLoop && p.condition === self) ||
  14392. (p instanceof AST_For && p.condition === self) ||
  14393. (p instanceof AST_UnaryPrefix && p.operator == "!" && p.expression === self))
  14394. {
  14395. return true;
  14396. }
  14397. if (!(p instanceof AST_Binary && (p.operator == "&&" || p.operator == "||")))
  14398. return false;
  14399. self = p;
  14400. }
  14401. },
  14402. loopcontrol_target: function(node) {
  14403. var stack = this.stack;
  14404. if (node.label) for (var i = stack.length; --i >= 0;) {
  14405. var x = stack[i];
  14406. if (x instanceof AST_LabeledStatement && x.label.name == node.label.name)
  14407. return x.body;
  14408. } else for (var i = stack.length; --i >= 0;) {
  14409. var x = stack[i];
  14410. if (x instanceof AST_IterationStatement
  14411. || node instanceof AST_Break && x instanceof AST_Switch)
  14412. return x;
  14413. }
  14414. }
  14415. };
  14416. /***********************************************************************
  14417. A JavaScript tokenizer / parser / beautifier / compressor.
  14418. https://github.com/mishoo/UglifyJS2
  14419. -------------------------------- (C) ---------------------------------
  14420. Author: Mihai Bazon
  14421. <mihai.bazon@gmail.com>
  14422. http://mihai.bazon.net/blog
  14423. Distributed under the BSD license:
  14424. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  14425. Parser based on parse-js (http://marijn.haverbeke.nl/parse-js/).
  14426. Redistribution and use in source and binary forms, with or without
  14427. modification, are permitted provided that the following conditions
  14428. are met:
  14429. * Redistributions of source code must retain the above
  14430. copyright notice, this list of conditions and the following
  14431. disclaimer.
  14432. * Redistributions in binary form must reproduce the above
  14433. copyright notice, this list of conditions and the following
  14434. disclaimer in the documentation and/or other materials
  14435. provided with the distribution.
  14436. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  14437. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  14438. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  14439. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  14440. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  14441. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  14442. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  14443. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  14444. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  14445. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  14446. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  14447. SUCH DAMAGE.
  14448. ***********************************************************************/
  14449. "use strict";
  14450. 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';
  14451. var KEYWORDS_ATOM = 'false null true';
  14452. var RESERVED_WORDS = 'abstract boolean byte char class double enum export extends final float goto implements import int interface let long native package private protected public short static super synchronized this throws transient volatile yield'
  14453. + " " + KEYWORDS_ATOM + " " + KEYWORDS;
  14454. var KEYWORDS_BEFORE_EXPRESSION = 'return new delete throw else case';
  14455. KEYWORDS = makePredicate(KEYWORDS);
  14456. RESERVED_WORDS = makePredicate(RESERVED_WORDS);
  14457. KEYWORDS_BEFORE_EXPRESSION = makePredicate(KEYWORDS_BEFORE_EXPRESSION);
  14458. KEYWORDS_ATOM = makePredicate(KEYWORDS_ATOM);
  14459. var OPERATOR_CHARS = makePredicate(characters("+-*&%=<>!?|~^"));
  14460. var RE_HEX_NUMBER = /^0x[0-9a-f]+$/i;
  14461. var RE_OCT_NUMBER = /^0[0-7]+$/;
  14462. var OPERATORS = makePredicate([
  14463. "in",
  14464. "instanceof",
  14465. "typeof",
  14466. "new",
  14467. "void",
  14468. "delete",
  14469. "++",
  14470. "--",
  14471. "+",
  14472. "-",
  14473. "!",
  14474. "~",
  14475. "&",
  14476. "|",
  14477. "^",
  14478. "*",
  14479. "/",
  14480. "%",
  14481. ">>",
  14482. "<<",
  14483. ">>>",
  14484. "<",
  14485. ">",
  14486. "<=",
  14487. ">=",
  14488. "==",
  14489. "===",
  14490. "!=",
  14491. "!==",
  14492. "?",
  14493. "=",
  14494. "+=",
  14495. "-=",
  14496. "/=",
  14497. "*=",
  14498. "%=",
  14499. ">>=",
  14500. "<<=",
  14501. ">>>=",
  14502. "|=",
  14503. "^=",
  14504. "&=",
  14505. "&&",
  14506. "||"
  14507. ]);
  14508. var WHITESPACE_CHARS = makePredicate(characters(" \u00a0\n\r\t\f\u000b\u200b\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000\uFEFF"));
  14509. var NEWLINE_CHARS = makePredicate(characters("\n\r\u2028\u2029"));
  14510. var PUNC_BEFORE_EXPRESSION = makePredicate(characters("[{(,;:"));
  14511. var PUNC_CHARS = makePredicate(characters("[]{}(),;:"));
  14512. var REGEXP_MODIFIERS = makePredicate(characters("gmsiy"));
  14513. /* -----[ Tokenizer ]----- */
  14514. // regexps adapted from http://xregexp.com/plugins/#unicode
  14515. var UNICODE = {
  14516. 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]"),
  14517. 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]"),
  14518. 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]"),
  14519. 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]"),
  14520. connector_punctuation: new RegExp("[\\u005F\\u203F\\u2040\\u2054\\uFE33\\uFE34\\uFE4D-\\uFE4F\\uFF3F]")
  14521. };
  14522. function is_letter(code) {
  14523. return (code >= 97 && code <= 122)
  14524. || (code >= 65 && code <= 90)
  14525. || (code >= 0xaa && UNICODE.letter.test(String.fromCharCode(code)));
  14526. };
  14527. function is_digit(code) {
  14528. return code >= 48 && code <= 57;
  14529. };
  14530. function is_alphanumeric_char(code) {
  14531. return is_digit(code) || is_letter(code);
  14532. };
  14533. function is_unicode_digit(code) {
  14534. return UNICODE.digit.test(String.fromCharCode(code));
  14535. }
  14536. function is_unicode_combining_mark(ch) {
  14537. return UNICODE.non_spacing_mark.test(ch) || UNICODE.space_combining_mark.test(ch);
  14538. };
  14539. function is_unicode_connector_punctuation(ch) {
  14540. return UNICODE.connector_punctuation.test(ch);
  14541. };
  14542. function is_identifier(name) {
  14543. return !RESERVED_WORDS(name) && /^[a-z_$][a-z0-9_$]*$/i.test(name);
  14544. };
  14545. function is_identifier_start(code) {
  14546. return code == 36 || code == 95 || is_letter(code);
  14547. };
  14548. function is_identifier_char(ch) {
  14549. var code = ch.charCodeAt(0);
  14550. return is_identifier_start(code)
  14551. || is_digit(code)
  14552. || code == 8204 // \u200c: zero-width non-joiner <ZWNJ>
  14553. || code == 8205 // \u200d: zero-width joiner <ZWJ> (in my ECMA-262 PDF, this is also 200c)
  14554. || is_unicode_combining_mark(ch)
  14555. || is_unicode_connector_punctuation(ch)
  14556. || is_unicode_digit(code)
  14557. ;
  14558. };
  14559. function is_identifier_string(str){
  14560. return /^[a-z_$][a-z0-9_$]*$/i.test(str);
  14561. };
  14562. function parse_js_number(num) {
  14563. if (RE_HEX_NUMBER.test(num)) {
  14564. return parseInt(num.substr(2), 16);
  14565. } else if (RE_OCT_NUMBER.test(num)) {
  14566. return parseInt(num.substr(1), 8);
  14567. } else {
  14568. var val = parseFloat(num);
  14569. if (val == num) return val;
  14570. }
  14571. };
  14572. function JS_Parse_Error(message, filename, line, col, pos) {
  14573. this.message = message;
  14574. this.filename = filename;
  14575. this.line = line;
  14576. this.col = col;
  14577. this.pos = pos;
  14578. };
  14579. JS_Parse_Error.prototype = Object.create(Error.prototype);
  14580. JS_Parse_Error.prototype.constructor = JS_Parse_Error;
  14581. JS_Parse_Error.prototype.name = "SyntaxError";
  14582. configure_error_stack(JS_Parse_Error);
  14583. function js_error(message, filename, line, col, pos) {
  14584. throw new JS_Parse_Error(message, filename, line, col, pos);
  14585. };
  14586. function is_token(token, type, val) {
  14587. return token.type == type && (val == null || token.value == val);
  14588. };
  14589. var EX_EOF = {};
  14590. function tokenizer($TEXT, filename, html5_comments, shebang) {
  14591. var S = {
  14592. text : $TEXT,
  14593. filename : filename,
  14594. pos : 0,
  14595. tokpos : 0,
  14596. line : 1,
  14597. tokline : 0,
  14598. col : 0,
  14599. tokcol : 0,
  14600. newline_before : false,
  14601. regex_allowed : false,
  14602. comments_before : [],
  14603. directives : {},
  14604. directive_stack : []
  14605. };
  14606. function peek() { return S.text.charAt(S.pos); };
  14607. function next(signal_eof, in_string) {
  14608. var ch = S.text.charAt(S.pos++);
  14609. if (signal_eof && !ch)
  14610. throw EX_EOF;
  14611. if (NEWLINE_CHARS(ch)) {
  14612. S.newline_before = S.newline_before || !in_string;
  14613. ++S.line;
  14614. S.col = 0;
  14615. if (!in_string && ch == "\r" && peek() == "\n") {
  14616. // treat a \r\n sequence as a single \n
  14617. ++S.pos;
  14618. ch = "\n";
  14619. }
  14620. } else {
  14621. ++S.col;
  14622. }
  14623. return ch;
  14624. };
  14625. function forward(i) {
  14626. while (i-- > 0) next();
  14627. };
  14628. function looking_at(str) {
  14629. return S.text.substr(S.pos, str.length) == str;
  14630. };
  14631. function find_eol() {
  14632. var text = S.text;
  14633. for (var i = S.pos, n = S.text.length; i < n; ++i) {
  14634. var ch = text[i];
  14635. if (NEWLINE_CHARS(ch))
  14636. return i;
  14637. }
  14638. return -1;
  14639. };
  14640. function find(what, signal_eof) {
  14641. var pos = S.text.indexOf(what, S.pos);
  14642. if (signal_eof && pos == -1) throw EX_EOF;
  14643. return pos;
  14644. };
  14645. function start_token() {
  14646. S.tokline = S.line;
  14647. S.tokcol = S.col;
  14648. S.tokpos = S.pos;
  14649. };
  14650. var prev_was_dot = false;
  14651. function token(type, value, is_comment) {
  14652. S.regex_allowed = ((type == "operator" && !UNARY_POSTFIX(value)) ||
  14653. (type == "keyword" && KEYWORDS_BEFORE_EXPRESSION(value)) ||
  14654. (type == "punc" && PUNC_BEFORE_EXPRESSION(value)));
  14655. if (type == "punc" && value == ".") {
  14656. prev_was_dot = true;
  14657. } else if (!is_comment) {
  14658. prev_was_dot = false;
  14659. }
  14660. var ret = {
  14661. type : type,
  14662. value : value,
  14663. line : S.tokline,
  14664. col : S.tokcol,
  14665. pos : S.tokpos,
  14666. endline : S.line,
  14667. endcol : S.col,
  14668. endpos : S.pos,
  14669. nlb : S.newline_before,
  14670. file : filename
  14671. };
  14672. if (/^(?:num|string|regexp)$/i.test(type)) {
  14673. ret.raw = $TEXT.substring(ret.pos, ret.endpos);
  14674. }
  14675. if (!is_comment) {
  14676. ret.comments_before = S.comments_before;
  14677. S.comments_before = [];
  14678. // make note of any newlines in the comments that came before
  14679. for (var i = 0, len = ret.comments_before.length; i < len; i++) {
  14680. ret.nlb = ret.nlb || ret.comments_before[i].nlb;
  14681. }
  14682. }
  14683. S.newline_before = false;
  14684. return new AST_Token(ret);
  14685. };
  14686. function skip_whitespace() {
  14687. while (WHITESPACE_CHARS(peek()))
  14688. next();
  14689. };
  14690. function read_while(pred) {
  14691. var ret = "", ch, i = 0;
  14692. while ((ch = peek()) && pred(ch, i++))
  14693. ret += next();
  14694. return ret;
  14695. };
  14696. function parse_error(err) {
  14697. js_error(err, filename, S.tokline, S.tokcol, S.tokpos);
  14698. };
  14699. function read_num(prefix) {
  14700. var has_e = false, after_e = false, has_x = false, has_dot = prefix == ".";
  14701. var num = read_while(function(ch, i){
  14702. var code = ch.charCodeAt(0);
  14703. switch (code) {
  14704. case 120: case 88: // xX
  14705. return has_x ? false : (has_x = true);
  14706. case 101: case 69: // eE
  14707. return has_x ? true : has_e ? false : (has_e = after_e = true);
  14708. case 45: // -
  14709. return after_e || (i == 0 && !prefix);
  14710. case 43: // +
  14711. return after_e;
  14712. case (after_e = false, 46): // .
  14713. return (!has_dot && !has_x && !has_e) ? (has_dot = true) : false;
  14714. }
  14715. return is_alphanumeric_char(code);
  14716. });
  14717. if (prefix) num = prefix + num;
  14718. if (RE_OCT_NUMBER.test(num) && next_token.has_directive("use strict")) {
  14719. parse_error("Legacy octal literals are not allowed in strict mode");
  14720. }
  14721. var valid = parse_js_number(num);
  14722. if (!isNaN(valid)) {
  14723. return token("num", valid);
  14724. } else {
  14725. parse_error("Invalid syntax: " + num);
  14726. }
  14727. };
  14728. function read_escaped_char(in_string) {
  14729. var ch = next(true, in_string);
  14730. switch (ch.charCodeAt(0)) {
  14731. case 110 : return "\n";
  14732. case 114 : return "\r";
  14733. case 116 : return "\t";
  14734. case 98 : return "\b";
  14735. case 118 : return "\u000b"; // \v
  14736. case 102 : return "\f";
  14737. case 120 : return String.fromCharCode(hex_bytes(2)); // \x
  14738. case 117 : return String.fromCharCode(hex_bytes(4)); // \u
  14739. case 10 : return ""; // newline
  14740. case 13 : // \r
  14741. if (peek() == "\n") { // DOS newline
  14742. next(true, in_string);
  14743. return "";
  14744. }
  14745. }
  14746. if (ch >= "0" && ch <= "7")
  14747. return read_octal_escape_sequence(ch);
  14748. return ch;
  14749. };
  14750. function read_octal_escape_sequence(ch) {
  14751. // Read
  14752. var p = peek();
  14753. if (p >= "0" && p <= "7") {
  14754. ch += next(true);
  14755. if (ch[0] <= "3" && (p = peek()) >= "0" && p <= "7")
  14756. ch += next(true);
  14757. }
  14758. // Parse
  14759. if (ch === "0") return "\0";
  14760. if (ch.length > 0 && next_token.has_directive("use strict"))
  14761. parse_error("Legacy octal escape sequences are not allowed in strict mode");
  14762. return String.fromCharCode(parseInt(ch, 8));
  14763. }
  14764. function hex_bytes(n) {
  14765. var num = 0;
  14766. for (; n > 0; --n) {
  14767. var digit = parseInt(next(true), 16);
  14768. if (isNaN(digit))
  14769. parse_error("Invalid hex-character pattern in string");
  14770. num = (num << 4) | digit;
  14771. }
  14772. return num;
  14773. };
  14774. var read_string = with_eof_error("Unterminated string constant", function(quote_char){
  14775. var quote = next(), ret = "";
  14776. for (;;) {
  14777. var ch = next(true, true);
  14778. if (ch == "\\") ch = read_escaped_char(true);
  14779. else if (NEWLINE_CHARS(ch)) parse_error("Unterminated string constant");
  14780. else if (ch == quote) break;
  14781. ret += ch;
  14782. }
  14783. var tok = token("string", ret);
  14784. tok.quote = quote_char;
  14785. return tok;
  14786. });
  14787. function skip_line_comment(type) {
  14788. var regex_allowed = S.regex_allowed;
  14789. var i = find_eol(), ret;
  14790. if (i == -1) {
  14791. ret = S.text.substr(S.pos);
  14792. S.pos = S.text.length;
  14793. } else {
  14794. ret = S.text.substring(S.pos, i);
  14795. S.pos = i;
  14796. }
  14797. S.col = S.tokcol + (S.pos - S.tokpos);
  14798. S.comments_before.push(token(type, ret, true));
  14799. S.regex_allowed = regex_allowed;
  14800. return next_token;
  14801. };
  14802. var skip_multiline_comment = with_eof_error("Unterminated multiline comment", function(){
  14803. var regex_allowed = S.regex_allowed;
  14804. var i = find("*/", true);
  14805. var text = S.text.substring(S.pos, i).replace(/\r\n|\r|\u2028|\u2029/g, '\n');
  14806. // update stream position
  14807. forward(text.length /* doesn't count \r\n as 2 char while S.pos - i does */ + 2);
  14808. S.comments_before.push(token("comment2", text, true));
  14809. S.regex_allowed = regex_allowed;
  14810. return next_token;
  14811. });
  14812. function read_name() {
  14813. var backslash = false, name = "", ch, escaped = false, hex;
  14814. while ((ch = peek()) != null) {
  14815. if (!backslash) {
  14816. if (ch == "\\") escaped = backslash = true, next();
  14817. else if (is_identifier_char(ch)) name += next();
  14818. else break;
  14819. }
  14820. else {
  14821. if (ch != "u") parse_error("Expecting UnicodeEscapeSequence -- uXXXX");
  14822. ch = read_escaped_char();
  14823. if (!is_identifier_char(ch)) parse_error("Unicode char: " + ch.charCodeAt(0) + " is not valid in identifier");
  14824. name += ch;
  14825. backslash = false;
  14826. }
  14827. }
  14828. if (KEYWORDS(name) && escaped) {
  14829. hex = name.charCodeAt(0).toString(16).toUpperCase();
  14830. name = "\\u" + "0000".substr(hex.length) + hex + name.slice(1);
  14831. }
  14832. return name;
  14833. };
  14834. var read_regexp = with_eof_error("Unterminated regular expression", function(regexp){
  14835. var prev_backslash = false, ch, in_class = false;
  14836. while ((ch = next(true))) if (NEWLINE_CHARS(ch)) {
  14837. parse_error("Unexpected line terminator");
  14838. } else if (prev_backslash) {
  14839. regexp += "\\" + ch;
  14840. prev_backslash = false;
  14841. } else if (ch == "[") {
  14842. in_class = true;
  14843. regexp += ch;
  14844. } else if (ch == "]" && in_class) {
  14845. in_class = false;
  14846. regexp += ch;
  14847. } else if (ch == "/" && !in_class) {
  14848. break;
  14849. } else if (ch == "\\") {
  14850. prev_backslash = true;
  14851. } else {
  14852. regexp += ch;
  14853. }
  14854. var mods = read_name();
  14855. try {
  14856. return token("regexp", new RegExp(regexp, mods));
  14857. } catch(e) {
  14858. parse_error(e.message);
  14859. }
  14860. });
  14861. function read_operator(prefix) {
  14862. function grow(op) {
  14863. if (!peek()) return op;
  14864. var bigger = op + peek();
  14865. if (OPERATORS(bigger)) {
  14866. next();
  14867. return grow(bigger);
  14868. } else {
  14869. return op;
  14870. }
  14871. };
  14872. return token("operator", grow(prefix || next()));
  14873. };
  14874. function handle_slash() {
  14875. next();
  14876. switch (peek()) {
  14877. case "/":
  14878. next();
  14879. return skip_line_comment("comment1");
  14880. case "*":
  14881. next();
  14882. return skip_multiline_comment();
  14883. }
  14884. return S.regex_allowed ? read_regexp("") : read_operator("/");
  14885. };
  14886. function handle_dot() {
  14887. next();
  14888. return is_digit(peek().charCodeAt(0))
  14889. ? read_num(".")
  14890. : token("punc", ".");
  14891. };
  14892. function read_word() {
  14893. var word = read_name();
  14894. if (prev_was_dot) return token("name", word);
  14895. return KEYWORDS_ATOM(word) ? token("atom", word)
  14896. : !KEYWORDS(word) ? token("name", word)
  14897. : OPERATORS(word) ? token("operator", word)
  14898. : token("keyword", word);
  14899. };
  14900. function with_eof_error(eof_error, cont) {
  14901. return function(x) {
  14902. try {
  14903. return cont(x);
  14904. } catch(ex) {
  14905. if (ex === EX_EOF) parse_error(eof_error);
  14906. else throw ex;
  14907. }
  14908. };
  14909. };
  14910. function next_token(force_regexp) {
  14911. if (force_regexp != null)
  14912. return read_regexp(force_regexp);
  14913. if (shebang && S.pos == 0 && looking_at("#!")) {
  14914. start_token();
  14915. forward(2);
  14916. skip_line_comment("comment5");
  14917. }
  14918. for (;;) {
  14919. skip_whitespace();
  14920. start_token();
  14921. if (html5_comments) {
  14922. if (looking_at("<!--")) {
  14923. forward(4);
  14924. skip_line_comment("comment3");
  14925. continue;
  14926. }
  14927. if (looking_at("-->") && S.newline_before) {
  14928. forward(3);
  14929. skip_line_comment("comment4");
  14930. continue;
  14931. }
  14932. }
  14933. var ch = peek();
  14934. if (!ch) return token("eof");
  14935. var code = ch.charCodeAt(0);
  14936. switch (code) {
  14937. case 34: case 39: return read_string(ch);
  14938. case 46: return handle_dot();
  14939. case 47: {
  14940. var tok = handle_slash();
  14941. if (tok === next_token) continue;
  14942. return tok;
  14943. }
  14944. }
  14945. if (is_digit(code)) return read_num();
  14946. if (PUNC_CHARS(ch)) return token("punc", next());
  14947. if (OPERATOR_CHARS(ch)) return read_operator();
  14948. if (code == 92 || is_identifier_start(code)) return read_word();
  14949. break;
  14950. }
  14951. parse_error("Unexpected character '" + ch + "'");
  14952. };
  14953. next_token.context = function(nc) {
  14954. if (nc) S = nc;
  14955. return S;
  14956. };
  14957. next_token.add_directive = function(directive) {
  14958. S.directive_stack[S.directive_stack.length - 1].push(directive);
  14959. if (S.directives[directive] === undefined) {
  14960. S.directives[directive] = 1;
  14961. } else {
  14962. S.directives[directive]++;
  14963. }
  14964. }
  14965. next_token.push_directives_stack = function() {
  14966. S.directive_stack.push([]);
  14967. }
  14968. next_token.pop_directives_stack = function() {
  14969. var directives = S.directive_stack[S.directive_stack.length - 1];
  14970. for (var i = 0; i < directives.length; i++) {
  14971. S.directives[directives[i]]--;
  14972. }
  14973. S.directive_stack.pop();
  14974. }
  14975. next_token.has_directive = function(directive) {
  14976. return S.directives[directive] !== undefined &&
  14977. S.directives[directive] > 0;
  14978. }
  14979. return next_token;
  14980. };
  14981. /* -----[ Parser (constants) ]----- */
  14982. var UNARY_PREFIX = makePredicate([
  14983. "typeof",
  14984. "void",
  14985. "delete",
  14986. "--",
  14987. "++",
  14988. "!",
  14989. "~",
  14990. "-",
  14991. "+"
  14992. ]);
  14993. var UNARY_POSTFIX = makePredicate([ "--", "++" ]);
  14994. var ASSIGNMENT = makePredicate([ "=", "+=", "-=", "/=", "*=", "%=", ">>=", "<<=", ">>>=", "|=", "^=", "&=" ]);
  14995. var PRECEDENCE = (function(a, ret){
  14996. for (var i = 0; i < a.length; ++i) {
  14997. var b = a[i];
  14998. for (var j = 0; j < b.length; ++j) {
  14999. ret[b[j]] = i + 1;
  15000. }
  15001. }
  15002. return ret;
  15003. })(
  15004. [
  15005. ["||"],
  15006. ["&&"],
  15007. ["|"],
  15008. ["^"],
  15009. ["&"],
  15010. ["==", "===", "!=", "!=="],
  15011. ["<", ">", "<=", ">=", "in", "instanceof"],
  15012. [">>", "<<", ">>>"],
  15013. ["+", "-"],
  15014. ["*", "/", "%"]
  15015. ],
  15016. {}
  15017. );
  15018. var STATEMENTS_WITH_LABELS = array_to_hash([ "for", "do", "while", "switch" ]);
  15019. var ATOMIC_START_TOKEN = array_to_hash([ "atom", "num", "string", "regexp", "name" ]);
  15020. /* -----[ Parser ]----- */
  15021. function parse($TEXT, options) {
  15022. options = defaults(options, {
  15023. bare_returns : false,
  15024. cli : false,
  15025. expression : false,
  15026. filename : null,
  15027. html5_comments : true,
  15028. shebang : true,
  15029. strict : false,
  15030. toplevel : null,
  15031. });
  15032. var S = {
  15033. input : (typeof $TEXT == "string"
  15034. ? tokenizer($TEXT, options.filename,
  15035. options.html5_comments, options.shebang)
  15036. : $TEXT),
  15037. token : null,
  15038. prev : null,
  15039. peeked : null,
  15040. in_function : 0,
  15041. in_directives : true,
  15042. in_loop : 0,
  15043. labels : []
  15044. };
  15045. S.token = next();
  15046. function is(type, value) {
  15047. return is_token(S.token, type, value);
  15048. };
  15049. function peek() { return S.peeked || (S.peeked = S.input()); };
  15050. function next() {
  15051. S.prev = S.token;
  15052. if (S.peeked) {
  15053. S.token = S.peeked;
  15054. S.peeked = null;
  15055. } else {
  15056. S.token = S.input();
  15057. }
  15058. S.in_directives = S.in_directives && (
  15059. S.token.type == "string" || is("punc", ";")
  15060. );
  15061. return S.token;
  15062. };
  15063. function prev() {
  15064. return S.prev;
  15065. };
  15066. function croak(msg, line, col, pos) {
  15067. var ctx = S.input.context();
  15068. js_error(msg,
  15069. ctx.filename,
  15070. line != null ? line : ctx.tokline,
  15071. col != null ? col : ctx.tokcol,
  15072. pos != null ? pos : ctx.tokpos);
  15073. };
  15074. function token_error(token, msg) {
  15075. croak(msg, token.line, token.col);
  15076. };
  15077. function unexpected(token) {
  15078. if (token == null)
  15079. token = S.token;
  15080. token_error(token, "Unexpected token: " + token.type + " (" + token.value + ")");
  15081. };
  15082. function expect_token(type, val) {
  15083. if (is(type, val)) {
  15084. return next();
  15085. }
  15086. token_error(S.token, "Unexpected token " + S.token.type + " «" + S.token.value + "»" + ", expected " + type + " «" + val + "»");
  15087. };
  15088. function expect(punc) { return expect_token("punc", punc); };
  15089. function can_insert_semicolon() {
  15090. return !options.strict && (
  15091. S.token.nlb || is("eof") || is("punc", "}")
  15092. );
  15093. };
  15094. function semicolon(optional) {
  15095. if (is("punc", ";")) next();
  15096. else if (!optional && !can_insert_semicolon()) unexpected();
  15097. };
  15098. function parenthesised() {
  15099. expect("(");
  15100. var exp = expression(true);
  15101. expect(")");
  15102. return exp;
  15103. };
  15104. function embed_tokens(parser) {
  15105. return function() {
  15106. var start = S.token;
  15107. var expr = parser();
  15108. var end = prev();
  15109. expr.start = start;
  15110. expr.end = end;
  15111. return expr;
  15112. };
  15113. };
  15114. function handle_regexp() {
  15115. if (is("operator", "/") || is("operator", "/=")) {
  15116. S.peeked = null;
  15117. S.token = S.input(S.token.value.substr(1)); // force regexp
  15118. }
  15119. };
  15120. var statement = embed_tokens(function() {
  15121. handle_regexp();
  15122. switch (S.token.type) {
  15123. case "string":
  15124. if (S.in_directives) {
  15125. var token = peek();
  15126. if (S.token.raw.indexOf("\\") == -1
  15127. && (token.nlb
  15128. || is_token(token, "eof")
  15129. || is_token(token, "punc", ";")
  15130. || is_token(token, "punc", "}"))) {
  15131. S.input.add_directive(S.token.value);
  15132. } else {
  15133. S.in_directives = false;
  15134. }
  15135. }
  15136. var dir = S.in_directives, stat = simple_statement();
  15137. return dir ? new AST_Directive(stat.body) : stat;
  15138. case "num":
  15139. case "regexp":
  15140. case "operator":
  15141. case "atom":
  15142. return simple_statement();
  15143. case "name":
  15144. return is_token(peek(), "punc", ":")
  15145. ? labeled_statement()
  15146. : simple_statement();
  15147. case "punc":
  15148. switch (S.token.value) {
  15149. case "{":
  15150. return new AST_BlockStatement({
  15151. start : S.token,
  15152. body : block_(),
  15153. end : prev()
  15154. });
  15155. case "[":
  15156. case "(":
  15157. return simple_statement();
  15158. case ";":
  15159. S.in_directives = false;
  15160. next();
  15161. return new AST_EmptyStatement();
  15162. default:
  15163. unexpected();
  15164. }
  15165. case "keyword":
  15166. switch (S.token.value) {
  15167. case "break":
  15168. next();
  15169. return break_cont(AST_Break);
  15170. case "continue":
  15171. next();
  15172. return break_cont(AST_Continue);
  15173. case "debugger":
  15174. next();
  15175. semicolon();
  15176. return new AST_Debugger();
  15177. case "do":
  15178. next();
  15179. var body = in_loop(statement);
  15180. expect_token("keyword", "while");
  15181. var condition = parenthesised();
  15182. semicolon(true);
  15183. return new AST_Do({
  15184. body : body,
  15185. condition : condition
  15186. });
  15187. case "while":
  15188. next();
  15189. return new AST_While({
  15190. condition : parenthesised(),
  15191. body : in_loop(statement)
  15192. });
  15193. case "for":
  15194. next();
  15195. return for_();
  15196. case "function":
  15197. next();
  15198. return function_(AST_Defun);
  15199. case "if":
  15200. next();
  15201. return if_();
  15202. case "return":
  15203. if (S.in_function == 0 && !options.bare_returns)
  15204. croak("'return' outside of function");
  15205. next();
  15206. var value = null;
  15207. if (is("punc", ";")) {
  15208. next();
  15209. } else if (!can_insert_semicolon()) {
  15210. value = expression(true);
  15211. semicolon();
  15212. }
  15213. return new AST_Return({
  15214. value: value
  15215. });
  15216. case "switch":
  15217. next();
  15218. return new AST_Switch({
  15219. expression : parenthesised(),
  15220. body : in_loop(switch_body_)
  15221. });
  15222. case "throw":
  15223. next();
  15224. if (S.token.nlb)
  15225. croak("Illegal newline after 'throw'");
  15226. var value = expression(true);
  15227. semicolon();
  15228. return new AST_Throw({
  15229. value: value
  15230. });
  15231. case "try":
  15232. next();
  15233. return try_();
  15234. case "var":
  15235. next();
  15236. var node = var_();
  15237. semicolon();
  15238. return node;
  15239. case "const":
  15240. next();
  15241. var node = const_();
  15242. semicolon();
  15243. return node;
  15244. case "with":
  15245. if (S.input.has_directive("use strict")) {
  15246. croak("Strict mode may not include a with statement");
  15247. }
  15248. next();
  15249. return new AST_With({
  15250. expression : parenthesised(),
  15251. body : statement()
  15252. });
  15253. }
  15254. }
  15255. unexpected();
  15256. });
  15257. function labeled_statement() {
  15258. var label = as_symbol(AST_Label);
  15259. if (find_if(function(l){ return l.name == label.name }, S.labels)) {
  15260. // ECMA-262, 12.12: An ECMAScript program is considered
  15261. // syntactically incorrect if it contains a
  15262. // LabelledStatement that is enclosed by a
  15263. // LabelledStatement with the same Identifier as label.
  15264. croak("Label " + label.name + " defined twice");
  15265. }
  15266. expect(":");
  15267. S.labels.push(label);
  15268. var stat = statement();
  15269. S.labels.pop();
  15270. if (!(stat instanceof AST_IterationStatement)) {
  15271. // check for `continue` that refers to this label.
  15272. // those should be reported as syntax errors.
  15273. // https://github.com/mishoo/UglifyJS2/issues/287
  15274. label.references.forEach(function(ref){
  15275. if (ref instanceof AST_Continue) {
  15276. ref = ref.label.start;
  15277. croak("Continue label `" + label.name + "` refers to non-IterationStatement.",
  15278. ref.line, ref.col, ref.pos);
  15279. }
  15280. });
  15281. }
  15282. return new AST_LabeledStatement({ body: stat, label: label });
  15283. };
  15284. function simple_statement(tmp) {
  15285. return new AST_SimpleStatement({ body: (tmp = expression(true), semicolon(), tmp) });
  15286. };
  15287. function break_cont(type) {
  15288. var label = null, ldef;
  15289. if (!can_insert_semicolon()) {
  15290. label = as_symbol(AST_LabelRef, true);
  15291. }
  15292. if (label != null) {
  15293. ldef = find_if(function(l){ return l.name == label.name }, S.labels);
  15294. if (!ldef)
  15295. croak("Undefined label " + label.name);
  15296. label.thedef = ldef;
  15297. }
  15298. else if (S.in_loop == 0)
  15299. croak(type.TYPE + " not inside a loop or switch");
  15300. semicolon();
  15301. var stat = new type({ label: label });
  15302. if (ldef) ldef.references.push(stat);
  15303. return stat;
  15304. };
  15305. function for_() {
  15306. expect("(");
  15307. var init = null;
  15308. if (!is("punc", ";")) {
  15309. init = is("keyword", "var")
  15310. ? (next(), var_(true))
  15311. : expression(true, true);
  15312. if (is("operator", "in")) {
  15313. if (init instanceof AST_Var && init.definitions.length > 1)
  15314. croak("Only one variable declaration allowed in for..in loop");
  15315. next();
  15316. return for_in(init);
  15317. }
  15318. }
  15319. return regular_for(init);
  15320. };
  15321. function regular_for(init) {
  15322. expect(";");
  15323. var test = is("punc", ";") ? null : expression(true);
  15324. expect(";");
  15325. var step = is("punc", ")") ? null : expression(true);
  15326. expect(")");
  15327. return new AST_For({
  15328. init : init,
  15329. condition : test,
  15330. step : step,
  15331. body : in_loop(statement)
  15332. });
  15333. };
  15334. function for_in(init) {
  15335. var lhs = init instanceof AST_Var ? init.definitions[0].name : null;
  15336. var obj = expression(true);
  15337. expect(")");
  15338. return new AST_ForIn({
  15339. init : init,
  15340. name : lhs,
  15341. object : obj,
  15342. body : in_loop(statement)
  15343. });
  15344. };
  15345. var function_ = function(ctor) {
  15346. var in_statement = ctor === AST_Defun;
  15347. var name = is("name") ? as_symbol(in_statement ? AST_SymbolDefun : AST_SymbolLambda) : null;
  15348. if (in_statement && !name)
  15349. unexpected();
  15350. expect("(");
  15351. return new ctor({
  15352. name: name,
  15353. argnames: (function(first, a){
  15354. while (!is("punc", ")")) {
  15355. if (first) first = false; else expect(",");
  15356. a.push(as_symbol(AST_SymbolFunarg));
  15357. }
  15358. next();
  15359. return a;
  15360. })(true, []),
  15361. body: (function(loop, labels){
  15362. ++S.in_function;
  15363. S.in_directives = true;
  15364. S.input.push_directives_stack();
  15365. S.in_loop = 0;
  15366. S.labels = [];
  15367. var a = block_();
  15368. S.input.pop_directives_stack();
  15369. --S.in_function;
  15370. S.in_loop = loop;
  15371. S.labels = labels;
  15372. return a;
  15373. })(S.in_loop, S.labels)
  15374. });
  15375. };
  15376. function if_() {
  15377. var cond = parenthesised(), body = statement(), belse = null;
  15378. if (is("keyword", "else")) {
  15379. next();
  15380. belse = statement();
  15381. }
  15382. return new AST_If({
  15383. condition : cond,
  15384. body : body,
  15385. alternative : belse
  15386. });
  15387. };
  15388. function block_() {
  15389. expect("{");
  15390. var a = [];
  15391. while (!is("punc", "}")) {
  15392. if (is("eof")) unexpected();
  15393. a.push(statement());
  15394. }
  15395. next();
  15396. return a;
  15397. };
  15398. function switch_body_() {
  15399. expect("{");
  15400. var a = [], cur = null, branch = null, tmp;
  15401. while (!is("punc", "}")) {
  15402. if (is("eof")) unexpected();
  15403. if (is("keyword", "case")) {
  15404. if (branch) branch.end = prev();
  15405. cur = [];
  15406. branch = new AST_Case({
  15407. start : (tmp = S.token, next(), tmp),
  15408. expression : expression(true),
  15409. body : cur
  15410. });
  15411. a.push(branch);
  15412. expect(":");
  15413. }
  15414. else if (is("keyword", "default")) {
  15415. if (branch) branch.end = prev();
  15416. cur = [];
  15417. branch = new AST_Default({
  15418. start : (tmp = S.token, next(), expect(":"), tmp),
  15419. body : cur
  15420. });
  15421. a.push(branch);
  15422. }
  15423. else {
  15424. if (!cur) unexpected();
  15425. cur.push(statement());
  15426. }
  15427. }
  15428. if (branch) branch.end = prev();
  15429. next();
  15430. return a;
  15431. };
  15432. function try_() {
  15433. var body = block_(), bcatch = null, bfinally = null;
  15434. if (is("keyword", "catch")) {
  15435. var start = S.token;
  15436. next();
  15437. expect("(");
  15438. var name = as_symbol(AST_SymbolCatch);
  15439. expect(")");
  15440. bcatch = new AST_Catch({
  15441. start : start,
  15442. argname : name,
  15443. body : block_(),
  15444. end : prev()
  15445. });
  15446. }
  15447. if (is("keyword", "finally")) {
  15448. var start = S.token;
  15449. next();
  15450. bfinally = new AST_Finally({
  15451. start : start,
  15452. body : block_(),
  15453. end : prev()
  15454. });
  15455. }
  15456. if (!bcatch && !bfinally)
  15457. croak("Missing catch/finally blocks");
  15458. return new AST_Try({
  15459. body : body,
  15460. bcatch : bcatch,
  15461. bfinally : bfinally
  15462. });
  15463. };
  15464. function vardefs(no_in, in_const) {
  15465. var a = [];
  15466. for (;;) {
  15467. a.push(new AST_VarDef({
  15468. start : S.token,
  15469. name : as_symbol(in_const ? AST_SymbolConst : AST_SymbolVar),
  15470. value : is("operator", "=") ? (next(), expression(false, no_in)) : null,
  15471. end : prev()
  15472. }));
  15473. if (!is("punc", ","))
  15474. break;
  15475. next();
  15476. }
  15477. return a;
  15478. };
  15479. var var_ = function(no_in) {
  15480. return new AST_Var({
  15481. start : prev(),
  15482. definitions : vardefs(no_in, false),
  15483. end : prev()
  15484. });
  15485. };
  15486. var const_ = function() {
  15487. return new AST_Const({
  15488. start : prev(),
  15489. definitions : vardefs(false, true),
  15490. end : prev()
  15491. });
  15492. };
  15493. var new_ = function(allow_calls) {
  15494. var start = S.token;
  15495. expect_token("operator", "new");
  15496. var newexp = expr_atom(false), args;
  15497. if (is("punc", "(")) {
  15498. next();
  15499. args = expr_list(")");
  15500. } else {
  15501. args = [];
  15502. }
  15503. return subscripts(new AST_New({
  15504. start : start,
  15505. expression : newexp,
  15506. args : args,
  15507. end : prev()
  15508. }), allow_calls);
  15509. };
  15510. function as_atom_node() {
  15511. var tok = S.token, ret;
  15512. switch (tok.type) {
  15513. case "name":
  15514. case "keyword":
  15515. ret = _make_symbol(AST_SymbolRef);
  15516. break;
  15517. case "num":
  15518. ret = new AST_Number({ start: tok, end: tok, value: tok.value });
  15519. break;
  15520. case "string":
  15521. ret = new AST_String({
  15522. start : tok,
  15523. end : tok,
  15524. value : tok.value,
  15525. quote : tok.quote
  15526. });
  15527. break;
  15528. case "regexp":
  15529. ret = new AST_RegExp({ start: tok, end: tok, value: tok.value });
  15530. break;
  15531. case "atom":
  15532. switch (tok.value) {
  15533. case "false":
  15534. ret = new AST_False({ start: tok, end: tok });
  15535. break;
  15536. case "true":
  15537. ret = new AST_True({ start: tok, end: tok });
  15538. break;
  15539. case "null":
  15540. ret = new AST_Null({ start: tok, end: tok });
  15541. break;
  15542. }
  15543. break;
  15544. case "operator":
  15545. if (!is_identifier_string(tok.value)) {
  15546. croak("Invalid getter/setter name: " + tok.value,
  15547. tok.line, tok.col, tok.pos);
  15548. }
  15549. ret = _make_symbol(AST_SymbolRef);
  15550. break;
  15551. }
  15552. next();
  15553. return ret;
  15554. };
  15555. var expr_atom = function(allow_calls) {
  15556. if (is("operator", "new")) {
  15557. return new_(allow_calls);
  15558. }
  15559. var start = S.token;
  15560. if (is("punc")) {
  15561. switch (start.value) {
  15562. case "(":
  15563. next();
  15564. var ex = expression(true);
  15565. ex.start = start;
  15566. ex.end = S.token;
  15567. expect(")");
  15568. return subscripts(ex, allow_calls);
  15569. case "[":
  15570. return subscripts(array_(), allow_calls);
  15571. case "{":
  15572. return subscripts(object_(), allow_calls);
  15573. }
  15574. unexpected();
  15575. }
  15576. if (is("keyword", "function")) {
  15577. next();
  15578. var func = function_(AST_Function);
  15579. func.start = start;
  15580. func.end = prev();
  15581. return subscripts(func, allow_calls);
  15582. }
  15583. if (ATOMIC_START_TOKEN[S.token.type]) {
  15584. return subscripts(as_atom_node(), allow_calls);
  15585. }
  15586. unexpected();
  15587. };
  15588. function expr_list(closing, allow_trailing_comma, allow_empty) {
  15589. var first = true, a = [];
  15590. while (!is("punc", closing)) {
  15591. if (first) first = false; else expect(",");
  15592. if (allow_trailing_comma && is("punc", closing)) break;
  15593. if (is("punc", ",") && allow_empty) {
  15594. a.push(new AST_Hole({ start: S.token, end: S.token }));
  15595. } else {
  15596. a.push(expression(false));
  15597. }
  15598. }
  15599. next();
  15600. return a;
  15601. };
  15602. var array_ = embed_tokens(function() {
  15603. expect("[");
  15604. return new AST_Array({
  15605. elements: expr_list("]", !options.strict, true)
  15606. });
  15607. });
  15608. var create_accessor = embed_tokens(function() {
  15609. return function_(AST_Accessor);
  15610. });
  15611. var object_ = embed_tokens(function() {
  15612. expect("{");
  15613. var first = true, a = [];
  15614. while (!is("punc", "}")) {
  15615. if (first) first = false; else expect(",");
  15616. if (!options.strict && is("punc", "}"))
  15617. // allow trailing comma
  15618. break;
  15619. var start = S.token;
  15620. var type = start.type;
  15621. var name = as_property_name();
  15622. if (type == "name" && !is("punc", ":")) {
  15623. var key = new AST_SymbolAccessor({
  15624. start: S.token,
  15625. name: as_property_name(),
  15626. end: prev()
  15627. });
  15628. if (name == "get") {
  15629. a.push(new AST_ObjectGetter({
  15630. start : start,
  15631. key : key,
  15632. value : create_accessor(),
  15633. end : prev()
  15634. }));
  15635. continue;
  15636. }
  15637. if (name == "set") {
  15638. a.push(new AST_ObjectSetter({
  15639. start : start,
  15640. key : key,
  15641. value : create_accessor(),
  15642. end : prev()
  15643. }));
  15644. continue;
  15645. }
  15646. }
  15647. expect(":");
  15648. a.push(new AST_ObjectKeyVal({
  15649. start : start,
  15650. quote : start.quote,
  15651. key : name,
  15652. value : expression(false),
  15653. end : prev()
  15654. }));
  15655. }
  15656. next();
  15657. return new AST_Object({ properties: a });
  15658. });
  15659. function as_property_name() {
  15660. var tmp = S.token;
  15661. switch (tmp.type) {
  15662. case "operator":
  15663. if (!KEYWORDS(tmp.value)) unexpected();
  15664. case "num":
  15665. case "string":
  15666. case "name":
  15667. case "keyword":
  15668. case "atom":
  15669. next();
  15670. return tmp.value;
  15671. default:
  15672. unexpected();
  15673. }
  15674. };
  15675. function as_name() {
  15676. var tmp = S.token;
  15677. if (tmp.type != "name") unexpected();
  15678. next();
  15679. return tmp.value;
  15680. };
  15681. function _make_symbol(type) {
  15682. var name = S.token.value;
  15683. return new (name == "this" ? AST_This : type)({
  15684. name : String(name),
  15685. start : S.token,
  15686. end : S.token
  15687. });
  15688. };
  15689. function as_symbol(type, noerror) {
  15690. if (!is("name")) {
  15691. if (!noerror) croak("Name expected");
  15692. return null;
  15693. }
  15694. var sym = _make_symbol(type);
  15695. next();
  15696. return sym;
  15697. };
  15698. var subscripts = function(expr, allow_calls) {
  15699. var start = expr.start;
  15700. if (is("punc", ".")) {
  15701. next();
  15702. return subscripts(new AST_Dot({
  15703. start : start,
  15704. expression : expr,
  15705. property : as_name(),
  15706. end : prev()
  15707. }), allow_calls);
  15708. }
  15709. if (is("punc", "[")) {
  15710. next();
  15711. var prop = expression(true);
  15712. expect("]");
  15713. return subscripts(new AST_Sub({
  15714. start : start,
  15715. expression : expr,
  15716. property : prop,
  15717. end : prev()
  15718. }), allow_calls);
  15719. }
  15720. if (allow_calls && is("punc", "(")) {
  15721. next();
  15722. return subscripts(new AST_Call({
  15723. start : start,
  15724. expression : expr,
  15725. args : expr_list(")"),
  15726. end : prev()
  15727. }), true);
  15728. }
  15729. return expr;
  15730. };
  15731. var maybe_unary = function(allow_calls) {
  15732. var start = S.token;
  15733. if (is("operator") && UNARY_PREFIX(start.value)) {
  15734. next();
  15735. handle_regexp();
  15736. var ex = make_unary(AST_UnaryPrefix, start, maybe_unary(allow_calls));
  15737. ex.start = start;
  15738. ex.end = prev();
  15739. return ex;
  15740. }
  15741. var val = expr_atom(allow_calls);
  15742. while (is("operator") && UNARY_POSTFIX(S.token.value) && !S.token.nlb) {
  15743. val = make_unary(AST_UnaryPostfix, S.token, val);
  15744. val.start = start;
  15745. val.end = S.token;
  15746. next();
  15747. }
  15748. return val;
  15749. };
  15750. function make_unary(ctor, token, expr) {
  15751. var op = token.value;
  15752. if ((op == "++" || op == "--") && !is_assignable(expr))
  15753. croak("Invalid use of " + op + " operator", token.line, token.col, token.pos);
  15754. return new ctor({ operator: op, expression: expr });
  15755. };
  15756. var expr_op = function(left, min_prec, no_in) {
  15757. var op = is("operator") ? S.token.value : null;
  15758. if (op == "in" && no_in) op = null;
  15759. var prec = op != null ? PRECEDENCE[op] : null;
  15760. if (prec != null && prec > min_prec) {
  15761. next();
  15762. var right = expr_op(maybe_unary(true), prec, no_in);
  15763. return expr_op(new AST_Binary({
  15764. start : left.start,
  15765. left : left,
  15766. operator : op,
  15767. right : right,
  15768. end : right.end
  15769. }), min_prec, no_in);
  15770. }
  15771. return left;
  15772. };
  15773. function expr_ops(no_in) {
  15774. return expr_op(maybe_unary(true), 0, no_in);
  15775. };
  15776. var maybe_conditional = function(no_in) {
  15777. var start = S.token;
  15778. var expr = expr_ops(no_in);
  15779. if (is("operator", "?")) {
  15780. next();
  15781. var yes = expression(false);
  15782. expect(":");
  15783. return new AST_Conditional({
  15784. start : start,
  15785. condition : expr,
  15786. consequent : yes,
  15787. alternative : expression(false, no_in),
  15788. end : prev()
  15789. });
  15790. }
  15791. return expr;
  15792. };
  15793. function is_assignable(expr) {
  15794. if (options.cli) return true;
  15795. return expr instanceof AST_PropAccess || expr instanceof AST_SymbolRef;
  15796. };
  15797. var maybe_assign = function(no_in) {
  15798. var start = S.token;
  15799. var left = maybe_conditional(no_in), val = S.token.value;
  15800. if (is("operator") && ASSIGNMENT(val)) {
  15801. if (is_assignable(left)) {
  15802. next();
  15803. return new AST_Assign({
  15804. start : start,
  15805. left : left,
  15806. operator : val,
  15807. right : maybe_assign(no_in),
  15808. end : prev()
  15809. });
  15810. }
  15811. croak("Invalid assignment");
  15812. }
  15813. return left;
  15814. };
  15815. var expression = function(commas, no_in) {
  15816. var start = S.token;
  15817. var expr = maybe_assign(no_in);
  15818. if (commas && is("punc", ",")) {
  15819. next();
  15820. return new AST_Seq({
  15821. start : start,
  15822. car : expr,
  15823. cdr : expression(true, no_in),
  15824. end : peek()
  15825. });
  15826. }
  15827. return expr;
  15828. };
  15829. function in_loop(cont) {
  15830. ++S.in_loop;
  15831. var ret = cont();
  15832. --S.in_loop;
  15833. return ret;
  15834. };
  15835. if (options.expression) {
  15836. return expression(true);
  15837. }
  15838. return (function(){
  15839. var start = S.token;
  15840. var body = [];
  15841. S.input.push_directives_stack();
  15842. while (!is("eof"))
  15843. body.push(statement());
  15844. S.input.pop_directives_stack();
  15845. var end = prev();
  15846. var toplevel = options.toplevel;
  15847. if (toplevel) {
  15848. toplevel.body = toplevel.body.concat(body);
  15849. toplevel.end = end;
  15850. } else {
  15851. toplevel = new AST_Toplevel({ start: start, body: body, end: end });
  15852. }
  15853. return toplevel;
  15854. })();
  15855. };
  15856. /***********************************************************************
  15857. A JavaScript tokenizer / parser / beautifier / compressor.
  15858. https://github.com/mishoo/UglifyJS2
  15859. -------------------------------- (C) ---------------------------------
  15860. Author: Mihai Bazon
  15861. <mihai.bazon@gmail.com>
  15862. http://mihai.bazon.net/blog
  15863. Distributed under the BSD license:
  15864. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  15865. Redistribution and use in source and binary forms, with or without
  15866. modification, are permitted provided that the following conditions
  15867. are met:
  15868. * Redistributions of source code must retain the above
  15869. copyright notice, this list of conditions and the following
  15870. disclaimer.
  15871. * Redistributions in binary form must reproduce the above
  15872. copyright notice, this list of conditions and the following
  15873. disclaimer in the documentation and/or other materials
  15874. provided with the distribution.
  15875. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  15876. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  15877. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  15878. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  15879. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  15880. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  15881. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  15882. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  15883. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  15884. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  15885. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  15886. SUCH DAMAGE.
  15887. ***********************************************************************/
  15888. "use strict";
  15889. // Tree transformer helpers.
  15890. function TreeTransformer(before, after) {
  15891. TreeWalker.call(this);
  15892. this.before = before;
  15893. this.after = after;
  15894. }
  15895. TreeTransformer.prototype = new TreeWalker;
  15896. (function(undefined){
  15897. function _(node, descend) {
  15898. node.DEFMETHOD("transform", function(tw, in_list){
  15899. var x, y;
  15900. tw.push(this);
  15901. if (tw.before) x = tw.before(this, descend, in_list);
  15902. if (x === undefined) {
  15903. if (!tw.after) {
  15904. x = this;
  15905. descend(x, tw);
  15906. } else {
  15907. tw.stack[tw.stack.length - 1] = x = this;
  15908. descend(x, tw);
  15909. y = tw.after(x, in_list);
  15910. if (y !== undefined) x = y;
  15911. }
  15912. }
  15913. tw.pop(this);
  15914. return x;
  15915. });
  15916. };
  15917. function do_list(list, tw) {
  15918. return MAP(list, function(node){
  15919. return node.transform(tw, true);
  15920. });
  15921. };
  15922. _(AST_Node, noop);
  15923. _(AST_LabeledStatement, function(self, tw){
  15924. self.label = self.label.transform(tw);
  15925. self.body = self.body.transform(tw);
  15926. });
  15927. _(AST_SimpleStatement, function(self, tw){
  15928. self.body = self.body.transform(tw);
  15929. });
  15930. _(AST_Block, function(self, tw){
  15931. self.body = do_list(self.body, tw);
  15932. });
  15933. _(AST_DWLoop, function(self, tw){
  15934. self.condition = self.condition.transform(tw);
  15935. self.body = self.body.transform(tw);
  15936. });
  15937. _(AST_For, function(self, tw){
  15938. if (self.init) self.init = self.init.transform(tw);
  15939. if (self.condition) self.condition = self.condition.transform(tw);
  15940. if (self.step) self.step = self.step.transform(tw);
  15941. self.body = self.body.transform(tw);
  15942. });
  15943. _(AST_ForIn, function(self, tw){
  15944. self.init = self.init.transform(tw);
  15945. self.object = self.object.transform(tw);
  15946. self.body = self.body.transform(tw);
  15947. });
  15948. _(AST_With, function(self, tw){
  15949. self.expression = self.expression.transform(tw);
  15950. self.body = self.body.transform(tw);
  15951. });
  15952. _(AST_Exit, function(self, tw){
  15953. if (self.value) self.value = self.value.transform(tw);
  15954. });
  15955. _(AST_LoopControl, function(self, tw){
  15956. if (self.label) self.label = self.label.transform(tw);
  15957. });
  15958. _(AST_If, function(self, tw){
  15959. self.condition = self.condition.transform(tw);
  15960. self.body = self.body.transform(tw);
  15961. if (self.alternative) self.alternative = self.alternative.transform(tw);
  15962. });
  15963. _(AST_Switch, function(self, tw){
  15964. self.expression = self.expression.transform(tw);
  15965. self.body = do_list(self.body, tw);
  15966. });
  15967. _(AST_Case, function(self, tw){
  15968. self.expression = self.expression.transform(tw);
  15969. self.body = do_list(self.body, tw);
  15970. });
  15971. _(AST_Try, function(self, tw){
  15972. self.body = do_list(self.body, tw);
  15973. if (self.bcatch) self.bcatch = self.bcatch.transform(tw);
  15974. if (self.bfinally) self.bfinally = self.bfinally.transform(tw);
  15975. });
  15976. _(AST_Catch, function(self, tw){
  15977. self.argname = self.argname.transform(tw);
  15978. self.body = do_list(self.body, tw);
  15979. });
  15980. _(AST_Definitions, function(self, tw){
  15981. self.definitions = do_list(self.definitions, tw);
  15982. });
  15983. _(AST_VarDef, function(self, tw){
  15984. self.name = self.name.transform(tw);
  15985. if (self.value) self.value = self.value.transform(tw);
  15986. });
  15987. _(AST_Lambda, function(self, tw){
  15988. if (self.name) self.name = self.name.transform(tw);
  15989. self.argnames = do_list(self.argnames, tw);
  15990. self.body = do_list(self.body, tw);
  15991. });
  15992. _(AST_Call, function(self, tw){
  15993. self.expression = self.expression.transform(tw);
  15994. self.args = do_list(self.args, tw);
  15995. });
  15996. _(AST_Seq, function(self, tw){
  15997. self.car = self.car.transform(tw);
  15998. self.cdr = self.cdr.transform(tw);
  15999. });
  16000. _(AST_Dot, function(self, tw){
  16001. self.expression = self.expression.transform(tw);
  16002. });
  16003. _(AST_Sub, function(self, tw){
  16004. self.expression = self.expression.transform(tw);
  16005. self.property = self.property.transform(tw);
  16006. });
  16007. _(AST_Unary, function(self, tw){
  16008. self.expression = self.expression.transform(tw);
  16009. });
  16010. _(AST_Binary, function(self, tw){
  16011. self.left = self.left.transform(tw);
  16012. self.right = self.right.transform(tw);
  16013. });
  16014. _(AST_Conditional, function(self, tw){
  16015. self.condition = self.condition.transform(tw);
  16016. self.consequent = self.consequent.transform(tw);
  16017. self.alternative = self.alternative.transform(tw);
  16018. });
  16019. _(AST_Array, function(self, tw){
  16020. self.elements = do_list(self.elements, tw);
  16021. });
  16022. _(AST_Object, function(self, tw){
  16023. self.properties = do_list(self.properties, tw);
  16024. });
  16025. _(AST_ObjectProperty, function(self, tw){
  16026. self.value = self.value.transform(tw);
  16027. });
  16028. })();
  16029. /***********************************************************************
  16030. A JavaScript tokenizer / parser / beautifier / compressor.
  16031. https://github.com/mishoo/UglifyJS2
  16032. -------------------------------- (C) ---------------------------------
  16033. Author: Mihai Bazon
  16034. <mihai.bazon@gmail.com>
  16035. http://mihai.bazon.net/blog
  16036. Distributed under the BSD license:
  16037. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  16038. Redistribution and use in source and binary forms, with or without
  16039. modification, are permitted provided that the following conditions
  16040. are met:
  16041. * Redistributions of source code must retain the above
  16042. copyright notice, this list of conditions and the following
  16043. disclaimer.
  16044. * Redistributions in binary form must reproduce the above
  16045. copyright notice, this list of conditions and the following
  16046. disclaimer in the documentation and/or other materials
  16047. provided with the distribution.
  16048. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  16049. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  16050. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  16051. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  16052. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  16053. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  16054. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  16055. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  16056. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  16057. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  16058. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  16059. SUCH DAMAGE.
  16060. ***********************************************************************/
  16061. "use strict";
  16062. function SymbolDef(scope, index, orig) {
  16063. this.name = orig.name;
  16064. this.orig = [ orig ];
  16065. this.scope = scope;
  16066. this.references = [];
  16067. this.global = false;
  16068. this.mangled_name = null;
  16069. this.undeclared = false;
  16070. this.index = index;
  16071. this.id = SymbolDef.next_id++;
  16072. };
  16073. SymbolDef.next_id = 1;
  16074. SymbolDef.prototype = {
  16075. unmangleable: function(options) {
  16076. if (!options) options = {};
  16077. return (this.global && !options.toplevel)
  16078. || this.undeclared
  16079. || (!options.eval && (this.scope.uses_eval || this.scope.uses_with))
  16080. || (options.keep_fnames
  16081. && (this.orig[0] instanceof AST_SymbolLambda
  16082. || this.orig[0] instanceof AST_SymbolDefun));
  16083. },
  16084. mangle: function(options) {
  16085. var cache = options.cache && options.cache.props;
  16086. if (this.global && cache && cache.has(this.name)) {
  16087. this.mangled_name = cache.get(this.name);
  16088. }
  16089. else if (!this.mangled_name && !this.unmangleable(options)) {
  16090. var s = this.scope;
  16091. var sym = this.orig[0];
  16092. if (!options.screw_ie8 && sym instanceof AST_SymbolLambda)
  16093. s = s.parent_scope;
  16094. var def;
  16095. if (this.defun && (def = this.defun.variables.get(this.name))) {
  16096. this.mangled_name = def.mangled_name || def.name;
  16097. } else
  16098. this.mangled_name = s.next_mangled(options, this);
  16099. if (this.global && cache) {
  16100. cache.set(this.name, this.mangled_name);
  16101. }
  16102. }
  16103. }
  16104. };
  16105. AST_Toplevel.DEFMETHOD("figure_out_scope", function(options){
  16106. options = defaults(options, {
  16107. cache: null,
  16108. screw_ie8: true,
  16109. });
  16110. // pass 1: setup scope chaining and handle definitions
  16111. var self = this;
  16112. var scope = self.parent_scope = null;
  16113. var labels = new Dictionary();
  16114. var defun = null;
  16115. var tw = new TreeWalker(function(node, descend){
  16116. if (node instanceof AST_Catch) {
  16117. var save_scope = scope;
  16118. scope = new AST_Scope(node);
  16119. scope.init_scope_vars(save_scope);
  16120. descend();
  16121. scope = save_scope;
  16122. return true;
  16123. }
  16124. if (node instanceof AST_Scope) {
  16125. node.init_scope_vars(scope);
  16126. var save_scope = scope;
  16127. var save_defun = defun;
  16128. var save_labels = labels;
  16129. defun = scope = node;
  16130. labels = new Dictionary();
  16131. descend();
  16132. scope = save_scope;
  16133. defun = save_defun;
  16134. labels = save_labels;
  16135. return true; // don't descend again in TreeWalker
  16136. }
  16137. if (node instanceof AST_LabeledStatement) {
  16138. var l = node.label;
  16139. if (labels.has(l.name)) {
  16140. throw new Error(string_template("Label {name} defined twice", l));
  16141. }
  16142. labels.set(l.name, l);
  16143. descend();
  16144. labels.del(l.name);
  16145. return true; // no descend again
  16146. }
  16147. if (node instanceof AST_With) {
  16148. for (var s = scope; s; s = s.parent_scope)
  16149. s.uses_with = true;
  16150. return;
  16151. }
  16152. if (node instanceof AST_Symbol) {
  16153. node.scope = scope;
  16154. }
  16155. if (node instanceof AST_Label) {
  16156. node.thedef = node;
  16157. node.references = [];
  16158. }
  16159. if (node instanceof AST_SymbolLambda) {
  16160. defun.def_function(node);
  16161. }
  16162. else if (node instanceof AST_SymbolDefun) {
  16163. // Careful here, the scope where this should be defined is
  16164. // the parent scope. The reason is that we enter a new
  16165. // scope when we encounter the AST_Defun node (which is
  16166. // instanceof AST_Scope) but we get to the symbol a bit
  16167. // later.
  16168. (node.scope = defun.parent_scope).def_function(node);
  16169. }
  16170. else if (node instanceof AST_SymbolVar
  16171. || node instanceof AST_SymbolConst) {
  16172. defun.def_variable(node);
  16173. if (defun !== scope) {
  16174. node.mark_enclosed(options);
  16175. var def = scope.find_variable(node);
  16176. if (node.thedef !== def) {
  16177. node.thedef = def;
  16178. node.reference(options);
  16179. }
  16180. }
  16181. }
  16182. else if (node instanceof AST_SymbolCatch) {
  16183. scope.def_variable(node).defun = defun;
  16184. }
  16185. else if (node instanceof AST_LabelRef) {
  16186. var sym = labels.get(node.name);
  16187. if (!sym) throw new Error(string_template("Undefined label {name} [{line},{col}]", {
  16188. name: node.name,
  16189. line: node.start.line,
  16190. col: node.start.col
  16191. }));
  16192. node.thedef = sym;
  16193. }
  16194. });
  16195. self.walk(tw);
  16196. // pass 2: find back references and eval
  16197. var func = null;
  16198. var globals = self.globals = new Dictionary();
  16199. var tw = new TreeWalker(function(node, descend){
  16200. if (node instanceof AST_Lambda) {
  16201. var prev_func = func;
  16202. func = node;
  16203. descend();
  16204. func = prev_func;
  16205. return true;
  16206. }
  16207. if (node instanceof AST_LoopControl && node.label) {
  16208. node.label.thedef.references.push(node);
  16209. return true;
  16210. }
  16211. if (node instanceof AST_SymbolRef) {
  16212. var name = node.name;
  16213. if (name == "eval" && tw.parent() instanceof AST_Call) {
  16214. for (var s = node.scope; s && !s.uses_eval; s = s.parent_scope) {
  16215. s.uses_eval = true;
  16216. }
  16217. }
  16218. var sym = node.scope.find_variable(name);
  16219. if (node.scope instanceof AST_Lambda && name == "arguments") {
  16220. node.scope.uses_arguments = true;
  16221. }
  16222. if (!sym) {
  16223. sym = self.def_global(node);
  16224. }
  16225. node.thedef = sym;
  16226. node.reference(options);
  16227. return true;
  16228. }
  16229. });
  16230. self.walk(tw);
  16231. // pass 3: fix up any scoping issue with IE8
  16232. if (!options.screw_ie8) {
  16233. self.walk(new TreeWalker(function(node, descend) {
  16234. if (node instanceof AST_SymbolCatch) {
  16235. var name = node.name;
  16236. var refs = node.thedef.references;
  16237. var scope = node.thedef.defun;
  16238. var def = scope.find_variable(name) || self.globals.get(name) || scope.def_variable(node);
  16239. refs.forEach(function(ref) {
  16240. ref.thedef = def;
  16241. ref.reference(options);
  16242. });
  16243. node.thedef = def;
  16244. return true;
  16245. }
  16246. }));
  16247. }
  16248. if (options.cache) {
  16249. this.cname = options.cache.cname;
  16250. }
  16251. });
  16252. AST_Toplevel.DEFMETHOD("def_global", function(node){
  16253. var globals = this.globals, name = node.name;
  16254. if (globals.has(name)) {
  16255. return globals.get(name);
  16256. } else {
  16257. var g = new SymbolDef(this, globals.size(), node);
  16258. g.undeclared = true;
  16259. g.global = true;
  16260. globals.set(name, g);
  16261. return g;
  16262. }
  16263. });
  16264. AST_Scope.DEFMETHOD("init_scope_vars", function(parent_scope){
  16265. this.variables = new Dictionary(); // map name to AST_SymbolVar (variables defined in this scope; includes functions)
  16266. this.functions = new Dictionary(); // map name to AST_SymbolDefun (functions defined in this scope)
  16267. this.uses_with = false; // will be set to true if this or some nested scope uses the `with` statement
  16268. this.uses_eval = false; // will be set to true if this or nested scope uses the global `eval`
  16269. this.parent_scope = parent_scope; // the parent scope
  16270. this.enclosed = []; // a list of variables from this or outer scope(s) that are referenced from this or inner scopes
  16271. this.cname = -1; // the current index for mangling functions/variables
  16272. });
  16273. AST_Lambda.DEFMETHOD("init_scope_vars", function(){
  16274. AST_Scope.prototype.init_scope_vars.apply(this, arguments);
  16275. this.uses_arguments = false;
  16276. this.def_variable(new AST_SymbolVar({
  16277. name: "arguments",
  16278. start: this.start,
  16279. end: this.end
  16280. }));
  16281. });
  16282. AST_Symbol.DEFMETHOD("mark_enclosed", function(options) {
  16283. var def = this.definition();
  16284. var s = this.scope;
  16285. while (s) {
  16286. push_uniq(s.enclosed, def);
  16287. if (options.keep_fnames) {
  16288. s.functions.each(function(d) {
  16289. push_uniq(def.scope.enclosed, d);
  16290. });
  16291. }
  16292. if (s === def.scope) break;
  16293. s = s.parent_scope;
  16294. }
  16295. });
  16296. AST_Symbol.DEFMETHOD("reference", function(options) {
  16297. this.definition().references.push(this);
  16298. this.mark_enclosed(options);
  16299. });
  16300. AST_Scope.DEFMETHOD("find_variable", function(name){
  16301. if (name instanceof AST_Symbol) name = name.name;
  16302. return this.variables.get(name)
  16303. || (this.parent_scope && this.parent_scope.find_variable(name));
  16304. });
  16305. AST_Scope.DEFMETHOD("def_function", function(symbol){
  16306. this.functions.set(symbol.name, this.def_variable(symbol));
  16307. });
  16308. AST_Scope.DEFMETHOD("def_variable", function(symbol){
  16309. var def;
  16310. if (!this.variables.has(symbol.name)) {
  16311. def = new SymbolDef(this, this.variables.size(), symbol);
  16312. this.variables.set(symbol.name, def);
  16313. def.global = !this.parent_scope;
  16314. } else {
  16315. def = this.variables.get(symbol.name);
  16316. def.orig.push(symbol);
  16317. }
  16318. return symbol.thedef = def;
  16319. });
  16320. AST_Scope.DEFMETHOD("next_mangled", function(options){
  16321. var ext = this.enclosed;
  16322. out: while (true) {
  16323. var m = base54(++this.cname);
  16324. if (!is_identifier(m)) continue; // skip over "do"
  16325. // https://github.com/mishoo/UglifyJS2/issues/242 -- do not
  16326. // shadow a name excepted from mangling.
  16327. if (options.except.indexOf(m) >= 0) continue;
  16328. // we must ensure that the mangled name does not shadow a name
  16329. // from some parent scope that is referenced in this or in
  16330. // inner scopes.
  16331. for (var i = ext.length; --i >= 0;) {
  16332. var sym = ext[i];
  16333. var name = sym.mangled_name || (sym.unmangleable(options) && sym.name);
  16334. if (m == name) continue out;
  16335. }
  16336. return m;
  16337. }
  16338. });
  16339. AST_Function.DEFMETHOD("next_mangled", function(options, def){
  16340. // #179, #326
  16341. // in Safari strict mode, something like (function x(x){...}) is a syntax error;
  16342. // a function expression's argument cannot shadow the function expression's name
  16343. var tricky_def = def.orig[0] instanceof AST_SymbolFunarg && this.name && this.name.definition();
  16344. // the function's mangled_name is null when keep_fnames is true
  16345. var tricky_name = tricky_def ? tricky_def.mangled_name || tricky_def.name : null;
  16346. while (true) {
  16347. var name = AST_Lambda.prototype.next_mangled.call(this, options, def);
  16348. if (!tricky_name || tricky_name != name)
  16349. return name;
  16350. }
  16351. });
  16352. AST_Symbol.DEFMETHOD("unmangleable", function(options){
  16353. return this.definition().unmangleable(options);
  16354. });
  16355. // labels are always mangleable
  16356. AST_Label.DEFMETHOD("unmangleable", function(){
  16357. return false;
  16358. });
  16359. AST_Symbol.DEFMETHOD("unreferenced", function(){
  16360. return this.definition().references.length == 0
  16361. && !(this.scope.uses_eval || this.scope.uses_with);
  16362. });
  16363. AST_Symbol.DEFMETHOD("undeclared", function(){
  16364. return this.definition().undeclared;
  16365. });
  16366. AST_LabelRef.DEFMETHOD("undeclared", function(){
  16367. return false;
  16368. });
  16369. AST_Label.DEFMETHOD("undeclared", function(){
  16370. return false;
  16371. });
  16372. AST_Symbol.DEFMETHOD("definition", function(){
  16373. return this.thedef;
  16374. });
  16375. AST_Symbol.DEFMETHOD("global", function(){
  16376. return this.definition().global;
  16377. });
  16378. AST_Toplevel.DEFMETHOD("_default_mangler_options", function(options){
  16379. return defaults(options, {
  16380. eval : false,
  16381. except : [],
  16382. keep_fnames : false,
  16383. screw_ie8 : true,
  16384. sort : false, // Ignored. Flag retained for backwards compatibility.
  16385. toplevel : false,
  16386. });
  16387. });
  16388. AST_Toplevel.DEFMETHOD("mangle_names", function(options){
  16389. options = this._default_mangler_options(options);
  16390. // Never mangle arguments
  16391. options.except.push('arguments');
  16392. // We only need to mangle declaration nodes. Special logic wired
  16393. // into the code generator will display the mangled name if it's
  16394. // present (and for AST_SymbolRef-s it'll use the mangled name of
  16395. // the AST_SymbolDeclaration that it points to).
  16396. var lname = -1;
  16397. var to_mangle = [];
  16398. if (options.cache) {
  16399. this.globals.each(function(symbol){
  16400. if (options.except.indexOf(symbol.name) < 0) {
  16401. to_mangle.push(symbol);
  16402. }
  16403. });
  16404. }
  16405. var tw = new TreeWalker(function(node, descend){
  16406. if (node instanceof AST_LabeledStatement) {
  16407. // lname is incremented when we get to the AST_Label
  16408. var save_nesting = lname;
  16409. descend();
  16410. lname = save_nesting;
  16411. return true; // don't descend again in TreeWalker
  16412. }
  16413. if (node instanceof AST_Scope) {
  16414. var p = tw.parent(), a = [];
  16415. node.variables.each(function(symbol){
  16416. if (options.except.indexOf(symbol.name) < 0) {
  16417. a.push(symbol);
  16418. }
  16419. });
  16420. to_mangle.push.apply(to_mangle, a);
  16421. return;
  16422. }
  16423. if (node instanceof AST_Label) {
  16424. var name;
  16425. do name = base54(++lname); while (!is_identifier(name));
  16426. node.mangled_name = name;
  16427. return true;
  16428. }
  16429. if (options.screw_ie8 && node instanceof AST_SymbolCatch) {
  16430. to_mangle.push(node.definition());
  16431. return;
  16432. }
  16433. });
  16434. this.walk(tw);
  16435. to_mangle.forEach(function(def){ def.mangle(options) });
  16436. if (options.cache) {
  16437. options.cache.cname = this.cname;
  16438. }
  16439. });
  16440. AST_Toplevel.DEFMETHOD("compute_char_frequency", function(options){
  16441. options = this._default_mangler_options(options);
  16442. var tw = new TreeWalker(function(node){
  16443. if (node instanceof AST_Constant)
  16444. base54.consider(node.print_to_string());
  16445. else if (node instanceof AST_Return)
  16446. base54.consider("return");
  16447. else if (node instanceof AST_Throw)
  16448. base54.consider("throw");
  16449. else if (node instanceof AST_Continue)
  16450. base54.consider("continue");
  16451. else if (node instanceof AST_Break)
  16452. base54.consider("break");
  16453. else if (node instanceof AST_Debugger)
  16454. base54.consider("debugger");
  16455. else if (node instanceof AST_Directive)
  16456. base54.consider(node.value);
  16457. else if (node instanceof AST_While)
  16458. base54.consider("while");
  16459. else if (node instanceof AST_Do)
  16460. base54.consider("do while");
  16461. else if (node instanceof AST_If) {
  16462. base54.consider("if");
  16463. if (node.alternative) base54.consider("else");
  16464. }
  16465. else if (node instanceof AST_Var)
  16466. base54.consider("var");
  16467. else if (node instanceof AST_Const)
  16468. base54.consider("const");
  16469. else if (node instanceof AST_Lambda)
  16470. base54.consider("function");
  16471. else if (node instanceof AST_For)
  16472. base54.consider("for");
  16473. else if (node instanceof AST_ForIn)
  16474. base54.consider("for in");
  16475. else if (node instanceof AST_Switch)
  16476. base54.consider("switch");
  16477. else if (node instanceof AST_Case)
  16478. base54.consider("case");
  16479. else if (node instanceof AST_Default)
  16480. base54.consider("default");
  16481. else if (node instanceof AST_With)
  16482. base54.consider("with");
  16483. else if (node instanceof AST_ObjectSetter)
  16484. base54.consider("set" + node.key);
  16485. else if (node instanceof AST_ObjectGetter)
  16486. base54.consider("get" + node.key);
  16487. else if (node instanceof AST_ObjectKeyVal)
  16488. base54.consider(node.key);
  16489. else if (node instanceof AST_New)
  16490. base54.consider("new");
  16491. else if (node instanceof AST_This)
  16492. base54.consider("this");
  16493. else if (node instanceof AST_Try)
  16494. base54.consider("try");
  16495. else if (node instanceof AST_Catch)
  16496. base54.consider("catch");
  16497. else if (node instanceof AST_Finally)
  16498. base54.consider("finally");
  16499. else if (node instanceof AST_Symbol && node.unmangleable(options))
  16500. base54.consider(node.name);
  16501. else if (node instanceof AST_Unary || node instanceof AST_Binary)
  16502. base54.consider(node.operator);
  16503. else if (node instanceof AST_Dot)
  16504. base54.consider(node.property);
  16505. });
  16506. this.walk(tw);
  16507. base54.sort();
  16508. });
  16509. var base54 = (function() {
  16510. var string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_0123456789";
  16511. var chars, frequency;
  16512. function reset() {
  16513. frequency = Object.create(null);
  16514. chars = string.split("").map(function(ch){ return ch.charCodeAt(0) });
  16515. chars.forEach(function(ch){ frequency[ch] = 0 });
  16516. }
  16517. base54.consider = function(str){
  16518. for (var i = str.length; --i >= 0;) {
  16519. var code = str.charCodeAt(i);
  16520. if (code in frequency) ++frequency[code];
  16521. }
  16522. };
  16523. base54.sort = function() {
  16524. chars = mergeSort(chars, function(a, b){
  16525. if (is_digit(a) && !is_digit(b)) return 1;
  16526. if (is_digit(b) && !is_digit(a)) return -1;
  16527. return frequency[b] - frequency[a];
  16528. });
  16529. };
  16530. base54.reset = reset;
  16531. reset();
  16532. base54.get = function(){ return chars };
  16533. base54.freq = function(){ return frequency };
  16534. function base54(num) {
  16535. var ret = "", base = 54;
  16536. num++;
  16537. do {
  16538. num--;
  16539. ret += String.fromCharCode(chars[num % base]);
  16540. num = Math.floor(num / base);
  16541. base = 64;
  16542. } while (num > 0);
  16543. return ret;
  16544. };
  16545. return base54;
  16546. })();
  16547. AST_Toplevel.DEFMETHOD("scope_warnings", function(options){
  16548. options = defaults(options, {
  16549. assign_to_global : true,
  16550. eval : true,
  16551. func_arguments : true,
  16552. nested_defuns : true,
  16553. undeclared : false, // this makes a lot of noise
  16554. unreferenced : true,
  16555. });
  16556. var tw = new TreeWalker(function(node){
  16557. if (options.undeclared
  16558. && node instanceof AST_SymbolRef
  16559. && node.undeclared())
  16560. {
  16561. // XXX: this also warns about JS standard names,
  16562. // i.e. Object, Array, parseInt etc. Should add a list of
  16563. // exceptions.
  16564. AST_Node.warn("Undeclared symbol: {name} [{file}:{line},{col}]", {
  16565. name: node.name,
  16566. file: node.start.file,
  16567. line: node.start.line,
  16568. col: node.start.col
  16569. });
  16570. }
  16571. if (options.assign_to_global)
  16572. {
  16573. var sym = null;
  16574. if (node instanceof AST_Assign && node.left instanceof AST_SymbolRef)
  16575. sym = node.left;
  16576. else if (node instanceof AST_ForIn && node.init instanceof AST_SymbolRef)
  16577. sym = node.init;
  16578. if (sym
  16579. && (sym.undeclared()
  16580. || (sym.global() && sym.scope !== sym.definition().scope))) {
  16581. AST_Node.warn("{msg}: {name} [{file}:{line},{col}]", {
  16582. msg: sym.undeclared() ? "Accidental global?" : "Assignment to global",
  16583. name: sym.name,
  16584. file: sym.start.file,
  16585. line: sym.start.line,
  16586. col: sym.start.col
  16587. });
  16588. }
  16589. }
  16590. if (options.eval
  16591. && node instanceof AST_SymbolRef
  16592. && node.undeclared()
  16593. && node.name == "eval") {
  16594. AST_Node.warn("Eval is used [{file}:{line},{col}]", node.start);
  16595. }
  16596. if (options.unreferenced
  16597. && (node instanceof AST_SymbolDeclaration || node instanceof AST_Label)
  16598. && !(node instanceof AST_SymbolCatch)
  16599. && node.unreferenced()) {
  16600. AST_Node.warn("{type} {name} is declared but not referenced [{file}:{line},{col}]", {
  16601. type: node instanceof AST_Label ? "Label" : "Symbol",
  16602. name: node.name,
  16603. file: node.start.file,
  16604. line: node.start.line,
  16605. col: node.start.col
  16606. });
  16607. }
  16608. if (options.func_arguments
  16609. && node instanceof AST_Lambda
  16610. && node.uses_arguments) {
  16611. AST_Node.warn("arguments used in function {name} [{file}:{line},{col}]", {
  16612. name: node.name ? node.name.name : "anonymous",
  16613. file: node.start.file,
  16614. line: node.start.line,
  16615. col: node.start.col
  16616. });
  16617. }
  16618. if (options.nested_defuns
  16619. && node instanceof AST_Defun
  16620. && !(tw.parent() instanceof AST_Scope)) {
  16621. AST_Node.warn("Function {name} declared in nested statement \"{type}\" [{file}:{line},{col}]", {
  16622. name: node.name.name,
  16623. type: tw.parent().TYPE,
  16624. file: node.start.file,
  16625. line: node.start.line,
  16626. col: node.start.col
  16627. });
  16628. }
  16629. });
  16630. this.walk(tw);
  16631. });
  16632. /***********************************************************************
  16633. A JavaScript tokenizer / parser / beautifier / compressor.
  16634. https://github.com/mishoo/UglifyJS2
  16635. -------------------------------- (C) ---------------------------------
  16636. Author: Mihai Bazon
  16637. <mihai.bazon@gmail.com>
  16638. http://mihai.bazon.net/blog
  16639. Distributed under the BSD license:
  16640. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  16641. Redistribution and use in source and binary forms, with or without
  16642. modification, are permitted provided that the following conditions
  16643. are met:
  16644. * Redistributions of source code must retain the above
  16645. copyright notice, this list of conditions and the following
  16646. disclaimer.
  16647. * Redistributions in binary form must reproduce the above
  16648. copyright notice, this list of conditions and the following
  16649. disclaimer in the documentation and/or other materials
  16650. provided with the distribution.
  16651. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  16652. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  16653. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  16654. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  16655. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  16656. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  16657. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  16658. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  16659. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  16660. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  16661. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  16662. SUCH DAMAGE.
  16663. ***********************************************************************/
  16664. "use strict";
  16665. var EXPECT_DIRECTIVE = /^$|[;{][\s\n]*$/;
  16666. function is_some_comments(comment) {
  16667. // multiline comment
  16668. return comment.type == "comment2" && /@preserve|@license|@cc_on/i.test(comment.value);
  16669. }
  16670. function OutputStream(options) {
  16671. options = defaults(options, {
  16672. ascii_only : false,
  16673. beautify : false,
  16674. bracketize : false,
  16675. comments : false,
  16676. indent_level : 4,
  16677. indent_start : 0,
  16678. inline_script : true,
  16679. keep_quoted_props: false,
  16680. max_line_len : false,
  16681. preamble : null,
  16682. preserve_line : false,
  16683. quote_keys : false,
  16684. quote_style : 0,
  16685. screw_ie8 : true,
  16686. semicolons : true,
  16687. shebang : true,
  16688. source_map : null,
  16689. space_colon : true,
  16690. unescape_regexps : false,
  16691. width : 80,
  16692. wrap_iife : false,
  16693. }, true);
  16694. // Convert comment option to RegExp if neccessary and set up comments filter
  16695. var comment_filter = return_false; // Default case, throw all comments away
  16696. if (options.comments) {
  16697. var comments = options.comments;
  16698. if (typeof options.comments === "string" && /^\/.*\/[a-zA-Z]*$/.test(options.comments)) {
  16699. var regex_pos = options.comments.lastIndexOf("/");
  16700. comments = new RegExp(
  16701. options.comments.substr(1, regex_pos - 1),
  16702. options.comments.substr(regex_pos + 1)
  16703. );
  16704. }
  16705. if (comments instanceof RegExp) {
  16706. comment_filter = function(comment) {
  16707. return comment.type != "comment5" && comments.test(comment.value);
  16708. };
  16709. }
  16710. else if (typeof comments === "function") {
  16711. comment_filter = function(comment) {
  16712. return comment.type != "comment5" && comments(this, comment);
  16713. };
  16714. }
  16715. else if (comments === "some") {
  16716. comment_filter = is_some_comments;
  16717. } else { // NOTE includes "all" option
  16718. comment_filter = return_true;
  16719. }
  16720. }
  16721. var indentation = 0;
  16722. var current_col = 0;
  16723. var current_line = 1;
  16724. var current_pos = 0;
  16725. var OUTPUT = "";
  16726. function to_ascii(str, identifier) {
  16727. return str.replace(/[\u0000-\u001f\u007f-\uffff]/g, function(ch) {
  16728. var code = ch.charCodeAt(0).toString(16);
  16729. if (code.length <= 2 && !identifier) {
  16730. while (code.length < 2) code = "0" + code;
  16731. return "\\x" + code;
  16732. } else {
  16733. while (code.length < 4) code = "0" + code;
  16734. return "\\u" + code;
  16735. }
  16736. });
  16737. };
  16738. function make_string(str, quote) {
  16739. var dq = 0, sq = 0;
  16740. str = str.replace(/[\\\b\f\n\r\v\t\x22\x27\u2028\u2029\0\ufeff]/g,
  16741. function(s, i){
  16742. switch (s) {
  16743. case '"': ++dq; return '"';
  16744. case "'": ++sq; return "'";
  16745. case "\\": return "\\\\";
  16746. case "\n": return "\\n";
  16747. case "\r": return "\\r";
  16748. case "\t": return "\\t";
  16749. case "\b": return "\\b";
  16750. case "\f": return "\\f";
  16751. case "\x0B": return options.screw_ie8 ? "\\v" : "\\x0B";
  16752. case "\u2028": return "\\u2028";
  16753. case "\u2029": return "\\u2029";
  16754. case "\ufeff": return "\\ufeff";
  16755. case "\0":
  16756. return /[0-7]/.test(str.charAt(i+1)) ? "\\x00" : "\\0";
  16757. }
  16758. return s;
  16759. });
  16760. function quote_single() {
  16761. return "'" + str.replace(/\x27/g, "\\'") + "'";
  16762. }
  16763. function quote_double() {
  16764. return '"' + str.replace(/\x22/g, '\\"') + '"';
  16765. }
  16766. if (options.ascii_only) str = to_ascii(str);
  16767. switch (options.quote_style) {
  16768. case 1:
  16769. return quote_single();
  16770. case 2:
  16771. return quote_double();
  16772. case 3:
  16773. return quote == "'" ? quote_single() : quote_double();
  16774. default:
  16775. return dq > sq ? quote_single() : quote_double();
  16776. }
  16777. };
  16778. function encode_string(str, quote) {
  16779. var ret = make_string(str, quote);
  16780. if (options.inline_script) {
  16781. ret = ret.replace(/<\x2fscript([>\/\t\n\f\r ])/gi, "<\\/script$1");
  16782. ret = ret.replace(/\x3c!--/g, "\\x3c!--");
  16783. ret = ret.replace(/--\x3e/g, "--\\x3e");
  16784. }
  16785. return ret;
  16786. };
  16787. function make_name(name) {
  16788. name = name.toString();
  16789. if (options.ascii_only)
  16790. name = to_ascii(name, true);
  16791. return name;
  16792. };
  16793. function make_indent(back) {
  16794. return repeat_string(" ", options.indent_start + indentation - back * options.indent_level);
  16795. };
  16796. /* -----[ beautification/minification ]----- */
  16797. var might_need_space = false;
  16798. var might_need_semicolon = false;
  16799. var might_add_newline = 0;
  16800. var last = "";
  16801. var ensure_line_len = options.max_line_len ? function() {
  16802. if (current_col > options.max_line_len) {
  16803. if (might_add_newline) {
  16804. var left = OUTPUT.slice(0, might_add_newline);
  16805. var right = OUTPUT.slice(might_add_newline);
  16806. OUTPUT = left + "\n" + right;
  16807. current_line++;
  16808. current_pos++;
  16809. current_col = right.length;
  16810. }
  16811. if (current_col > options.max_line_len) {
  16812. AST_Node.warn("Output exceeds {max_line_len} characters", options);
  16813. }
  16814. }
  16815. might_add_newline = 0;
  16816. } : noop;
  16817. var requireSemicolonChars = makePredicate("( [ + * / - , .");
  16818. function print(str) {
  16819. str = String(str);
  16820. var ch = str.charAt(0);
  16821. var prev = last.charAt(last.length - 1);
  16822. if (might_need_semicolon) {
  16823. might_need_semicolon = false;
  16824. if (prev == ":" && ch == "}" || (!ch || ";}".indexOf(ch) < 0) && prev != ";") {
  16825. if (options.semicolons || requireSemicolonChars(ch)) {
  16826. OUTPUT += ";";
  16827. current_col++;
  16828. current_pos++;
  16829. } else {
  16830. ensure_line_len();
  16831. OUTPUT += "\n";
  16832. current_pos++;
  16833. current_line++;
  16834. current_col = 0;
  16835. if (/^\s+$/.test(str)) {
  16836. // reset the semicolon flag, since we didn't print one
  16837. // now and might still have to later
  16838. might_need_semicolon = true;
  16839. }
  16840. }
  16841. if (!options.beautify)
  16842. might_need_space = false;
  16843. }
  16844. }
  16845. if (!options.beautify && options.preserve_line && stack[stack.length - 1]) {
  16846. var target_line = stack[stack.length - 1].start.line;
  16847. while (current_line < target_line) {
  16848. ensure_line_len();
  16849. OUTPUT += "\n";
  16850. current_pos++;
  16851. current_line++;
  16852. current_col = 0;
  16853. might_need_space = false;
  16854. }
  16855. }
  16856. if (might_need_space) {
  16857. if ((is_identifier_char(prev)
  16858. && (is_identifier_char(ch) || ch == "\\"))
  16859. || (ch == "/" && ch == prev)
  16860. || ((ch == "+" || ch == "-") && ch == last))
  16861. {
  16862. OUTPUT += " ";
  16863. current_col++;
  16864. current_pos++;
  16865. }
  16866. might_need_space = false;
  16867. }
  16868. OUTPUT += str;
  16869. current_pos += str.length;
  16870. var a = str.split(/\r?\n/), n = a.length - 1;
  16871. current_line += n;
  16872. current_col += a[0].length;
  16873. if (n > 0) {
  16874. ensure_line_len();
  16875. current_col = a[n].length;
  16876. }
  16877. last = str;
  16878. };
  16879. var space = options.beautify ? function() {
  16880. print(" ");
  16881. } : function() {
  16882. might_need_space = true;
  16883. };
  16884. var indent = options.beautify ? function(half) {
  16885. if (options.beautify) {
  16886. print(make_indent(half ? 0.5 : 0));
  16887. }
  16888. } : noop;
  16889. var with_indent = options.beautify ? function(col, cont) {
  16890. if (col === true) col = next_indent();
  16891. var save_indentation = indentation;
  16892. indentation = col;
  16893. var ret = cont();
  16894. indentation = save_indentation;
  16895. return ret;
  16896. } : function(col, cont) { return cont() };
  16897. var newline = options.beautify ? function() {
  16898. print("\n");
  16899. } : options.max_line_len ? function() {
  16900. ensure_line_len();
  16901. might_add_newline = OUTPUT.length;
  16902. } : noop;
  16903. var semicolon = options.beautify ? function() {
  16904. print(";");
  16905. } : function() {
  16906. might_need_semicolon = true;
  16907. };
  16908. function force_semicolon() {
  16909. might_need_semicolon = false;
  16910. print(";");
  16911. };
  16912. function next_indent() {
  16913. return indentation + options.indent_level;
  16914. };
  16915. function with_block(cont) {
  16916. var ret;
  16917. print("{");
  16918. newline();
  16919. with_indent(next_indent(), function(){
  16920. ret = cont();
  16921. });
  16922. indent();
  16923. print("}");
  16924. return ret;
  16925. };
  16926. function with_parens(cont) {
  16927. print("(");
  16928. //XXX: still nice to have that for argument lists
  16929. //var ret = with_indent(current_col, cont);
  16930. var ret = cont();
  16931. print(")");
  16932. return ret;
  16933. };
  16934. function with_square(cont) {
  16935. print("[");
  16936. //var ret = with_indent(current_col, cont);
  16937. var ret = cont();
  16938. print("]");
  16939. return ret;
  16940. };
  16941. function comma() {
  16942. print(",");
  16943. space();
  16944. };
  16945. function colon() {
  16946. print(":");
  16947. if (options.space_colon) space();
  16948. };
  16949. var add_mapping = options.source_map ? function(token, name) {
  16950. try {
  16951. if (token) options.source_map.add(
  16952. token.file || "?",
  16953. current_line, current_col,
  16954. token.line, token.col,
  16955. (!name && token.type == "name") ? token.value : name
  16956. );
  16957. } catch(ex) {
  16958. AST_Node.warn("Couldn't figure out mapping for {file}:{line},{col} → {cline},{ccol} [{name}]", {
  16959. file: token.file,
  16960. line: token.line,
  16961. col: token.col,
  16962. cline: current_line,
  16963. ccol: current_col,
  16964. name: name || ""
  16965. })
  16966. }
  16967. } : noop;
  16968. function get() {
  16969. if (might_add_newline) {
  16970. ensure_line_len();
  16971. }
  16972. return OUTPUT;
  16973. };
  16974. var stack = [];
  16975. return {
  16976. get : get,
  16977. toString : get,
  16978. indent : indent,
  16979. indentation : function() { return indentation },
  16980. current_width : function() { return current_col - indentation },
  16981. should_break : function() { return options.width && this.current_width() >= options.width },
  16982. newline : newline,
  16983. print : print,
  16984. space : space,
  16985. comma : comma,
  16986. colon : colon,
  16987. last : function() { return last },
  16988. semicolon : semicolon,
  16989. force_semicolon : force_semicolon,
  16990. to_ascii : to_ascii,
  16991. print_name : function(name) { print(make_name(name)) },
  16992. print_string : function(str, quote, escape_directive) {
  16993. var encoded = encode_string(str, quote);
  16994. if (escape_directive === true && encoded.indexOf("\\") === -1) {
  16995. // Insert semicolons to break directive prologue
  16996. if (!EXPECT_DIRECTIVE.test(OUTPUT)) {
  16997. force_semicolon();
  16998. }
  16999. force_semicolon();
  17000. }
  17001. print(encoded);
  17002. },
  17003. encode_string : encode_string,
  17004. next_indent : next_indent,
  17005. with_indent : with_indent,
  17006. with_block : with_block,
  17007. with_parens : with_parens,
  17008. with_square : with_square,
  17009. add_mapping : add_mapping,
  17010. option : function(opt) { return options[opt] },
  17011. comment_filter : comment_filter,
  17012. line : function() { return current_line },
  17013. col : function() { return current_col },
  17014. pos : function() { return current_pos },
  17015. push_node : function(node) { stack.push(node) },
  17016. pop_node : function() { return stack.pop() },
  17017. parent : function(n) {
  17018. return stack[stack.length - 2 - (n || 0)];
  17019. }
  17020. };
  17021. };
  17022. /* -----[ code generators ]----- */
  17023. (function(){
  17024. /* -----[ utils ]----- */
  17025. function DEFPRINT(nodetype, generator) {
  17026. nodetype.DEFMETHOD("_codegen", generator);
  17027. };
  17028. var use_asm = false;
  17029. var in_directive = false;
  17030. AST_Node.DEFMETHOD("print", function(stream, force_parens){
  17031. var self = this, generator = self._codegen, prev_use_asm = use_asm;
  17032. if (self instanceof AST_Directive && self.value == "use asm" && stream.parent() instanceof AST_Scope) {
  17033. use_asm = true;
  17034. }
  17035. function doit() {
  17036. self.add_comments(stream);
  17037. self.add_source_map(stream);
  17038. generator(self, stream);
  17039. }
  17040. stream.push_node(self);
  17041. if (force_parens || self.needs_parens(stream)) {
  17042. stream.with_parens(doit);
  17043. } else {
  17044. doit();
  17045. }
  17046. stream.pop_node();
  17047. if (self instanceof AST_Scope) {
  17048. use_asm = prev_use_asm;
  17049. }
  17050. });
  17051. AST_Node.DEFMETHOD("print_to_string", function(options){
  17052. var s = OutputStream(options);
  17053. if (!options) s._readonly = true;
  17054. this.print(s);
  17055. return s.get();
  17056. });
  17057. /* -----[ comments ]----- */
  17058. AST_Node.DEFMETHOD("add_comments", function(output){
  17059. if (output._readonly) return;
  17060. var self = this;
  17061. var start = self.start;
  17062. if (start && !start._comments_dumped) {
  17063. start._comments_dumped = true;
  17064. var comments = start.comments_before || [];
  17065. // XXX: ugly fix for https://github.com/mishoo/UglifyJS2/issues/112
  17066. // and https://github.com/mishoo/UglifyJS2/issues/372
  17067. if (self instanceof AST_Exit && self.value) {
  17068. self.value.walk(new TreeWalker(function(node){
  17069. if (node.start && node.start.comments_before) {
  17070. comments = comments.concat(node.start.comments_before);
  17071. node.start.comments_before = [];
  17072. }
  17073. if (node instanceof AST_Function ||
  17074. node instanceof AST_Array ||
  17075. node instanceof AST_Object)
  17076. {
  17077. return true; // don't go inside.
  17078. }
  17079. }));
  17080. }
  17081. if (output.pos() == 0) {
  17082. if (comments.length > 0 && output.option("shebang") && comments[0].type == "comment5") {
  17083. output.print("#!" + comments.shift().value + "\n");
  17084. output.indent();
  17085. }
  17086. var preamble = output.option("preamble");
  17087. if (preamble) {
  17088. output.print(preamble.replace(/\r\n?|[\n\u2028\u2029]|\s*$/g, "\n"));
  17089. }
  17090. }
  17091. comments = comments.filter(output.comment_filter, self);
  17092. // Keep single line comments after nlb, after nlb
  17093. if (!output.option("beautify") && comments.length > 0 &&
  17094. /comment[134]/.test(comments[0].type) &&
  17095. output.col() !== 0 && comments[0].nlb)
  17096. {
  17097. output.print("\n");
  17098. }
  17099. comments.forEach(function(c){
  17100. if (/comment[134]/.test(c.type)) {
  17101. output.print("//" + c.value + "\n");
  17102. output.indent();
  17103. }
  17104. else if (c.type == "comment2") {
  17105. output.print("/*" + c.value + "*/");
  17106. if (start.nlb) {
  17107. output.print("\n");
  17108. output.indent();
  17109. } else {
  17110. output.space();
  17111. }
  17112. }
  17113. });
  17114. }
  17115. });
  17116. /* -----[ PARENTHESES ]----- */
  17117. function PARENS(nodetype, func) {
  17118. if (Array.isArray(nodetype)) {
  17119. nodetype.forEach(function(nodetype){
  17120. PARENS(nodetype, func);
  17121. });
  17122. } else {
  17123. nodetype.DEFMETHOD("needs_parens", func);
  17124. }
  17125. };
  17126. PARENS(AST_Node, function(){
  17127. return false;
  17128. });
  17129. // a function expression needs parens around it when it's provably
  17130. // the first token to appear in a statement.
  17131. PARENS(AST_Function, function(output){
  17132. if (first_in_statement(output)) {
  17133. return true;
  17134. }
  17135. if (output.option('wrap_iife')) {
  17136. var p = output.parent();
  17137. return p instanceof AST_Call && p.expression === this;
  17138. }
  17139. return false;
  17140. });
  17141. // same goes for an object literal, because otherwise it would be
  17142. // interpreted as a block of code.
  17143. PARENS(AST_Object, function(output){
  17144. return first_in_statement(output);
  17145. });
  17146. PARENS(AST_Unary, function(output){
  17147. var p = output.parent();
  17148. return p instanceof AST_PropAccess && p.expression === this
  17149. || p instanceof AST_Call && p.expression === this;
  17150. });
  17151. PARENS(AST_Seq, function(output){
  17152. var p = output.parent();
  17153. return p instanceof AST_Call // (foo, bar)() or foo(1, (2, 3), 4)
  17154. || p instanceof AST_Unary // !(foo, bar, baz)
  17155. || p instanceof AST_Binary // 1 + (2, 3) + 4 ==> 8
  17156. || p instanceof AST_VarDef // var a = (1, 2), b = a + a; ==> b == 4
  17157. || p instanceof AST_PropAccess // (1, {foo:2}).foo or (1, {foo:2})["foo"] ==> 2
  17158. || p instanceof AST_Array // [ 1, (2, 3), 4 ] ==> [ 1, 3, 4 ]
  17159. || p instanceof AST_ObjectProperty // { foo: (1, 2) }.foo ==> 2
  17160. || p instanceof AST_Conditional /* (false, true) ? (a = 10, b = 20) : (c = 30)
  17161. * ==> 20 (side effect, set a := 10 and b := 20) */
  17162. ;
  17163. });
  17164. PARENS(AST_Binary, function(output){
  17165. var p = output.parent();
  17166. // (foo && bar)()
  17167. if (p instanceof AST_Call && p.expression === this)
  17168. return true;
  17169. // typeof (foo && bar)
  17170. if (p instanceof AST_Unary)
  17171. return true;
  17172. // (foo && bar)["prop"], (foo && bar).prop
  17173. if (p instanceof AST_PropAccess && p.expression === this)
  17174. return true;
  17175. // this deals with precedence: 3 * (2 + 1)
  17176. if (p instanceof AST_Binary) {
  17177. var po = p.operator, pp = PRECEDENCE[po];
  17178. var so = this.operator, sp = PRECEDENCE[so];
  17179. if (pp > sp
  17180. || (pp == sp
  17181. && this === p.right)) {
  17182. return true;
  17183. }
  17184. }
  17185. });
  17186. PARENS(AST_PropAccess, function(output){
  17187. var p = output.parent();
  17188. if (p instanceof AST_New && p.expression === this) {
  17189. // i.e. new (foo.bar().baz)
  17190. //
  17191. // if there's one call into this subtree, then we need
  17192. // parens around it too, otherwise the call will be
  17193. // interpreted as passing the arguments to the upper New
  17194. // expression.
  17195. try {
  17196. this.walk(new TreeWalker(function(node){
  17197. if (node instanceof AST_Call) throw p;
  17198. }));
  17199. } catch(ex) {
  17200. if (ex !== p) throw ex;
  17201. return true;
  17202. }
  17203. }
  17204. });
  17205. PARENS(AST_Call, function(output){
  17206. var p = output.parent(), p1;
  17207. if (p instanceof AST_New && p.expression === this)
  17208. return true;
  17209. // workaround for Safari bug.
  17210. // https://bugs.webkit.org/show_bug.cgi?id=123506
  17211. return this.expression instanceof AST_Function
  17212. && p instanceof AST_PropAccess
  17213. && p.expression === this
  17214. && (p1 = output.parent(1)) instanceof AST_Assign
  17215. && p1.left === p;
  17216. });
  17217. PARENS(AST_New, function(output){
  17218. var p = output.parent();
  17219. if (!need_constructor_parens(this, output)
  17220. && (p instanceof AST_PropAccess // (new Date).getTime(), (new Date)["getTime"]()
  17221. || p instanceof AST_Call && p.expression === this)) // (new foo)(bar)
  17222. return true;
  17223. });
  17224. PARENS(AST_Number, function(output){
  17225. var p = output.parent();
  17226. if (p instanceof AST_PropAccess && p.expression === this) {
  17227. var value = this.getValue();
  17228. if (value < 0 || /^0/.test(make_num(value))) {
  17229. return true;
  17230. }
  17231. }
  17232. });
  17233. PARENS([ AST_Assign, AST_Conditional ], function (output){
  17234. var p = output.parent();
  17235. // !(a = false) → true
  17236. if (p instanceof AST_Unary)
  17237. return true;
  17238. // 1 + (a = 2) + 3 → 6, side effect setting a = 2
  17239. if (p instanceof AST_Binary && !(p instanceof AST_Assign))
  17240. return true;
  17241. // (a = func)() —or— new (a = Object)()
  17242. if (p instanceof AST_Call && p.expression === this)
  17243. return true;
  17244. // (a = foo) ? bar : baz
  17245. if (p instanceof AST_Conditional && p.condition === this)
  17246. return true;
  17247. // (a = foo)["prop"] —or— (a = foo).prop
  17248. if (p instanceof AST_PropAccess && p.expression === this)
  17249. return true;
  17250. });
  17251. /* -----[ PRINTERS ]----- */
  17252. DEFPRINT(AST_Directive, function(self, output){
  17253. output.print_string(self.value, self.quote);
  17254. output.semicolon();
  17255. });
  17256. DEFPRINT(AST_Debugger, function(self, output){
  17257. output.print("debugger");
  17258. output.semicolon();
  17259. });
  17260. /* -----[ statements ]----- */
  17261. function display_body(body, is_toplevel, output, allow_directives) {
  17262. var last = body.length - 1;
  17263. in_directive = allow_directives;
  17264. body.forEach(function(stmt, i){
  17265. if (in_directive === true && !(stmt instanceof AST_Directive ||
  17266. stmt instanceof AST_EmptyStatement ||
  17267. (stmt instanceof AST_SimpleStatement && stmt.body instanceof AST_String)
  17268. )) {
  17269. in_directive = false;
  17270. }
  17271. if (!(stmt instanceof AST_EmptyStatement)) {
  17272. output.indent();
  17273. stmt.print(output);
  17274. if (!(i == last && is_toplevel)) {
  17275. output.newline();
  17276. if (is_toplevel) output.newline();
  17277. }
  17278. }
  17279. if (in_directive === true &&
  17280. stmt instanceof AST_SimpleStatement &&
  17281. stmt.body instanceof AST_String
  17282. ) {
  17283. in_directive = false;
  17284. }
  17285. });
  17286. in_directive = false;
  17287. };
  17288. AST_StatementWithBody.DEFMETHOD("_do_print_body", function(output){
  17289. force_statement(this.body, output);
  17290. });
  17291. DEFPRINT(AST_Statement, function(self, output){
  17292. self.body.print(output);
  17293. output.semicolon();
  17294. });
  17295. DEFPRINT(AST_Toplevel, function(self, output){
  17296. display_body(self.body, true, output, true);
  17297. output.print("");
  17298. });
  17299. DEFPRINT(AST_LabeledStatement, function(self, output){
  17300. self.label.print(output);
  17301. output.colon();
  17302. self.body.print(output);
  17303. });
  17304. DEFPRINT(AST_SimpleStatement, function(self, output){
  17305. self.body.print(output);
  17306. output.semicolon();
  17307. });
  17308. function print_bracketed(body, output, allow_directives) {
  17309. if (body.length > 0) output.with_block(function(){
  17310. display_body(body, false, output, allow_directives);
  17311. });
  17312. else output.print("{}");
  17313. };
  17314. DEFPRINT(AST_BlockStatement, function(self, output){
  17315. print_bracketed(self.body, output);
  17316. });
  17317. DEFPRINT(AST_EmptyStatement, function(self, output){
  17318. output.semicolon();
  17319. });
  17320. DEFPRINT(AST_Do, function(self, output){
  17321. output.print("do");
  17322. output.space();
  17323. make_block(self.body, output);
  17324. output.space();
  17325. output.print("while");
  17326. output.space();
  17327. output.with_parens(function(){
  17328. self.condition.print(output);
  17329. });
  17330. output.semicolon();
  17331. });
  17332. DEFPRINT(AST_While, function(self, output){
  17333. output.print("while");
  17334. output.space();
  17335. output.with_parens(function(){
  17336. self.condition.print(output);
  17337. });
  17338. output.space();
  17339. self._do_print_body(output);
  17340. });
  17341. DEFPRINT(AST_For, function(self, output){
  17342. output.print("for");
  17343. output.space();
  17344. output.with_parens(function(){
  17345. if (self.init) {
  17346. if (self.init instanceof AST_Definitions) {
  17347. self.init.print(output);
  17348. } else {
  17349. parenthesize_for_noin(self.init, output, true);
  17350. }
  17351. output.print(";");
  17352. output.space();
  17353. } else {
  17354. output.print(";");
  17355. }
  17356. if (self.condition) {
  17357. self.condition.print(output);
  17358. output.print(";");
  17359. output.space();
  17360. } else {
  17361. output.print(";");
  17362. }
  17363. if (self.step) {
  17364. self.step.print(output);
  17365. }
  17366. });
  17367. output.space();
  17368. self._do_print_body(output);
  17369. });
  17370. DEFPRINT(AST_ForIn, function(self, output){
  17371. output.print("for");
  17372. output.space();
  17373. output.with_parens(function(){
  17374. self.init.print(output);
  17375. output.space();
  17376. output.print("in");
  17377. output.space();
  17378. self.object.print(output);
  17379. });
  17380. output.space();
  17381. self._do_print_body(output);
  17382. });
  17383. DEFPRINT(AST_With, function(self, output){
  17384. output.print("with");
  17385. output.space();
  17386. output.with_parens(function(){
  17387. self.expression.print(output);
  17388. });
  17389. output.space();
  17390. self._do_print_body(output);
  17391. });
  17392. /* -----[ functions ]----- */
  17393. AST_Lambda.DEFMETHOD("_do_print", function(output, nokeyword){
  17394. var self = this;
  17395. if (!nokeyword) {
  17396. output.print("function");
  17397. }
  17398. if (self.name) {
  17399. output.space();
  17400. self.name.print(output);
  17401. }
  17402. output.with_parens(function(){
  17403. self.argnames.forEach(function(arg, i){
  17404. if (i) output.comma();
  17405. arg.print(output);
  17406. });
  17407. });
  17408. output.space();
  17409. print_bracketed(self.body, output, true);
  17410. });
  17411. DEFPRINT(AST_Lambda, function(self, output){
  17412. self._do_print(output);
  17413. });
  17414. /* -----[ exits ]----- */
  17415. AST_Exit.DEFMETHOD("_do_print", function(output, kind){
  17416. output.print(kind);
  17417. if (this.value) {
  17418. output.space();
  17419. this.value.print(output);
  17420. }
  17421. output.semicolon();
  17422. });
  17423. DEFPRINT(AST_Return, function(self, output){
  17424. self._do_print(output, "return");
  17425. });
  17426. DEFPRINT(AST_Throw, function(self, output){
  17427. self._do_print(output, "throw");
  17428. });
  17429. /* -----[ loop control ]----- */
  17430. AST_LoopControl.DEFMETHOD("_do_print", function(output, kind){
  17431. output.print(kind);
  17432. if (this.label) {
  17433. output.space();
  17434. this.label.print(output);
  17435. }
  17436. output.semicolon();
  17437. });
  17438. DEFPRINT(AST_Break, function(self, output){
  17439. self._do_print(output, "break");
  17440. });
  17441. DEFPRINT(AST_Continue, function(self, output){
  17442. self._do_print(output, "continue");
  17443. });
  17444. /* -----[ if ]----- */
  17445. function make_then(self, output) {
  17446. var b = self.body;
  17447. if (output.option("bracketize")
  17448. || !output.option("screw_ie8") && b instanceof AST_Do)
  17449. return make_block(b, output);
  17450. // The squeezer replaces "block"-s that contain only a single
  17451. // statement with the statement itself; technically, the AST
  17452. // is correct, but this can create problems when we output an
  17453. // IF having an ELSE clause where the THEN clause ends in an
  17454. // IF *without* an ELSE block (then the outer ELSE would refer
  17455. // to the inner IF). This function checks for this case and
  17456. // adds the block brackets if needed.
  17457. if (!b) return output.force_semicolon();
  17458. while (true) {
  17459. if (b instanceof AST_If) {
  17460. if (!b.alternative) {
  17461. make_block(self.body, output);
  17462. return;
  17463. }
  17464. b = b.alternative;
  17465. }
  17466. else if (b instanceof AST_StatementWithBody) {
  17467. b = b.body;
  17468. }
  17469. else break;
  17470. }
  17471. force_statement(self.body, output);
  17472. };
  17473. DEFPRINT(AST_If, function(self, output){
  17474. output.print("if");
  17475. output.space();
  17476. output.with_parens(function(){
  17477. self.condition.print(output);
  17478. });
  17479. output.space();
  17480. if (self.alternative) {
  17481. make_then(self, output);
  17482. output.space();
  17483. output.print("else");
  17484. output.space();
  17485. if (self.alternative instanceof AST_If)
  17486. self.alternative.print(output);
  17487. else
  17488. force_statement(self.alternative, output);
  17489. } else {
  17490. self._do_print_body(output);
  17491. }
  17492. });
  17493. /* -----[ switch ]----- */
  17494. DEFPRINT(AST_Switch, function(self, output){
  17495. output.print("switch");
  17496. output.space();
  17497. output.with_parens(function(){
  17498. self.expression.print(output);
  17499. });
  17500. output.space();
  17501. var last = self.body.length - 1;
  17502. if (last < 0) output.print("{}");
  17503. else output.with_block(function(){
  17504. self.body.forEach(function(branch, i){
  17505. output.indent(true);
  17506. branch.print(output);
  17507. if (i < last && branch.body.length > 0)
  17508. output.newline();
  17509. });
  17510. });
  17511. });
  17512. AST_SwitchBranch.DEFMETHOD("_do_print_body", function(output){
  17513. output.newline();
  17514. this.body.forEach(function(stmt){
  17515. output.indent();
  17516. stmt.print(output);
  17517. output.newline();
  17518. });
  17519. });
  17520. DEFPRINT(AST_Default, function(self, output){
  17521. output.print("default:");
  17522. self._do_print_body(output);
  17523. });
  17524. DEFPRINT(AST_Case, function(self, output){
  17525. output.print("case");
  17526. output.space();
  17527. self.expression.print(output);
  17528. output.print(":");
  17529. self._do_print_body(output);
  17530. });
  17531. /* -----[ exceptions ]----- */
  17532. DEFPRINT(AST_Try, function(self, output){
  17533. output.print("try");
  17534. output.space();
  17535. print_bracketed(self.body, output);
  17536. if (self.bcatch) {
  17537. output.space();
  17538. self.bcatch.print(output);
  17539. }
  17540. if (self.bfinally) {
  17541. output.space();
  17542. self.bfinally.print(output);
  17543. }
  17544. });
  17545. DEFPRINT(AST_Catch, function(self, output){
  17546. output.print("catch");
  17547. output.space();
  17548. output.with_parens(function(){
  17549. self.argname.print(output);
  17550. });
  17551. output.space();
  17552. print_bracketed(self.body, output);
  17553. });
  17554. DEFPRINT(AST_Finally, function(self, output){
  17555. output.print("finally");
  17556. output.space();
  17557. print_bracketed(self.body, output);
  17558. });
  17559. /* -----[ var/const ]----- */
  17560. AST_Definitions.DEFMETHOD("_do_print", function(output, kind){
  17561. output.print(kind);
  17562. output.space();
  17563. this.definitions.forEach(function(def, i){
  17564. if (i) output.comma();
  17565. def.print(output);
  17566. });
  17567. var p = output.parent();
  17568. var in_for = p instanceof AST_For || p instanceof AST_ForIn;
  17569. var avoid_semicolon = in_for && p.init === this;
  17570. if (!avoid_semicolon)
  17571. output.semicolon();
  17572. });
  17573. DEFPRINT(AST_Var, function(self, output){
  17574. self._do_print(output, "var");
  17575. });
  17576. DEFPRINT(AST_Const, function(self, output){
  17577. self._do_print(output, "const");
  17578. });
  17579. function parenthesize_for_noin(node, output, noin) {
  17580. if (!noin) node.print(output);
  17581. else try {
  17582. // need to take some precautions here:
  17583. // https://github.com/mishoo/UglifyJS2/issues/60
  17584. node.walk(new TreeWalker(function(node){
  17585. if (node instanceof AST_Binary && node.operator == "in")
  17586. throw output;
  17587. }));
  17588. node.print(output);
  17589. } catch(ex) {
  17590. if (ex !== output) throw ex;
  17591. node.print(output, true);
  17592. }
  17593. };
  17594. DEFPRINT(AST_VarDef, function(self, output){
  17595. self.name.print(output);
  17596. if (self.value) {
  17597. output.space();
  17598. output.print("=");
  17599. output.space();
  17600. var p = output.parent(1);
  17601. var noin = p instanceof AST_For || p instanceof AST_ForIn;
  17602. parenthesize_for_noin(self.value, output, noin);
  17603. }
  17604. });
  17605. /* -----[ other expressions ]----- */
  17606. DEFPRINT(AST_Call, function(self, output){
  17607. self.expression.print(output);
  17608. if (self instanceof AST_New && !need_constructor_parens(self, output))
  17609. return;
  17610. output.with_parens(function(){
  17611. self.args.forEach(function(expr, i){
  17612. if (i) output.comma();
  17613. expr.print(output);
  17614. });
  17615. });
  17616. });
  17617. DEFPRINT(AST_New, function(self, output){
  17618. output.print("new");
  17619. output.space();
  17620. AST_Call.prototype._codegen(self, output);
  17621. });
  17622. AST_Seq.DEFMETHOD("_do_print", function(output){
  17623. this.car.print(output);
  17624. if (this.cdr) {
  17625. output.comma();
  17626. if (output.should_break()) {
  17627. output.newline();
  17628. output.indent();
  17629. }
  17630. this.cdr.print(output);
  17631. }
  17632. });
  17633. DEFPRINT(AST_Seq, function(self, output){
  17634. self._do_print(output);
  17635. // var p = output.parent();
  17636. // if (p instanceof AST_Statement) {
  17637. // output.with_indent(output.next_indent(), function(){
  17638. // self._do_print(output);
  17639. // });
  17640. // } else {
  17641. // self._do_print(output);
  17642. // }
  17643. });
  17644. DEFPRINT(AST_Dot, function(self, output){
  17645. var expr = self.expression;
  17646. expr.print(output);
  17647. if (expr instanceof AST_Number && expr.getValue() >= 0) {
  17648. if (!/[xa-f.)]/i.test(output.last())) {
  17649. output.print(".");
  17650. }
  17651. }
  17652. output.print(".");
  17653. // the name after dot would be mapped about here.
  17654. output.add_mapping(self.end);
  17655. output.print_name(self.property);
  17656. });
  17657. DEFPRINT(AST_Sub, function(self, output){
  17658. self.expression.print(output);
  17659. output.print("[");
  17660. self.property.print(output);
  17661. output.print("]");
  17662. });
  17663. DEFPRINT(AST_UnaryPrefix, function(self, output){
  17664. var op = self.operator;
  17665. output.print(op);
  17666. if (/^[a-z]/i.test(op)
  17667. || (/[+-]$/.test(op)
  17668. && self.expression instanceof AST_UnaryPrefix
  17669. && /^[+-]/.test(self.expression.operator))) {
  17670. output.space();
  17671. }
  17672. self.expression.print(output);
  17673. });
  17674. DEFPRINT(AST_UnaryPostfix, function(self, output){
  17675. self.expression.print(output);
  17676. output.print(self.operator);
  17677. });
  17678. DEFPRINT(AST_Binary, function(self, output){
  17679. var op = self.operator;
  17680. self.left.print(output);
  17681. if (op[0] == ">" /* ">>" ">>>" ">" ">=" */
  17682. && self.left instanceof AST_UnaryPostfix
  17683. && self.left.operator == "--") {
  17684. // space is mandatory to avoid outputting -->
  17685. output.print(" ");
  17686. } else {
  17687. // the space is optional depending on "beautify"
  17688. output.space();
  17689. }
  17690. output.print(op);
  17691. if ((op == "<" || op == "<<")
  17692. && self.right instanceof AST_UnaryPrefix
  17693. && self.right.operator == "!"
  17694. && self.right.expression instanceof AST_UnaryPrefix
  17695. && self.right.expression.operator == "--") {
  17696. // space is mandatory to avoid outputting <!--
  17697. output.print(" ");
  17698. } else {
  17699. // the space is optional depending on "beautify"
  17700. output.space();
  17701. }
  17702. self.right.print(output);
  17703. });
  17704. DEFPRINT(AST_Conditional, function(self, output){
  17705. self.condition.print(output);
  17706. output.space();
  17707. output.print("?");
  17708. output.space();
  17709. self.consequent.print(output);
  17710. output.space();
  17711. output.colon();
  17712. self.alternative.print(output);
  17713. });
  17714. /* -----[ literals ]----- */
  17715. DEFPRINT(AST_Array, function(self, output){
  17716. output.with_square(function(){
  17717. var a = self.elements, len = a.length;
  17718. if (len > 0) output.space();
  17719. a.forEach(function(exp, i){
  17720. if (i) output.comma();
  17721. exp.print(output);
  17722. // If the final element is a hole, we need to make sure it
  17723. // doesn't look like a trailing comma, by inserting an actual
  17724. // trailing comma.
  17725. if (i === len - 1 && exp instanceof AST_Hole)
  17726. output.comma();
  17727. });
  17728. if (len > 0) output.space();
  17729. });
  17730. });
  17731. DEFPRINT(AST_Object, function(self, output){
  17732. if (self.properties.length > 0) output.with_block(function(){
  17733. self.properties.forEach(function(prop, i){
  17734. if (i) {
  17735. output.print(",");
  17736. output.newline();
  17737. }
  17738. output.indent();
  17739. prop.print(output);
  17740. });
  17741. output.newline();
  17742. });
  17743. else output.print("{}");
  17744. });
  17745. function print_property_name(key, quote, output) {
  17746. if (output.option("quote_keys")) {
  17747. output.print_string(key + "");
  17748. } else if ((typeof key == "number"
  17749. || !output.option("beautify")
  17750. && +key + "" == key)
  17751. && parseFloat(key) >= 0) {
  17752. output.print(make_num(key));
  17753. } else if (RESERVED_WORDS(key) ? output.option("screw_ie8") : is_identifier_string(key)) {
  17754. if (quote && output.option("keep_quoted_props")) {
  17755. output.print_string(key, quote);
  17756. } else {
  17757. output.print_name(key);
  17758. }
  17759. } else {
  17760. output.print_string(key, quote);
  17761. }
  17762. }
  17763. DEFPRINT(AST_ObjectKeyVal, function(self, output){
  17764. print_property_name(self.key, self.quote, output);
  17765. output.colon();
  17766. self.value.print(output);
  17767. });
  17768. AST_ObjectProperty.DEFMETHOD("_print_getter_setter", function(type, output) {
  17769. output.print(type);
  17770. output.space();
  17771. print_property_name(this.key.name, this.quote, output);
  17772. this.value._do_print(output, true);
  17773. });
  17774. DEFPRINT(AST_ObjectSetter, function(self, output){
  17775. self._print_getter_setter("set", output);
  17776. });
  17777. DEFPRINT(AST_ObjectGetter, function(self, output){
  17778. self._print_getter_setter("get", output);
  17779. });
  17780. DEFPRINT(AST_Symbol, function(self, output){
  17781. var def = self.definition();
  17782. output.print_name(def ? def.mangled_name || def.name : self.name);
  17783. });
  17784. DEFPRINT(AST_Hole, noop);
  17785. DEFPRINT(AST_This, function(self, output){
  17786. output.print("this");
  17787. });
  17788. DEFPRINT(AST_Constant, function(self, output){
  17789. output.print(self.getValue());
  17790. });
  17791. DEFPRINT(AST_String, function(self, output){
  17792. output.print_string(self.getValue(), self.quote, in_directive);
  17793. });
  17794. DEFPRINT(AST_Number, function(self, output){
  17795. if (use_asm && self.start && self.start.raw != null) {
  17796. output.print(self.start.raw);
  17797. } else {
  17798. output.print(make_num(self.getValue()));
  17799. }
  17800. });
  17801. function regexp_safe_literal(code) {
  17802. return [
  17803. 0x5c , // \
  17804. 0x2f , // /
  17805. 0x2e , // .
  17806. 0x2b , // +
  17807. 0x2a , // *
  17808. 0x3f , // ?
  17809. 0x28 , // (
  17810. 0x29 , // )
  17811. 0x5b , // [
  17812. 0x5d , // ]
  17813. 0x7b , // {
  17814. 0x7d , // }
  17815. 0x24 , // $
  17816. 0x5e , // ^
  17817. 0x3a , // :
  17818. 0x7c , // |
  17819. 0x21 , // !
  17820. 0x0a , // \n
  17821. 0x0d , // \r
  17822. 0x00 , // \0
  17823. 0xfeff , // Unicode BOM
  17824. 0x2028 , // unicode "line separator"
  17825. 0x2029 , // unicode "paragraph separator"
  17826. ].indexOf(code) < 0;
  17827. };
  17828. DEFPRINT(AST_RegExp, function(self, output){
  17829. var str = self.getValue().toString();
  17830. if (output.option("ascii_only")) {
  17831. str = output.to_ascii(str);
  17832. } else if (output.option("unescape_regexps")) {
  17833. str = str.split("\\\\").map(function(str){
  17834. return str.replace(/\\u[0-9a-fA-F]{4}|\\x[0-9a-fA-F]{2}/g, function(s){
  17835. var code = parseInt(s.substr(2), 16);
  17836. return regexp_safe_literal(code) ? String.fromCharCode(code) : s;
  17837. });
  17838. }).join("\\\\");
  17839. }
  17840. output.print(str);
  17841. var p = output.parent();
  17842. if (p instanceof AST_Binary && /^in/.test(p.operator) && p.left === self)
  17843. output.print(" ");
  17844. });
  17845. function force_statement(stat, output) {
  17846. if (output.option("bracketize")) {
  17847. make_block(stat, output);
  17848. } else {
  17849. if (!stat || stat instanceof AST_EmptyStatement)
  17850. output.force_semicolon();
  17851. else
  17852. stat.print(output);
  17853. }
  17854. };
  17855. // self should be AST_New. decide if we want to show parens or not.
  17856. function need_constructor_parens(self, output) {
  17857. // Always print parentheses with arguments
  17858. if (self.args.length > 0) return true;
  17859. return output.option("beautify");
  17860. };
  17861. function best_of(a) {
  17862. var best = a[0], len = best.length;
  17863. for (var i = 1; i < a.length; ++i) {
  17864. if (a[i].length < len) {
  17865. best = a[i];
  17866. len = best.length;
  17867. }
  17868. }
  17869. return best;
  17870. };
  17871. function make_num(num) {
  17872. var str = num.toString(10), a = [ str.replace(/^0\./, ".").replace('e+', 'e') ], m;
  17873. if (Math.floor(num) === num) {
  17874. if (num >= 0) {
  17875. a.push("0x" + num.toString(16).toLowerCase(), // probably pointless
  17876. "0" + num.toString(8)); // same.
  17877. } else {
  17878. a.push("-0x" + (-num).toString(16).toLowerCase(), // probably pointless
  17879. "-0" + (-num).toString(8)); // same.
  17880. }
  17881. if ((m = /^(.*?)(0+)$/.exec(num))) {
  17882. a.push(m[1] + "e" + m[2].length);
  17883. }
  17884. } else if ((m = /^0?\.(0+)(.*)$/.exec(num))) {
  17885. a.push(m[2] + "e-" + (m[1].length + m[2].length),
  17886. str.substr(str.indexOf(".")));
  17887. }
  17888. return best_of(a);
  17889. };
  17890. function make_block(stmt, output) {
  17891. if (!stmt || stmt instanceof AST_EmptyStatement)
  17892. output.print("{}");
  17893. else if (stmt instanceof AST_BlockStatement)
  17894. stmt.print(output);
  17895. else output.with_block(function(){
  17896. output.indent();
  17897. stmt.print(output);
  17898. output.newline();
  17899. });
  17900. };
  17901. /* -----[ source map generators ]----- */
  17902. function DEFMAP(nodetype, generator) {
  17903. nodetype.DEFMETHOD("add_source_map", function(stream){
  17904. generator(this, stream);
  17905. });
  17906. };
  17907. // We could easily add info for ALL nodes, but it seems to me that
  17908. // would be quite wasteful, hence this noop in the base class.
  17909. DEFMAP(AST_Node, noop);
  17910. function basic_sourcemap_gen(self, output) {
  17911. output.add_mapping(self.start);
  17912. };
  17913. // XXX: I'm not exactly sure if we need it for all of these nodes,
  17914. // or if we should add even more.
  17915. DEFMAP(AST_Directive, basic_sourcemap_gen);
  17916. DEFMAP(AST_Debugger, basic_sourcemap_gen);
  17917. DEFMAP(AST_Symbol, basic_sourcemap_gen);
  17918. DEFMAP(AST_Jump, basic_sourcemap_gen);
  17919. DEFMAP(AST_StatementWithBody, basic_sourcemap_gen);
  17920. DEFMAP(AST_LabeledStatement, noop); // since the label symbol will mark it
  17921. DEFMAP(AST_Lambda, basic_sourcemap_gen);
  17922. DEFMAP(AST_Switch, basic_sourcemap_gen);
  17923. DEFMAP(AST_SwitchBranch, basic_sourcemap_gen);
  17924. DEFMAP(AST_BlockStatement, basic_sourcemap_gen);
  17925. DEFMAP(AST_Toplevel, noop);
  17926. DEFMAP(AST_New, basic_sourcemap_gen);
  17927. DEFMAP(AST_Try, basic_sourcemap_gen);
  17928. DEFMAP(AST_Catch, basic_sourcemap_gen);
  17929. DEFMAP(AST_Finally, basic_sourcemap_gen);
  17930. DEFMAP(AST_Definitions, basic_sourcemap_gen);
  17931. DEFMAP(AST_Constant, basic_sourcemap_gen);
  17932. DEFMAP(AST_ObjectSetter, function(self, output){
  17933. output.add_mapping(self.start, self.key.name);
  17934. });
  17935. DEFMAP(AST_ObjectGetter, function(self, output){
  17936. output.add_mapping(self.start, self.key.name);
  17937. });
  17938. DEFMAP(AST_ObjectProperty, function(self, output){
  17939. output.add_mapping(self.start, self.key);
  17940. });
  17941. })();
  17942. /***********************************************************************
  17943. A JavaScript tokenizer / parser / beautifier / compressor.
  17944. https://github.com/mishoo/UglifyJS2
  17945. -------------------------------- (C) ---------------------------------
  17946. Author: Mihai Bazon
  17947. <mihai.bazon@gmail.com>
  17948. http://mihai.bazon.net/blog
  17949. Distributed under the BSD license:
  17950. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  17951. Redistribution and use in source and binary forms, with or without
  17952. modification, are permitted provided that the following conditions
  17953. are met:
  17954. * Redistributions of source code must retain the above
  17955. copyright notice, this list of conditions and the following
  17956. disclaimer.
  17957. * Redistributions in binary form must reproduce the above
  17958. copyright notice, this list of conditions and the following
  17959. disclaimer in the documentation and/or other materials
  17960. provided with the distribution.
  17961. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  17962. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17963. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  17964. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  17965. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  17966. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  17967. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  17968. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  17969. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  17970. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  17971. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  17972. SUCH DAMAGE.
  17973. ***********************************************************************/
  17974. "use strict";
  17975. function Compressor(options, false_by_default) {
  17976. if (!(this instanceof Compressor))
  17977. return new Compressor(options, false_by_default);
  17978. TreeTransformer.call(this, this.before, this.after);
  17979. this.options = defaults(options, {
  17980. angular : false,
  17981. booleans : !false_by_default,
  17982. cascade : !false_by_default,
  17983. collapse_vars : !false_by_default,
  17984. comparisons : !false_by_default,
  17985. conditionals : !false_by_default,
  17986. dead_code : !false_by_default,
  17987. drop_console : false,
  17988. drop_debugger : !false_by_default,
  17989. evaluate : !false_by_default,
  17990. expression : false,
  17991. global_defs : {},
  17992. hoist_funs : !false_by_default,
  17993. hoist_vars : false,
  17994. if_return : !false_by_default,
  17995. join_vars : !false_by_default,
  17996. keep_fargs : true,
  17997. keep_fnames : false,
  17998. keep_infinity : false,
  17999. loops : !false_by_default,
  18000. negate_iife : !false_by_default,
  18001. passes : 1,
  18002. properties : !false_by_default,
  18003. pure_getters : !false_by_default && "strict",
  18004. pure_funcs : null,
  18005. reduce_vars : !false_by_default,
  18006. screw_ie8 : true,
  18007. sequences : !false_by_default,
  18008. side_effects : !false_by_default,
  18009. switches : !false_by_default,
  18010. top_retain : null,
  18011. toplevel : !!(options && options["top_retain"]),
  18012. unsafe : false,
  18013. unsafe_comps : false,
  18014. unsafe_math : false,
  18015. unsafe_proto : false,
  18016. unsafe_regexp : false,
  18017. unused : !false_by_default,
  18018. warnings : true,
  18019. }, true);
  18020. var pure_funcs = this.options["pure_funcs"];
  18021. if (typeof pure_funcs == "function") {
  18022. this.pure_funcs = pure_funcs;
  18023. } else {
  18024. this.pure_funcs = pure_funcs ? function(node) {
  18025. return pure_funcs.indexOf(node.expression.print_to_string()) < 0;
  18026. } : return_true;
  18027. }
  18028. var top_retain = this.options["top_retain"];
  18029. if (top_retain instanceof RegExp) {
  18030. this.top_retain = function(def) {
  18031. return top_retain.test(def.name);
  18032. };
  18033. } else if (typeof top_retain == "function") {
  18034. this.top_retain = top_retain;
  18035. } else if (top_retain) {
  18036. if (typeof top_retain == "string") {
  18037. top_retain = top_retain.split(/,/);
  18038. }
  18039. this.top_retain = function(def) {
  18040. return top_retain.indexOf(def.name) >= 0;
  18041. };
  18042. }
  18043. var sequences = this.options["sequences"];
  18044. this.sequences_limit = sequences == 1 ? 200 : sequences | 0;
  18045. this.warnings_produced = {};
  18046. };
  18047. Compressor.prototype = new TreeTransformer;
  18048. merge(Compressor.prototype, {
  18049. option: function(key) { return this.options[key] },
  18050. compress: function(node) {
  18051. if (this.option("expression")) {
  18052. node = node.process_expression(true);
  18053. }
  18054. var passes = +this.options.passes || 1;
  18055. for (var pass = 0; pass < passes && pass < 3; ++pass) {
  18056. if (pass > 0 || this.option("reduce_vars"))
  18057. node.reset_opt_flags(this, true);
  18058. node = node.transform(this);
  18059. }
  18060. if (this.option("expression")) {
  18061. node = node.process_expression(false);
  18062. }
  18063. return node;
  18064. },
  18065. info: function() {
  18066. if (this.options.warnings == "verbose") {
  18067. AST_Node.warn.apply(AST_Node, arguments);
  18068. }
  18069. },
  18070. warn: function(text, props) {
  18071. if (this.options.warnings) {
  18072. // only emit unique warnings
  18073. var message = string_template(text, props);
  18074. if (!(message in this.warnings_produced)) {
  18075. this.warnings_produced[message] = true;
  18076. AST_Node.warn.apply(AST_Node, arguments);
  18077. }
  18078. }
  18079. },
  18080. clear_warnings: function() {
  18081. this.warnings_produced = {};
  18082. },
  18083. before: function(node, descend, in_list) {
  18084. if (node._squeezed) return node;
  18085. var was_scope = false;
  18086. if (node instanceof AST_Scope) {
  18087. node = node.hoist_declarations(this);
  18088. was_scope = true;
  18089. }
  18090. // Before https://github.com/mishoo/UglifyJS2/pull/1602 AST_Node.optimize()
  18091. // would call AST_Node.transform() if a different instance of AST_Node is
  18092. // produced after OPT().
  18093. // This corrupts TreeWalker.stack, which cause AST look-ups to malfunction.
  18094. // Migrate and defer all children's AST_Node.transform() to below, which
  18095. // will now happen after this parent AST_Node has been properly substituted
  18096. // thus gives a consistent AST snapshot.
  18097. descend(node, this);
  18098. // Existing code relies on how AST_Node.optimize() worked, and omitting the
  18099. // following replacement call would result in degraded efficiency of both
  18100. // output and performance.
  18101. descend(node, this);
  18102. var opt = node.optimize(this);
  18103. if (was_scope && opt instanceof AST_Scope) {
  18104. opt.drop_unused(this);
  18105. descend(opt, this);
  18106. }
  18107. if (opt === node) opt._squeezed = true;
  18108. return opt;
  18109. }
  18110. });
  18111. (function(){
  18112. function OPT(node, optimizer) {
  18113. node.DEFMETHOD("optimize", function(compressor){
  18114. var self = this;
  18115. if (self._optimized) return self;
  18116. if (compressor.has_directive("use asm")) return self;
  18117. var opt = optimizer(self, compressor);
  18118. opt._optimized = true;
  18119. return opt;
  18120. });
  18121. };
  18122. OPT(AST_Node, function(self, compressor){
  18123. return self;
  18124. });
  18125. AST_Node.DEFMETHOD("equivalent_to", function(node){
  18126. return this.TYPE == node.TYPE && this.print_to_string() == node.print_to_string();
  18127. });
  18128. AST_Node.DEFMETHOD("process_expression", function(insert, compressor) {
  18129. var self = this;
  18130. var tt = new TreeTransformer(function(node) {
  18131. if (insert && node instanceof AST_SimpleStatement) {
  18132. return make_node(AST_Return, node, {
  18133. value: node.body
  18134. });
  18135. }
  18136. if (!insert && node instanceof AST_Return) {
  18137. if (compressor) {
  18138. var value = node.value && node.value.drop_side_effect_free(compressor, true);
  18139. return value ? make_node(AST_SimpleStatement, node, {
  18140. body: value
  18141. }) : make_node(AST_EmptyStatement, node);
  18142. }
  18143. return make_node(AST_SimpleStatement, node, {
  18144. body: node.value || make_node(AST_UnaryPrefix, node, {
  18145. operator: "void",
  18146. expression: make_node(AST_Number, node, {
  18147. value: 0
  18148. })
  18149. })
  18150. });
  18151. }
  18152. if (node instanceof AST_Lambda && node !== self) {
  18153. return node;
  18154. }
  18155. if (node instanceof AST_Block) {
  18156. var index = node.body.length - 1;
  18157. if (index >= 0) {
  18158. node.body[index] = node.body[index].transform(tt);
  18159. }
  18160. }
  18161. if (node instanceof AST_If) {
  18162. node.body = node.body.transform(tt);
  18163. if (node.alternative) {
  18164. node.alternative = node.alternative.transform(tt);
  18165. }
  18166. }
  18167. if (node instanceof AST_With) {
  18168. node.body = node.body.transform(tt);
  18169. }
  18170. return node;
  18171. });
  18172. return self.transform(tt);
  18173. });
  18174. AST_Node.DEFMETHOD("reset_opt_flags", function(compressor, rescan){
  18175. var reduce_vars = rescan && compressor.option("reduce_vars");
  18176. var toplevel = compressor.option("toplevel");
  18177. var safe_ids = Object.create(null);
  18178. var suppressor = new TreeWalker(function(node) {
  18179. if (node instanceof AST_Symbol) {
  18180. var d = node.definition();
  18181. if (node instanceof AST_SymbolRef) d.references.push(node);
  18182. d.fixed = false;
  18183. }
  18184. });
  18185. var tw = new TreeWalker(function(node, descend){
  18186. node._squeezed = false;
  18187. node._optimized = false;
  18188. if (reduce_vars) {
  18189. if (node instanceof AST_Toplevel) node.globals.each(reset_def);
  18190. if (node instanceof AST_Scope) node.variables.each(reset_def);
  18191. if (node instanceof AST_SymbolRef) {
  18192. var d = node.definition();
  18193. d.references.push(node);
  18194. if (d.fixed === undefined || !is_safe(d)
  18195. || is_modified(node, 0, node.fixed_value() instanceof AST_Lambda)) {
  18196. d.fixed = false;
  18197. } else {
  18198. var parent = tw.parent();
  18199. if (parent instanceof AST_Assign && parent.operator == "=" && node === parent.right
  18200. || parent instanceof AST_Call && node !== parent.expression
  18201. || parent instanceof AST_Return && node === parent.value && node.scope !== d.scope
  18202. || parent instanceof AST_VarDef && node === parent.value) {
  18203. d.escaped = true;
  18204. }
  18205. }
  18206. }
  18207. if (node instanceof AST_SymbolCatch) {
  18208. node.definition().fixed = false;
  18209. }
  18210. if (node instanceof AST_VarDef) {
  18211. var d = node.name.definition();
  18212. if (d.fixed == null) {
  18213. if (node.value) {
  18214. d.fixed = function() {
  18215. return node.value;
  18216. };
  18217. mark(d, false);
  18218. descend();
  18219. } else {
  18220. d.fixed = null;
  18221. }
  18222. mark(d, true);
  18223. return true;
  18224. } else if (node.value) {
  18225. d.fixed = false;
  18226. }
  18227. }
  18228. if (node instanceof AST_Defun) {
  18229. var d = node.name.definition();
  18230. if (!toplevel && d.global || is_safe(d)) {
  18231. d.fixed = false;
  18232. } else {
  18233. d.fixed = node;
  18234. mark(d, true);
  18235. }
  18236. var save_ids = safe_ids;
  18237. safe_ids = Object.create(null);
  18238. descend();
  18239. safe_ids = save_ids;
  18240. return true;
  18241. }
  18242. if (node instanceof AST_Function) {
  18243. push();
  18244. var iife;
  18245. if (!node.name
  18246. && (iife = tw.parent()) instanceof AST_Call
  18247. && iife.expression === node) {
  18248. // Virtually turn IIFE parameters into variable definitions:
  18249. // (function(a,b) {...})(c,d) => (function() {var a=c,b=d; ...})()
  18250. // So existing transformation rules can work on them.
  18251. node.argnames.forEach(function(arg, i) {
  18252. var d = arg.definition();
  18253. if (!node.uses_arguments && d.fixed === undefined) {
  18254. d.fixed = function() {
  18255. return iife.args[i] || make_node(AST_Undefined, iife);
  18256. };
  18257. mark(d, true);
  18258. } else {
  18259. d.fixed = false;
  18260. }
  18261. });
  18262. }
  18263. descend();
  18264. pop();
  18265. return true;
  18266. }
  18267. if (node instanceof AST_Accessor) {
  18268. var save_ids = safe_ids;
  18269. safe_ids = Object.create(null);
  18270. descend();
  18271. safe_ids = save_ids;
  18272. return true;
  18273. }
  18274. if (node instanceof AST_Binary
  18275. && (node.operator == "&&" || node.operator == "||")) {
  18276. node.left.walk(tw);
  18277. push();
  18278. node.right.walk(tw);
  18279. pop();
  18280. return true;
  18281. }
  18282. if (node instanceof AST_Conditional) {
  18283. node.condition.walk(tw);
  18284. push();
  18285. node.consequent.walk(tw);
  18286. pop();
  18287. push();
  18288. node.alternative.walk(tw);
  18289. pop();
  18290. return true;
  18291. }
  18292. if (node instanceof AST_If || node instanceof AST_DWLoop) {
  18293. node.condition.walk(tw);
  18294. push();
  18295. node.body.walk(tw);
  18296. pop();
  18297. if (node.alternative) {
  18298. push();
  18299. node.alternative.walk(tw);
  18300. pop();
  18301. }
  18302. return true;
  18303. }
  18304. if (node instanceof AST_LabeledStatement) {
  18305. push();
  18306. node.body.walk(tw);
  18307. pop();
  18308. return true;
  18309. }
  18310. if (node instanceof AST_For) {
  18311. if (node.init) node.init.walk(tw);
  18312. push();
  18313. if (node.condition) node.condition.walk(tw);
  18314. node.body.walk(tw);
  18315. if (node.step) node.step.walk(tw);
  18316. pop();
  18317. return true;
  18318. }
  18319. if (node instanceof AST_ForIn) {
  18320. node.init.walk(suppressor);
  18321. node.object.walk(tw);
  18322. push();
  18323. node.body.walk(tw);
  18324. pop();
  18325. return true;
  18326. }
  18327. if (node instanceof AST_Try) {
  18328. push();
  18329. walk_body(node, tw);
  18330. pop();
  18331. if (node.bcatch) {
  18332. push();
  18333. node.bcatch.walk(tw);
  18334. pop();
  18335. }
  18336. if (node.bfinally) node.bfinally.walk(tw);
  18337. return true;
  18338. }
  18339. if (node instanceof AST_SwitchBranch) {
  18340. push();
  18341. descend();
  18342. pop();
  18343. return true;
  18344. }
  18345. }
  18346. });
  18347. this.walk(tw);
  18348. function mark(def, safe) {
  18349. safe_ids[def.id] = safe;
  18350. }
  18351. function is_safe(def) {
  18352. if (safe_ids[def.id]) {
  18353. if (def.fixed == null) {
  18354. var orig = def.orig[0];
  18355. if (orig instanceof AST_SymbolFunarg || orig.name == "arguments") return false;
  18356. def.fixed = make_node(AST_Undefined, orig);
  18357. }
  18358. return true;
  18359. }
  18360. }
  18361. function push() {
  18362. safe_ids = Object.create(safe_ids);
  18363. }
  18364. function pop() {
  18365. safe_ids = Object.getPrototypeOf(safe_ids);
  18366. }
  18367. function reset_def(def) {
  18368. def.escaped = false;
  18369. if (def.scope.uses_eval) {
  18370. def.fixed = false;
  18371. } else if (toplevel || !def.global || def.orig[0] instanceof AST_SymbolConst) {
  18372. def.fixed = undefined;
  18373. } else {
  18374. def.fixed = false;
  18375. }
  18376. def.references = [];
  18377. def.should_replace = undefined;
  18378. }
  18379. function is_modified(node, level, func) {
  18380. var parent = tw.parent(level);
  18381. if (is_lhs(node, parent)
  18382. || !func && parent instanceof AST_Call && parent.expression === node) {
  18383. return true;
  18384. } else if (parent instanceof AST_PropAccess && parent.expression === node) {
  18385. return !func && is_modified(parent, level + 1);
  18386. }
  18387. }
  18388. });
  18389. AST_SymbolRef.DEFMETHOD("fixed_value", function() {
  18390. var fixed = this.definition().fixed;
  18391. if (!fixed || fixed instanceof AST_Node) return fixed;
  18392. return fixed();
  18393. });
  18394. function is_reference_const(ref) {
  18395. if (!(ref instanceof AST_SymbolRef)) return false;
  18396. var orig = ref.definition().orig;
  18397. for (var i = orig.length; --i >= 0;) {
  18398. if (orig[i] instanceof AST_SymbolConst) return true;
  18399. }
  18400. }
  18401. function find_variable(compressor, name) {
  18402. var scope, i = 0;
  18403. while (scope = compressor.parent(i++)) {
  18404. if (scope instanceof AST_Scope) break;
  18405. if (scope instanceof AST_Catch) {
  18406. scope = scope.argname.definition().scope;
  18407. break;
  18408. }
  18409. }
  18410. return scope.find_variable(name);
  18411. }
  18412. function make_node(ctor, orig, props) {
  18413. if (!props) props = {};
  18414. if (orig) {
  18415. if (!props.start) props.start = orig.start;
  18416. if (!props.end) props.end = orig.end;
  18417. }
  18418. return new ctor(props);
  18419. };
  18420. function make_node_from_constant(val, orig) {
  18421. switch (typeof val) {
  18422. case "string":
  18423. return make_node(AST_String, orig, {
  18424. value: val
  18425. });
  18426. case "number":
  18427. if (isNaN(val)) return make_node(AST_NaN, orig);
  18428. if (isFinite(val)) {
  18429. return 1 / val < 0 ? make_node(AST_UnaryPrefix, orig, {
  18430. operator: "-",
  18431. expression: make_node(AST_Number, orig, { value: -val })
  18432. }) : make_node(AST_Number, orig, { value: val });
  18433. }
  18434. return val < 0 ? make_node(AST_UnaryPrefix, orig, {
  18435. operator: "-",
  18436. expression: make_node(AST_Infinity, orig)
  18437. }) : make_node(AST_Infinity, orig);
  18438. case "boolean":
  18439. return make_node(val ? AST_True : AST_False, orig);
  18440. case "undefined":
  18441. return make_node(AST_Undefined, orig);
  18442. default:
  18443. if (val === null) {
  18444. return make_node(AST_Null, orig, { value: null });
  18445. }
  18446. if (val instanceof RegExp) {
  18447. return make_node(AST_RegExp, orig, { value: val });
  18448. }
  18449. throw new Error(string_template("Can't handle constant of type: {type}", {
  18450. type: typeof val
  18451. }));
  18452. }
  18453. };
  18454. // we shouldn't compress (1,func)(something) to
  18455. // func(something) because that changes the meaning of
  18456. // the func (becomes lexical instead of global).
  18457. function maintain_this_binding(parent, orig, val) {
  18458. if (parent instanceof AST_UnaryPrefix && parent.operator == "delete"
  18459. || parent instanceof AST_Call && parent.expression === orig
  18460. && (val instanceof AST_PropAccess || val instanceof AST_SymbolRef && val.name == "eval")) {
  18461. return make_node(AST_Seq, orig, {
  18462. car: make_node(AST_Number, orig, {
  18463. value: 0
  18464. }),
  18465. cdr: val
  18466. });
  18467. }
  18468. return val;
  18469. }
  18470. function as_statement_array(thing) {
  18471. if (thing === null) return [];
  18472. if (thing instanceof AST_BlockStatement) return thing.body;
  18473. if (thing instanceof AST_EmptyStatement) return [];
  18474. if (thing instanceof AST_Statement) return [ thing ];
  18475. throw new Error("Can't convert thing to statement array");
  18476. };
  18477. function is_empty(thing) {
  18478. if (thing === null) return true;
  18479. if (thing instanceof AST_EmptyStatement) return true;
  18480. if (thing instanceof AST_BlockStatement) return thing.body.length == 0;
  18481. return false;
  18482. };
  18483. function loop_body(x) {
  18484. if (x instanceof AST_Switch) return x;
  18485. if (x instanceof AST_For || x instanceof AST_ForIn || x instanceof AST_DWLoop) {
  18486. return (x.body instanceof AST_BlockStatement ? x.body : x);
  18487. }
  18488. return x;
  18489. };
  18490. function is_iife_call(node) {
  18491. if (node instanceof AST_Call && !(node instanceof AST_New)) {
  18492. return node.expression instanceof AST_Function || is_iife_call(node.expression);
  18493. }
  18494. return false;
  18495. }
  18496. function tighten_body(statements, compressor) {
  18497. var CHANGED, max_iter = 10;
  18498. do {
  18499. CHANGED = false;
  18500. if (compressor.option("angular")) {
  18501. statements = process_for_angular(statements);
  18502. }
  18503. statements = eliminate_spurious_blocks(statements);
  18504. if (compressor.option("dead_code")) {
  18505. statements = eliminate_dead_code(statements, compressor);
  18506. }
  18507. if (compressor.option("if_return")) {
  18508. statements = handle_if_return(statements, compressor);
  18509. }
  18510. if (compressor.sequences_limit > 0) {
  18511. statements = sequencesize(statements, compressor);
  18512. }
  18513. if (compressor.option("join_vars")) {
  18514. statements = join_consecutive_vars(statements, compressor);
  18515. }
  18516. if (compressor.option("collapse_vars")) {
  18517. statements = collapse_single_use_vars(statements, compressor);
  18518. }
  18519. } while (CHANGED && max_iter-- > 0);
  18520. return statements;
  18521. function collapse_single_use_vars(statements, compressor) {
  18522. // Iterate statements backwards looking for a statement with a var/const
  18523. // declaration immediately preceding it. Grab the rightmost var definition
  18524. // and if it has exactly one reference then attempt to replace its reference
  18525. // in the statement with the var value and then erase the var definition.
  18526. var self = compressor.self();
  18527. var var_defs_removed = false;
  18528. var toplevel = compressor.option("toplevel");
  18529. for (var stat_index = statements.length; --stat_index >= 0;) {
  18530. var stat = statements[stat_index];
  18531. if (stat instanceof AST_Definitions) continue;
  18532. // Process child blocks of statement if present.
  18533. [stat, stat.body, stat.alternative, stat.bcatch, stat.bfinally].forEach(function(node) {
  18534. node && node.body && collapse_single_use_vars(node.body, compressor);
  18535. });
  18536. // The variable definition must precede a statement.
  18537. if (stat_index <= 0) break;
  18538. var prev_stat_index = stat_index - 1;
  18539. var prev_stat = statements[prev_stat_index];
  18540. if (!(prev_stat instanceof AST_Definitions)) continue;
  18541. var var_defs = prev_stat.definitions;
  18542. if (var_defs == null) continue;
  18543. var var_names_seen = {};
  18544. var side_effects_encountered = false;
  18545. var lvalues_encountered = false;
  18546. var lvalues = {};
  18547. // Scan variable definitions from right to left.
  18548. for (var var_defs_index = var_defs.length; --var_defs_index >= 0;) {
  18549. // Obtain var declaration and var name with basic sanity check.
  18550. var var_decl = var_defs[var_defs_index];
  18551. if (var_decl.value == null) break;
  18552. var var_name = var_decl.name.name;
  18553. if (!var_name || !var_name.length) break;
  18554. // Bail if we've seen a var definition of same name before.
  18555. if (var_name in var_names_seen) break;
  18556. var_names_seen[var_name] = true;
  18557. // Only interested in cases with just one reference to the variable.
  18558. var def = self.find_variable && self.find_variable(var_name);
  18559. if (!def || !def.references || def.references.length !== 1
  18560. || var_name == "arguments" || (!toplevel && def.global)) {
  18561. side_effects_encountered = true;
  18562. continue;
  18563. }
  18564. var ref = def.references[0];
  18565. // Don't replace ref if eval() or with statement in scope.
  18566. if (ref.scope.uses_eval || ref.scope.uses_with) break;
  18567. // Constant single use vars can be replaced in any scope.
  18568. if (var_decl.value.is_constant()) {
  18569. var ctt = new TreeTransformer(function(node) {
  18570. var parent = ctt.parent();
  18571. if (parent instanceof AST_IterationStatement
  18572. && (parent.condition === node || parent.init === node)) {
  18573. return node;
  18574. }
  18575. if (node === ref)
  18576. return replace_var(node, parent, true);
  18577. });
  18578. stat.transform(ctt);
  18579. continue;
  18580. }
  18581. // Restrict var replacement to constants if side effects encountered.
  18582. if (side_effects_encountered |= lvalues_encountered) continue;
  18583. var value_has_side_effects = var_decl.value.has_side_effects(compressor);
  18584. // Non-constant single use vars can only be replaced in same scope.
  18585. if (ref.scope !== self) {
  18586. side_effects_encountered |= value_has_side_effects;
  18587. continue;
  18588. }
  18589. // Detect lvalues in var value.
  18590. var tw = new TreeWalker(function(node){
  18591. if (node instanceof AST_SymbolRef && is_lvalue(node, tw.parent())) {
  18592. lvalues[node.name] = lvalues_encountered = true;
  18593. }
  18594. });
  18595. var_decl.value.walk(tw);
  18596. // Replace the non-constant single use var in statement if side effect free.
  18597. var unwind = false;
  18598. var tt = new TreeTransformer(
  18599. function preorder(node) {
  18600. if (unwind) return node;
  18601. var parent = tt.parent();
  18602. if (node instanceof AST_Lambda
  18603. || node instanceof AST_Try
  18604. || node instanceof AST_With
  18605. || node instanceof AST_Case
  18606. || node instanceof AST_IterationStatement
  18607. || (parent instanceof AST_If && node !== parent.condition)
  18608. || (parent instanceof AST_Conditional && node !== parent.condition)
  18609. || (node instanceof AST_SymbolRef
  18610. && value_has_side_effects
  18611. && !are_references_in_scope(node.definition(), self))
  18612. || (parent instanceof AST_Binary
  18613. && (parent.operator == "&&" || parent.operator == "||")
  18614. && node === parent.right)
  18615. || (parent instanceof AST_Switch && node !== parent.expression)) {
  18616. return side_effects_encountered = unwind = true, node;
  18617. }
  18618. function are_references_in_scope(def, scope) {
  18619. if (def.orig.length === 1
  18620. && def.orig[0] instanceof AST_SymbolDefun) return true;
  18621. if (def.scope !== scope) return false;
  18622. var refs = def.references;
  18623. for (var i = 0, len = refs.length; i < len; i++) {
  18624. if (refs[i].scope !== scope) return false;
  18625. }
  18626. return true;
  18627. }
  18628. },
  18629. function postorder(node) {
  18630. if (unwind) return node;
  18631. if (node === ref)
  18632. return unwind = true, replace_var(node, tt.parent(), false);
  18633. if (side_effects_encountered |= node.has_side_effects(compressor))
  18634. return unwind = true, node;
  18635. if (lvalues_encountered && node instanceof AST_SymbolRef && node.name in lvalues) {
  18636. side_effects_encountered = true;
  18637. return unwind = true, node;
  18638. }
  18639. }
  18640. );
  18641. stat.transform(tt);
  18642. }
  18643. }
  18644. // Remove extraneous empty statments in block after removing var definitions.
  18645. // Leave at least one statement in `statements`.
  18646. if (var_defs_removed) for (var i = statements.length; --i >= 0;) {
  18647. if (statements.length > 1 && statements[i] instanceof AST_EmptyStatement)
  18648. statements.splice(i, 1);
  18649. }
  18650. return statements;
  18651. function is_lvalue(node, parent) {
  18652. return node instanceof AST_SymbolRef && is_lhs(node, parent);
  18653. }
  18654. function replace_var(node, parent, is_constant) {
  18655. if (is_lvalue(node, parent)) return node;
  18656. // Remove var definition and return its value to the TreeTransformer to replace.
  18657. var value = maintain_this_binding(parent, node, var_decl.value);
  18658. var_decl.value = null;
  18659. var_defs.splice(var_defs_index, 1);
  18660. if (var_defs.length === 0) {
  18661. statements[prev_stat_index] = make_node(AST_EmptyStatement, self);
  18662. var_defs_removed = true;
  18663. }
  18664. // Further optimize statement after substitution.
  18665. stat.reset_opt_flags(compressor);
  18666. compressor.info("Collapsing " + (is_constant ? "constant" : "variable") +
  18667. " " + var_name + " [{file}:{line},{col}]", node.start);
  18668. CHANGED = true;
  18669. return value;
  18670. }
  18671. }
  18672. function process_for_angular(statements) {
  18673. function has_inject(comment) {
  18674. return /@ngInject/.test(comment.value);
  18675. }
  18676. function make_arguments_names_list(func) {
  18677. return func.argnames.map(function(sym){
  18678. return make_node(AST_String, sym, { value: sym.name });
  18679. });
  18680. }
  18681. function make_array(orig, elements) {
  18682. return make_node(AST_Array, orig, { elements: elements });
  18683. }
  18684. function make_injector(func, name) {
  18685. return make_node(AST_SimpleStatement, func, {
  18686. body: make_node(AST_Assign, func, {
  18687. operator: "=",
  18688. left: make_node(AST_Dot, name, {
  18689. expression: make_node(AST_SymbolRef, name, name),
  18690. property: "$inject"
  18691. }),
  18692. right: make_array(func, make_arguments_names_list(func))
  18693. })
  18694. });
  18695. }
  18696. function check_expression(body) {
  18697. if (body && body.args) {
  18698. // if this is a function call check all of arguments passed
  18699. body.args.forEach(function(argument, index, array) {
  18700. var comments = argument.start.comments_before;
  18701. // if the argument is function preceded by @ngInject
  18702. if (argument instanceof AST_Lambda && comments.length && has_inject(comments[0])) {
  18703. // replace the function with an array of names of its parameters and function at the end
  18704. array[index] = make_array(argument, make_arguments_names_list(argument).concat(argument));
  18705. }
  18706. });
  18707. // if this is chained call check previous one recursively
  18708. if (body.expression && body.expression.expression) {
  18709. check_expression(body.expression.expression);
  18710. }
  18711. }
  18712. }
  18713. return statements.reduce(function(a, stat){
  18714. a.push(stat);
  18715. if (stat.body && stat.body.args) {
  18716. check_expression(stat.body);
  18717. } else {
  18718. var token = stat.start;
  18719. var comments = token.comments_before;
  18720. if (comments && comments.length > 0) {
  18721. var last = comments.pop();
  18722. if (has_inject(last)) {
  18723. // case 1: defun
  18724. if (stat instanceof AST_Defun) {
  18725. a.push(make_injector(stat, stat.name));
  18726. }
  18727. else if (stat instanceof AST_Definitions) {
  18728. stat.definitions.forEach(function(def) {
  18729. if (def.value && def.value instanceof AST_Lambda) {
  18730. a.push(make_injector(def.value, def.name));
  18731. }
  18732. });
  18733. }
  18734. else {
  18735. compressor.warn("Unknown statement marked with @ngInject [{file}:{line},{col}]", token);
  18736. }
  18737. }
  18738. }
  18739. }
  18740. return a;
  18741. }, []);
  18742. }
  18743. function eliminate_spurious_blocks(statements) {
  18744. var seen_dirs = [];
  18745. return statements.reduce(function(a, stat){
  18746. if (stat instanceof AST_BlockStatement) {
  18747. CHANGED = true;
  18748. a.push.apply(a, eliminate_spurious_blocks(stat.body));
  18749. } else if (stat instanceof AST_EmptyStatement) {
  18750. CHANGED = true;
  18751. } else if (stat instanceof AST_Directive) {
  18752. if (seen_dirs.indexOf(stat.value) < 0) {
  18753. a.push(stat);
  18754. seen_dirs.push(stat.value);
  18755. } else {
  18756. CHANGED = true;
  18757. }
  18758. } else {
  18759. a.push(stat);
  18760. }
  18761. return a;
  18762. }, []);
  18763. };
  18764. function handle_if_return(statements, compressor) {
  18765. var self = compressor.self();
  18766. var multiple_if_returns = has_multiple_if_returns(statements);
  18767. var in_lambda = self instanceof AST_Lambda;
  18768. var ret = []; // Optimized statements, build from tail to front
  18769. loop: for (var i = statements.length; --i >= 0;) {
  18770. var stat = statements[i];
  18771. switch (true) {
  18772. case (in_lambda && stat instanceof AST_Return && !stat.value && ret.length == 0):
  18773. CHANGED = true;
  18774. // note, ret.length is probably always zero
  18775. // because we drop unreachable code before this
  18776. // step. nevertheless, it's good to check.
  18777. continue loop;
  18778. case stat instanceof AST_If:
  18779. if (stat.body instanceof AST_Return) {
  18780. //---
  18781. // pretty silly case, but:
  18782. // if (foo()) return; return; ==> foo(); return;
  18783. if (((in_lambda && ret.length == 0)
  18784. || (ret[0] instanceof AST_Return && !ret[0].value))
  18785. && !stat.body.value && !stat.alternative) {
  18786. CHANGED = true;
  18787. var cond = make_node(AST_SimpleStatement, stat.condition, {
  18788. body: stat.condition
  18789. });
  18790. ret.unshift(cond);
  18791. continue loop;
  18792. }
  18793. //---
  18794. // if (foo()) return x; return y; ==> return foo() ? x : y;
  18795. if (ret[0] instanceof AST_Return && stat.body.value && ret[0].value && !stat.alternative) {
  18796. CHANGED = true;
  18797. stat = stat.clone();
  18798. stat.alternative = ret[0];
  18799. ret[0] = stat.transform(compressor);
  18800. continue loop;
  18801. }
  18802. //---
  18803. // if (foo()) return x; [ return ; ] ==> return foo() ? x : undefined;
  18804. if (multiple_if_returns && (ret.length == 0 || ret[0] instanceof AST_Return)
  18805. && stat.body.value && !stat.alternative && in_lambda) {
  18806. CHANGED = true;
  18807. stat = stat.clone();
  18808. stat.alternative = ret[0] || make_node(AST_Return, stat, {
  18809. value: null
  18810. });
  18811. ret[0] = stat.transform(compressor);
  18812. continue loop;
  18813. }
  18814. //---
  18815. // if (foo()) return; [ else x... ]; y... ==> if (!foo()) { x...; y... }
  18816. if (!stat.body.value && in_lambda) {
  18817. CHANGED = true;
  18818. stat = stat.clone();
  18819. stat.condition = stat.condition.negate(compressor);
  18820. var body = as_statement_array(stat.alternative).concat(ret);
  18821. var funs = extract_functions_from_statement_array(body);
  18822. stat.body = make_node(AST_BlockStatement, stat, {
  18823. body: body
  18824. });
  18825. stat.alternative = null;
  18826. ret = funs.concat([ stat.transform(compressor) ]);
  18827. continue loop;
  18828. }
  18829. //---
  18830. // if (a) return b; if (c) return d; e; ==> return a ? b : c ? d : void e;
  18831. //
  18832. // if sequences is not enabled, this can lead to an endless loop (issue #866).
  18833. // however, with sequences on this helps producing slightly better output for
  18834. // the example code.
  18835. if (compressor.option("sequences")
  18836. && i > 0 && statements[i - 1] instanceof AST_If && statements[i - 1].body instanceof AST_Return
  18837. && ret.length == 1 && in_lambda && ret[0] instanceof AST_SimpleStatement
  18838. && !stat.alternative) {
  18839. CHANGED = true;
  18840. ret.push(make_node(AST_Return, ret[0], {
  18841. value: null
  18842. }).transform(compressor));
  18843. ret.unshift(stat);
  18844. continue loop;
  18845. }
  18846. }
  18847. var ab = aborts(stat.body);
  18848. var lct = ab instanceof AST_LoopControl ? compressor.loopcontrol_target(ab) : null;
  18849. if (ab && ((ab instanceof AST_Return && !ab.value && in_lambda)
  18850. || (ab instanceof AST_Continue && self === loop_body(lct))
  18851. || (ab instanceof AST_Break && lct instanceof AST_BlockStatement && self === lct))) {
  18852. if (ab.label) {
  18853. remove(ab.label.thedef.references, ab);
  18854. }
  18855. CHANGED = true;
  18856. var body = as_statement_array(stat.body).slice(0, -1);
  18857. stat = stat.clone();
  18858. stat.condition = stat.condition.negate(compressor);
  18859. stat.body = make_node(AST_BlockStatement, stat, {
  18860. body: as_statement_array(stat.alternative).concat(ret)
  18861. });
  18862. stat.alternative = make_node(AST_BlockStatement, stat, {
  18863. body: body
  18864. });
  18865. ret = [ stat.transform(compressor) ];
  18866. continue loop;
  18867. }
  18868. var ab = aborts(stat.alternative);
  18869. var lct = ab instanceof AST_LoopControl ? compressor.loopcontrol_target(ab) : null;
  18870. if (ab && ((ab instanceof AST_Return && !ab.value && in_lambda)
  18871. || (ab instanceof AST_Continue && self === loop_body(lct))
  18872. || (ab instanceof AST_Break && lct instanceof AST_BlockStatement && self === lct))) {
  18873. if (ab.label) {
  18874. remove(ab.label.thedef.references, ab);
  18875. }
  18876. CHANGED = true;
  18877. stat = stat.clone();
  18878. stat.body = make_node(AST_BlockStatement, stat.body, {
  18879. body: as_statement_array(stat.body).concat(ret)
  18880. });
  18881. stat.alternative = make_node(AST_BlockStatement, stat.alternative, {
  18882. body: as_statement_array(stat.alternative).slice(0, -1)
  18883. });
  18884. ret = [ stat.transform(compressor) ];
  18885. continue loop;
  18886. }
  18887. ret.unshift(stat);
  18888. break;
  18889. default:
  18890. ret.unshift(stat);
  18891. break;
  18892. }
  18893. }
  18894. return ret;
  18895. function has_multiple_if_returns(statements) {
  18896. var n = 0;
  18897. for (var i = statements.length; --i >= 0;) {
  18898. var stat = statements[i];
  18899. if (stat instanceof AST_If && stat.body instanceof AST_Return) {
  18900. if (++n > 1) return true;
  18901. }
  18902. }
  18903. return false;
  18904. }
  18905. };
  18906. function eliminate_dead_code(statements, compressor) {
  18907. var has_quit = false;
  18908. var orig = statements.length;
  18909. var self = compressor.self();
  18910. statements = statements.reduce(function(a, stat){
  18911. if (has_quit) {
  18912. extract_declarations_from_unreachable_code(compressor, stat, a);
  18913. } else {
  18914. if (stat instanceof AST_LoopControl) {
  18915. var lct = compressor.loopcontrol_target(stat);
  18916. if ((stat instanceof AST_Break
  18917. && !(lct instanceof AST_IterationStatement)
  18918. && loop_body(lct) === self) || (stat instanceof AST_Continue
  18919. && loop_body(lct) === self)) {
  18920. if (stat.label) {
  18921. remove(stat.label.thedef.references, stat);
  18922. }
  18923. } else {
  18924. a.push(stat);
  18925. }
  18926. } else {
  18927. a.push(stat);
  18928. }
  18929. if (aborts(stat)) has_quit = true;
  18930. }
  18931. return a;
  18932. }, []);
  18933. CHANGED = statements.length != orig;
  18934. return statements;
  18935. };
  18936. function sequencesize(statements, compressor) {
  18937. if (statements.length < 2) return statements;
  18938. var seq = [], ret = [];
  18939. function push_seq() {
  18940. seq = AST_Seq.from_array(seq);
  18941. if (seq) ret.push(make_node(AST_SimpleStatement, seq, {
  18942. body: seq
  18943. }));
  18944. seq = [];
  18945. };
  18946. statements.forEach(function(stat){
  18947. if (stat instanceof AST_SimpleStatement) {
  18948. if (seqLength(seq) >= compressor.sequences_limit) push_seq();
  18949. var body = stat.body;
  18950. if (seq.length > 0) body = body.drop_side_effect_free(compressor);
  18951. if (body) seq.push(body);
  18952. } else {
  18953. push_seq();
  18954. ret.push(stat);
  18955. }
  18956. });
  18957. push_seq();
  18958. ret = sequencesize_2(ret, compressor);
  18959. CHANGED = ret.length != statements.length;
  18960. return ret;
  18961. };
  18962. function seqLength(a) {
  18963. for (var len = 0, i = 0; i < a.length; ++i) {
  18964. var stat = a[i];
  18965. if (stat instanceof AST_Seq) {
  18966. len += stat.len();
  18967. } else {
  18968. len++;
  18969. }
  18970. }
  18971. return len;
  18972. };
  18973. function sequencesize_2(statements, compressor) {
  18974. function cons_seq(right) {
  18975. ret.pop();
  18976. var left = prev.body;
  18977. if (left instanceof AST_Seq) {
  18978. left.add(right);
  18979. } else {
  18980. left = AST_Seq.cons(left, right);
  18981. }
  18982. return left.transform(compressor);
  18983. };
  18984. var ret = [], prev = null;
  18985. statements.forEach(function(stat){
  18986. if (prev) {
  18987. if (stat instanceof AST_For) {
  18988. var opera = {};
  18989. try {
  18990. prev.body.walk(new TreeWalker(function(node){
  18991. if (node instanceof AST_Binary && node.operator == "in")
  18992. throw opera;
  18993. }));
  18994. if (stat.init && !(stat.init instanceof AST_Definitions)) {
  18995. stat.init = cons_seq(stat.init);
  18996. }
  18997. else if (!stat.init) {
  18998. stat.init = prev.body.drop_side_effect_free(compressor);
  18999. ret.pop();
  19000. }
  19001. } catch(ex) {
  19002. if (ex !== opera) throw ex;
  19003. }
  19004. }
  19005. else if (stat instanceof AST_If) {
  19006. stat.condition = cons_seq(stat.condition);
  19007. }
  19008. else if (stat instanceof AST_With) {
  19009. stat.expression = cons_seq(stat.expression);
  19010. }
  19011. else if (stat instanceof AST_Exit && stat.value) {
  19012. stat.value = cons_seq(stat.value);
  19013. }
  19014. else if (stat instanceof AST_Exit) {
  19015. stat.value = cons_seq(make_node(AST_Undefined, stat).transform(compressor));
  19016. }
  19017. else if (stat instanceof AST_Switch) {
  19018. stat.expression = cons_seq(stat.expression);
  19019. }
  19020. }
  19021. ret.push(stat);
  19022. prev = stat instanceof AST_SimpleStatement ? stat : null;
  19023. });
  19024. return ret;
  19025. };
  19026. function join_consecutive_vars(statements, compressor) {
  19027. var prev = null;
  19028. return statements.reduce(function(a, stat){
  19029. if (stat instanceof AST_Definitions && prev && prev.TYPE == stat.TYPE) {
  19030. prev.definitions = prev.definitions.concat(stat.definitions);
  19031. CHANGED = true;
  19032. }
  19033. else if (stat instanceof AST_For
  19034. && prev instanceof AST_Var
  19035. && (!stat.init || stat.init.TYPE == prev.TYPE)) {
  19036. CHANGED = true;
  19037. a.pop();
  19038. if (stat.init) {
  19039. stat.init.definitions = prev.definitions.concat(stat.init.definitions);
  19040. } else {
  19041. stat.init = prev;
  19042. }
  19043. a.push(stat);
  19044. prev = stat;
  19045. }
  19046. else {
  19047. prev = stat;
  19048. a.push(stat);
  19049. }
  19050. return a;
  19051. }, []);
  19052. };
  19053. };
  19054. function extract_functions_from_statement_array(statements) {
  19055. var funs = [];
  19056. for (var i = statements.length - 1; i >= 0; --i) {
  19057. var stat = statements[i];
  19058. if (stat instanceof AST_Defun) {
  19059. statements.splice(i, 1);
  19060. funs.unshift(stat);
  19061. }
  19062. }
  19063. return funs;
  19064. }
  19065. function extract_declarations_from_unreachable_code(compressor, stat, target) {
  19066. if (!(stat instanceof AST_Defun)) {
  19067. compressor.warn("Dropping unreachable code [{file}:{line},{col}]", stat.start);
  19068. }
  19069. stat.walk(new TreeWalker(function(node){
  19070. if (node instanceof AST_Definitions) {
  19071. compressor.warn("Declarations in unreachable code! [{file}:{line},{col}]", node.start);
  19072. node.remove_initializers();
  19073. target.push(node);
  19074. return true;
  19075. }
  19076. if (node instanceof AST_Defun) {
  19077. target.push(node);
  19078. return true;
  19079. }
  19080. if (node instanceof AST_Scope) {
  19081. return true;
  19082. }
  19083. }));
  19084. };
  19085. function is_undefined(node, compressor) {
  19086. return node.is_undefined
  19087. || node instanceof AST_Undefined
  19088. || node instanceof AST_UnaryPrefix
  19089. && node.operator == "void"
  19090. && !node.expression.has_side_effects(compressor);
  19091. }
  19092. // may_throw_on_access()
  19093. // returns true if this node may be null, undefined or contain `AST_Accessor`
  19094. (function(def) {
  19095. AST_Node.DEFMETHOD("may_throw_on_access", function(compressor) {
  19096. var pure_getters = compressor.option("pure_getters");
  19097. return !pure_getters || this._throw_on_access(pure_getters);
  19098. });
  19099. function is_strict(pure_getters) {
  19100. return /strict/.test(pure_getters);
  19101. }
  19102. def(AST_Node, is_strict);
  19103. def(AST_Null, return_true);
  19104. def(AST_Undefined, return_true);
  19105. def(AST_Constant, return_false);
  19106. def(AST_Array, return_false);
  19107. def(AST_Object, function(pure_getters) {
  19108. if (!is_strict(pure_getters)) return false;
  19109. for (var i = this.properties.length; --i >=0;)
  19110. if (this.properties[i].value instanceof AST_Accessor) return true;
  19111. return false;
  19112. });
  19113. def(AST_Function, return_false);
  19114. def(AST_UnaryPostfix, return_false);
  19115. def(AST_UnaryPrefix, function() {
  19116. return this.operator == "void";
  19117. });
  19118. def(AST_Binary, function(pure_getters) {
  19119. switch (this.operator) {
  19120. case "&&":
  19121. return this.left._throw_on_access(pure_getters);
  19122. case "||":
  19123. return this.left._throw_on_access(pure_getters)
  19124. && this.right._throw_on_access(pure_getters);
  19125. default:
  19126. return false;
  19127. }
  19128. })
  19129. def(AST_Assign, function(pure_getters) {
  19130. return this.operator == "="
  19131. && this.right._throw_on_access(pure_getters);
  19132. })
  19133. def(AST_Conditional, function(pure_getters) {
  19134. return this.consequent._throw_on_access(pure_getters)
  19135. || this.alternative._throw_on_access(pure_getters);
  19136. })
  19137. def(AST_Seq, function(pure_getters) {
  19138. return this.cdr._throw_on_access(pure_getters);
  19139. });
  19140. def(AST_SymbolRef, function(pure_getters) {
  19141. if (this.is_undefined) return true;
  19142. if (!is_strict(pure_getters)) return false;
  19143. var fixed = this.fixed_value();
  19144. return !fixed || fixed._throw_on_access(pure_getters);
  19145. });
  19146. })(function(node, func) {
  19147. node.DEFMETHOD("_throw_on_access", func);
  19148. });
  19149. /* -----[ boolean/negation helpers ]----- */
  19150. // methods to determine whether an expression has a boolean result type
  19151. (function (def){
  19152. var unary_bool = [ "!", "delete" ];
  19153. var binary_bool = [ "in", "instanceof", "==", "!=", "===", "!==", "<", "<=", ">=", ">" ];
  19154. def(AST_Node, return_false);
  19155. def(AST_UnaryPrefix, function(){
  19156. return member(this.operator, unary_bool);
  19157. });
  19158. def(AST_Binary, function(){
  19159. return member(this.operator, binary_bool) ||
  19160. ( (this.operator == "&&" || this.operator == "||") &&
  19161. this.left.is_boolean() && this.right.is_boolean() );
  19162. });
  19163. def(AST_Conditional, function(){
  19164. return this.consequent.is_boolean() && this.alternative.is_boolean();
  19165. });
  19166. def(AST_Assign, function(){
  19167. return this.operator == "=" && this.right.is_boolean();
  19168. });
  19169. def(AST_Seq, function(){
  19170. return this.cdr.is_boolean();
  19171. });
  19172. def(AST_True, return_true);
  19173. def(AST_False, return_true);
  19174. })(function(node, func){
  19175. node.DEFMETHOD("is_boolean", func);
  19176. });
  19177. // methods to determine if an expression has a numeric result type
  19178. (function (def){
  19179. def(AST_Node, return_false);
  19180. def(AST_Number, return_true);
  19181. var unary = makePredicate("+ - ~ ++ --");
  19182. def(AST_Unary, function(){
  19183. return unary(this.operator);
  19184. });
  19185. var binary = makePredicate("- * / % & | ^ << >> >>>");
  19186. def(AST_Binary, function(compressor){
  19187. return binary(this.operator) || this.operator == "+"
  19188. && this.left.is_number(compressor)
  19189. && this.right.is_number(compressor);
  19190. });
  19191. def(AST_Assign, function(compressor){
  19192. return binary(this.operator.slice(0, -1))
  19193. || this.operator == "=" && this.right.is_number(compressor);
  19194. });
  19195. def(AST_Seq, function(compressor){
  19196. return this.cdr.is_number(compressor);
  19197. });
  19198. def(AST_Conditional, function(compressor){
  19199. return this.consequent.is_number(compressor) && this.alternative.is_number(compressor);
  19200. });
  19201. })(function(node, func){
  19202. node.DEFMETHOD("is_number", func);
  19203. });
  19204. // methods to determine if an expression has a string result type
  19205. (function (def){
  19206. def(AST_Node, return_false);
  19207. def(AST_String, return_true);
  19208. def(AST_UnaryPrefix, function(){
  19209. return this.operator == "typeof";
  19210. });
  19211. def(AST_Binary, function(compressor){
  19212. return this.operator == "+" &&
  19213. (this.left.is_string(compressor) || this.right.is_string(compressor));
  19214. });
  19215. def(AST_Assign, function(compressor){
  19216. return (this.operator == "=" || this.operator == "+=") && this.right.is_string(compressor);
  19217. });
  19218. def(AST_Seq, function(compressor){
  19219. return this.cdr.is_string(compressor);
  19220. });
  19221. def(AST_Conditional, function(compressor){
  19222. return this.consequent.is_string(compressor) && this.alternative.is_string(compressor);
  19223. });
  19224. })(function(node, func){
  19225. node.DEFMETHOD("is_string", func);
  19226. });
  19227. var unary_side_effects = makePredicate("delete ++ --");
  19228. function is_lhs(node, parent) {
  19229. if (parent instanceof AST_Unary && unary_side_effects(parent.operator)) return parent.expression;
  19230. if (parent instanceof AST_Assign && parent.left === node) return node;
  19231. }
  19232. (function (def){
  19233. AST_Node.DEFMETHOD("resolve_defines", function(compressor) {
  19234. if (!compressor.option("global_defs")) return;
  19235. var def = this._find_defs(compressor, "");
  19236. if (def) {
  19237. var node, parent = this, level = 0;
  19238. do {
  19239. node = parent;
  19240. parent = compressor.parent(level++);
  19241. } while (parent instanceof AST_PropAccess && parent.expression === node);
  19242. if (is_lhs(node, parent)) {
  19243. compressor.warn('global_defs ' + this.print_to_string() + ' redefined [{file}:{line},{col}]', this.start);
  19244. } else {
  19245. return def;
  19246. }
  19247. }
  19248. });
  19249. function to_node(value, orig) {
  19250. if (value instanceof AST_Node) return make_node(value.CTOR, orig, value);
  19251. if (Array.isArray(value)) return make_node(AST_Array, orig, {
  19252. elements: value.map(function(value) {
  19253. return to_node(value, orig);
  19254. })
  19255. });
  19256. if (value && typeof value == "object") {
  19257. var props = [];
  19258. for (var key in value) {
  19259. props.push(make_node(AST_ObjectKeyVal, orig, {
  19260. key: key,
  19261. value: to_node(value[key], orig)
  19262. }));
  19263. }
  19264. return make_node(AST_Object, orig, {
  19265. properties: props
  19266. });
  19267. }
  19268. return make_node_from_constant(value, orig);
  19269. }
  19270. def(AST_Node, noop);
  19271. def(AST_Dot, function(compressor, suffix){
  19272. return this.expression._find_defs(compressor, "." + this.property + suffix);
  19273. });
  19274. def(AST_SymbolRef, function(compressor, suffix){
  19275. if (!this.global()) return;
  19276. var name;
  19277. var defines = compressor.option("global_defs");
  19278. if (defines && HOP(defines, (name = this.name + suffix))) {
  19279. var node = to_node(defines[name], this);
  19280. var top = compressor.find_parent(AST_Toplevel);
  19281. node.walk(new TreeWalker(function(node) {
  19282. if (node instanceof AST_SymbolRef) {
  19283. node.scope = top;
  19284. node.thedef = top.def_global(node);
  19285. }
  19286. }));
  19287. return node;
  19288. }
  19289. });
  19290. })(function(node, func){
  19291. node.DEFMETHOD("_find_defs", func);
  19292. });
  19293. function best_of_expression(ast1, ast2) {
  19294. return ast1.print_to_string().length >
  19295. ast2.print_to_string().length
  19296. ? ast2 : ast1;
  19297. }
  19298. function best_of_statement(ast1, ast2) {
  19299. return best_of_expression(make_node(AST_SimpleStatement, ast1, {
  19300. body: ast1
  19301. }), make_node(AST_SimpleStatement, ast2, {
  19302. body: ast2
  19303. })).body;
  19304. }
  19305. function best_of(compressor, ast1, ast2) {
  19306. return (first_in_statement(compressor) ? best_of_statement : best_of_expression)(ast1, ast2);
  19307. }
  19308. // methods to evaluate a constant expression
  19309. (function (def){
  19310. // If the node has been successfully reduced to a constant,
  19311. // then its value is returned; otherwise the element itself
  19312. // is returned.
  19313. // They can be distinguished as constant value is never a
  19314. // descendant of AST_Node.
  19315. AST_Node.DEFMETHOD("evaluate", function(compressor){
  19316. if (!compressor.option("evaluate")) return this;
  19317. try {
  19318. var val = this._eval(compressor);
  19319. return !val || val instanceof RegExp || typeof val != "object" ? val : this;
  19320. } catch(ex) {
  19321. if (ex !== def) throw ex;
  19322. return this;
  19323. }
  19324. });
  19325. var unaryPrefix = makePredicate("! ~ - + void");
  19326. AST_Node.DEFMETHOD("is_constant", function(){
  19327. // Accomodate when compress option evaluate=false
  19328. // as well as the common constant expressions !0 and -1
  19329. if (this instanceof AST_Constant) {
  19330. return !(this instanceof AST_RegExp);
  19331. } else {
  19332. return this instanceof AST_UnaryPrefix
  19333. && this.expression instanceof AST_Constant
  19334. && unaryPrefix(this.operator);
  19335. }
  19336. });
  19337. // Obtain the constant value of an expression already known to be constant.
  19338. // Result only valid iff this.is_constant() is true.
  19339. AST_Node.DEFMETHOD("constant_value", function(compressor){
  19340. // Accomodate when option evaluate=false.
  19341. if (this instanceof AST_Constant && !(this instanceof AST_RegExp)) {
  19342. return this.value;
  19343. }
  19344. // Accomodate the common constant expressions !0 and -1 when option evaluate=false.
  19345. if (this instanceof AST_UnaryPrefix
  19346. && this.expression instanceof AST_Constant) switch (this.operator) {
  19347. case "!":
  19348. return !this.expression.value;
  19349. case "~":
  19350. return ~this.expression.value;
  19351. case "-":
  19352. return -this.expression.value;
  19353. case "+":
  19354. return +this.expression.value;
  19355. default:
  19356. throw new Error(string_template("Cannot evaluate unary expression {value}", {
  19357. value: this.print_to_string()
  19358. }));
  19359. }
  19360. var result = this.evaluate(compressor);
  19361. if (result !== this) {
  19362. return result;
  19363. }
  19364. throw new Error(string_template("Cannot evaluate constant [{file}:{line},{col}]", this.start));
  19365. });
  19366. def(AST_Statement, function(){
  19367. throw new Error(string_template("Cannot evaluate a statement [{file}:{line},{col}]", this.start));
  19368. });
  19369. def(AST_Lambda, function(){
  19370. throw def;
  19371. });
  19372. function ev(node, compressor) {
  19373. if (!compressor) throw new Error("Compressor must be passed");
  19374. return node._eval(compressor);
  19375. };
  19376. def(AST_Node, function(){
  19377. throw def; // not constant
  19378. });
  19379. def(AST_Constant, function(){
  19380. return this.getValue();
  19381. });
  19382. def(AST_Array, function(compressor){
  19383. if (compressor.option("unsafe")) {
  19384. return this.elements.map(function(element) {
  19385. return ev(element, compressor);
  19386. });
  19387. }
  19388. throw def;
  19389. });
  19390. def(AST_Object, function(compressor){
  19391. if (compressor.option("unsafe")) {
  19392. var val = {};
  19393. for (var i = 0, len = this.properties.length; i < len; i++) {
  19394. var prop = this.properties[i];
  19395. var key = prop.key;
  19396. if (key instanceof AST_Symbol) {
  19397. key = key.name;
  19398. } else if (key instanceof AST_Node) {
  19399. key = ev(key, compressor);
  19400. }
  19401. if (typeof Object.prototype[key] === 'function') {
  19402. throw def;
  19403. }
  19404. val[key] = ev(prop.value, compressor);
  19405. }
  19406. return val;
  19407. }
  19408. throw def;
  19409. });
  19410. def(AST_UnaryPrefix, function(compressor){
  19411. var e = this.expression;
  19412. switch (this.operator) {
  19413. case "!": return !ev(e, compressor);
  19414. case "typeof":
  19415. // Function would be evaluated to an array and so typeof would
  19416. // incorrectly return 'object'. Hence making is a special case.
  19417. if (e instanceof AST_Function) return typeof function(){};
  19418. e = ev(e, compressor);
  19419. // typeof <RegExp> returns "object" or "function" on different platforms
  19420. // so cannot evaluate reliably
  19421. if (e instanceof RegExp) throw def;
  19422. return typeof e;
  19423. case "void": return void ev(e, compressor);
  19424. case "~": return ~ev(e, compressor);
  19425. case "-": return -ev(e, compressor);
  19426. case "+": return +ev(e, compressor);
  19427. }
  19428. throw def;
  19429. });
  19430. def(AST_Binary, function(c){
  19431. var left = this.left, right = this.right, result;
  19432. switch (this.operator) {
  19433. case "&&" : result = ev(left, c) && ev(right, c); break;
  19434. case "||" : result = ev(left, c) || ev(right, c); break;
  19435. case "|" : result = ev(left, c) | ev(right, c); break;
  19436. case "&" : result = ev(left, c) & ev(right, c); break;
  19437. case "^" : result = ev(left, c) ^ ev(right, c); break;
  19438. case "+" : result = ev(left, c) + ev(right, c); break;
  19439. case "*" : result = ev(left, c) * ev(right, c); break;
  19440. case "/" : result = ev(left, c) / ev(right, c); break;
  19441. case "%" : result = ev(left, c) % ev(right, c); break;
  19442. case "-" : result = ev(left, c) - ev(right, c); break;
  19443. case "<<" : result = ev(left, c) << ev(right, c); break;
  19444. case ">>" : result = ev(left, c) >> ev(right, c); break;
  19445. case ">>>" : result = ev(left, c) >>> ev(right, c); break;
  19446. case "==" : result = ev(left, c) == ev(right, c); break;
  19447. case "===" : result = ev(left, c) === ev(right, c); break;
  19448. case "!=" : result = ev(left, c) != ev(right, c); break;
  19449. case "!==" : result = ev(left, c) !== ev(right, c); break;
  19450. case "<" : result = ev(left, c) < ev(right, c); break;
  19451. case "<=" : result = ev(left, c) <= ev(right, c); break;
  19452. case ">" : result = ev(left, c) > ev(right, c); break;
  19453. case ">=" : result = ev(left, c) >= ev(right, c); break;
  19454. default:
  19455. throw def;
  19456. }
  19457. if (isNaN(result) && c.find_parent(AST_With)) {
  19458. // leave original expression as is
  19459. throw def;
  19460. }
  19461. return result;
  19462. });
  19463. def(AST_Conditional, function(compressor){
  19464. return ev(this.condition, compressor)
  19465. ? ev(this.consequent, compressor)
  19466. : ev(this.alternative, compressor);
  19467. });
  19468. def(AST_SymbolRef, function(compressor){
  19469. if (!compressor.option("reduce_vars") || this._evaluating) throw def;
  19470. this._evaluating = true;
  19471. try {
  19472. var fixed = this.fixed_value();
  19473. if (!fixed) throw def;
  19474. var value = ev(fixed, compressor);
  19475. if (!HOP(fixed, "_eval")) fixed._eval = function() {
  19476. return value;
  19477. };
  19478. if (value && typeof value == "object" && this.definition().escaped) throw def;
  19479. return value;
  19480. } finally {
  19481. this._evaluating = false;
  19482. }
  19483. });
  19484. def(AST_PropAccess, function(compressor){
  19485. if (compressor.option("unsafe")) {
  19486. var key = this.property;
  19487. if (key instanceof AST_Node) {
  19488. key = ev(key, compressor);
  19489. }
  19490. var val = ev(this.expression, compressor);
  19491. if (val && HOP(val, key)) {
  19492. return val[key];
  19493. }
  19494. }
  19495. throw def;
  19496. });
  19497. })(function(node, func){
  19498. node.DEFMETHOD("_eval", func);
  19499. });
  19500. // method to negate an expression
  19501. (function(def){
  19502. function basic_negation(exp) {
  19503. return make_node(AST_UnaryPrefix, exp, {
  19504. operator: "!",
  19505. expression: exp
  19506. });
  19507. }
  19508. function best(orig, alt, first_in_statement) {
  19509. var negated = basic_negation(orig);
  19510. if (first_in_statement) {
  19511. var stat = make_node(AST_SimpleStatement, alt, {
  19512. body: alt
  19513. });
  19514. return best_of_expression(negated, stat) === stat ? alt : negated;
  19515. }
  19516. return best_of_expression(negated, alt);
  19517. }
  19518. def(AST_Node, function(){
  19519. return basic_negation(this);
  19520. });
  19521. def(AST_Statement, function(){
  19522. throw new Error("Cannot negate a statement");
  19523. });
  19524. def(AST_Function, function(){
  19525. return basic_negation(this);
  19526. });
  19527. def(AST_UnaryPrefix, function(){
  19528. if (this.operator == "!")
  19529. return this.expression;
  19530. return basic_negation(this);
  19531. });
  19532. def(AST_Seq, function(compressor){
  19533. var self = this.clone();
  19534. self.cdr = self.cdr.negate(compressor);
  19535. return self;
  19536. });
  19537. def(AST_Conditional, function(compressor, first_in_statement){
  19538. var self = this.clone();
  19539. self.consequent = self.consequent.negate(compressor);
  19540. self.alternative = self.alternative.negate(compressor);
  19541. return best(this, self, first_in_statement);
  19542. });
  19543. def(AST_Binary, function(compressor, first_in_statement){
  19544. var self = this.clone(), op = this.operator;
  19545. if (compressor.option("unsafe_comps")) {
  19546. switch (op) {
  19547. case "<=" : self.operator = ">" ; return self;
  19548. case "<" : self.operator = ">=" ; return self;
  19549. case ">=" : self.operator = "<" ; return self;
  19550. case ">" : self.operator = "<=" ; return self;
  19551. }
  19552. }
  19553. switch (op) {
  19554. case "==" : self.operator = "!="; return self;
  19555. case "!=" : self.operator = "=="; return self;
  19556. case "===": self.operator = "!=="; return self;
  19557. case "!==": self.operator = "==="; return self;
  19558. case "&&":
  19559. self.operator = "||";
  19560. self.left = self.left.negate(compressor, first_in_statement);
  19561. self.right = self.right.negate(compressor);
  19562. return best(this, self, first_in_statement);
  19563. case "||":
  19564. self.operator = "&&";
  19565. self.left = self.left.negate(compressor, first_in_statement);
  19566. self.right = self.right.negate(compressor);
  19567. return best(this, self, first_in_statement);
  19568. }
  19569. return basic_negation(this);
  19570. });
  19571. })(function(node, func){
  19572. node.DEFMETHOD("negate", function(compressor, first_in_statement){
  19573. return func.call(this, compressor, first_in_statement);
  19574. });
  19575. });
  19576. AST_Call.DEFMETHOD("has_pure_annotation", function(compressor) {
  19577. if (!compressor.option("side_effects")) return false;
  19578. if (this.pure !== undefined) return this.pure;
  19579. var pure = false;
  19580. var comments, last_comment;
  19581. if (this.start
  19582. && (comments = this.start.comments_before)
  19583. && comments.length
  19584. && /[@#]__PURE__/.test((last_comment = comments[comments.length - 1]).value)) {
  19585. pure = last_comment;
  19586. }
  19587. return this.pure = pure;
  19588. });
  19589. // determine if expression has side effects
  19590. (function(def){
  19591. def(AST_Node, return_true);
  19592. def(AST_EmptyStatement, return_false);
  19593. def(AST_Constant, return_false);
  19594. def(AST_This, return_false);
  19595. def(AST_Call, function(compressor){
  19596. if (!this.has_pure_annotation(compressor) && compressor.pure_funcs(this)) return true;
  19597. for (var i = this.args.length; --i >= 0;) {
  19598. if (this.args[i].has_side_effects(compressor))
  19599. return true;
  19600. }
  19601. return false;
  19602. });
  19603. function any(list, compressor) {
  19604. for (var i = list.length; --i >= 0;)
  19605. if (list[i].has_side_effects(compressor))
  19606. return true;
  19607. return false;
  19608. }
  19609. def(AST_Block, function(compressor){
  19610. return any(this.body, compressor);
  19611. });
  19612. def(AST_Switch, function(compressor){
  19613. return this.expression.has_side_effects(compressor)
  19614. || any(this.body, compressor);
  19615. });
  19616. def(AST_Case, function(compressor){
  19617. return this.expression.has_side_effects(compressor)
  19618. || any(this.body, compressor);
  19619. });
  19620. def(AST_Try, function(compressor){
  19621. return any(this.body, compressor)
  19622. || this.bcatch && this.bcatch.has_side_effects(compressor)
  19623. || this.bfinally && this.bfinally.has_side_effects(compressor);
  19624. });
  19625. def(AST_If, function(compressor){
  19626. return this.condition.has_side_effects(compressor)
  19627. || this.body && this.body.has_side_effects(compressor)
  19628. || this.alternative && this.alternative.has_side_effects(compressor);
  19629. });
  19630. def(AST_LabeledStatement, function(compressor){
  19631. return this.body.has_side_effects(compressor);
  19632. });
  19633. def(AST_SimpleStatement, function(compressor){
  19634. return this.body.has_side_effects(compressor);
  19635. });
  19636. def(AST_Defun, return_true);
  19637. def(AST_Function, return_false);
  19638. def(AST_Binary, function(compressor){
  19639. return this.left.has_side_effects(compressor)
  19640. || this.right.has_side_effects(compressor);
  19641. });
  19642. def(AST_Assign, return_true);
  19643. def(AST_Conditional, function(compressor){
  19644. return this.condition.has_side_effects(compressor)
  19645. || this.consequent.has_side_effects(compressor)
  19646. || this.alternative.has_side_effects(compressor);
  19647. });
  19648. def(AST_Unary, function(compressor){
  19649. return unary_side_effects(this.operator)
  19650. || this.expression.has_side_effects(compressor);
  19651. });
  19652. def(AST_SymbolRef, function(compressor){
  19653. return this.undeclared();
  19654. });
  19655. def(AST_Object, function(compressor){
  19656. return any(this.properties, compressor);
  19657. });
  19658. def(AST_ObjectProperty, function(compressor){
  19659. return this.value.has_side_effects(compressor);
  19660. });
  19661. def(AST_Array, function(compressor){
  19662. return any(this.elements, compressor);
  19663. });
  19664. def(AST_Dot, function(compressor){
  19665. return this.expression.may_throw_on_access(compressor)
  19666. || this.expression.has_side_effects(compressor);
  19667. });
  19668. def(AST_Sub, function(compressor){
  19669. return this.expression.may_throw_on_access(compressor)
  19670. || this.expression.has_side_effects(compressor)
  19671. || this.property.has_side_effects(compressor);
  19672. });
  19673. def(AST_Seq, function(compressor){
  19674. return this.car.has_side_effects(compressor)
  19675. || this.cdr.has_side_effects(compressor);
  19676. });
  19677. })(function(node, func){
  19678. node.DEFMETHOD("has_side_effects", func);
  19679. });
  19680. // tell me if a statement aborts
  19681. function aborts(thing) {
  19682. return thing && thing.aborts();
  19683. };
  19684. (function(def){
  19685. def(AST_Statement, return_null);
  19686. def(AST_Jump, return_this);
  19687. function block_aborts(){
  19688. var n = this.body.length;
  19689. return n > 0 && aborts(this.body[n - 1]);
  19690. };
  19691. def(AST_BlockStatement, block_aborts);
  19692. def(AST_SwitchBranch, block_aborts);
  19693. def(AST_If, function(){
  19694. return this.alternative && aborts(this.body) && aborts(this.alternative) && this;
  19695. });
  19696. })(function(node, func){
  19697. node.DEFMETHOD("aborts", func);
  19698. });
  19699. /* -----[ optimizers ]----- */
  19700. OPT(AST_Directive, function(self, compressor){
  19701. if (compressor.has_directive(self.value) !== self) {
  19702. return make_node(AST_EmptyStatement, self);
  19703. }
  19704. return self;
  19705. });
  19706. OPT(AST_Debugger, function(self, compressor){
  19707. if (compressor.option("drop_debugger"))
  19708. return make_node(AST_EmptyStatement, self);
  19709. return self;
  19710. });
  19711. OPT(AST_LabeledStatement, function(self, compressor){
  19712. if (self.body instanceof AST_Break
  19713. && compressor.loopcontrol_target(self.body) === self.body) {
  19714. return make_node(AST_EmptyStatement, self);
  19715. }
  19716. return self.label.references.length == 0 ? self.body : self;
  19717. });
  19718. OPT(AST_Block, function(self, compressor){
  19719. self.body = tighten_body(self.body, compressor);
  19720. return self;
  19721. });
  19722. OPT(AST_BlockStatement, function(self, compressor){
  19723. self.body = tighten_body(self.body, compressor);
  19724. switch (self.body.length) {
  19725. case 1: return self.body[0];
  19726. case 0: return make_node(AST_EmptyStatement, self);
  19727. }
  19728. return self;
  19729. });
  19730. AST_Scope.DEFMETHOD("drop_unused", function(compressor){
  19731. var self = this;
  19732. if (compressor.has_directive("use asm")) return self;
  19733. var toplevel = compressor.option("toplevel");
  19734. if (compressor.option("unused")
  19735. && (!(self instanceof AST_Toplevel) || toplevel)
  19736. && !self.uses_eval
  19737. && !self.uses_with) {
  19738. var assign_as_unused = !/keep_assign/.test(compressor.option("unused"));
  19739. var drop_funcs = /funcs/.test(toplevel);
  19740. var drop_vars = /vars/.test(toplevel);
  19741. if (!(self instanceof AST_Toplevel) || toplevel == true) {
  19742. drop_funcs = drop_vars = true;
  19743. }
  19744. var in_use = [];
  19745. var in_use_ids = Object.create(null); // avoid expensive linear scans of in_use
  19746. if (self instanceof AST_Toplevel && compressor.top_retain) {
  19747. self.variables.each(function(def) {
  19748. if (compressor.top_retain(def) && !(def.id in in_use_ids)) {
  19749. in_use_ids[def.id] = true;
  19750. in_use.push(def);
  19751. }
  19752. });
  19753. }
  19754. var initializations = new Dictionary();
  19755. // pass 1: find out which symbols are directly used in
  19756. // this scope (not in nested scopes).
  19757. var scope = this;
  19758. var tw = new TreeWalker(function(node, descend){
  19759. if (node !== self) {
  19760. if (node instanceof AST_Defun) {
  19761. if (!drop_funcs && scope === self) {
  19762. var node_def = node.name.definition();
  19763. if (!(node_def.id in in_use_ids)) {
  19764. in_use_ids[node_def.id] = true;
  19765. in_use.push(node_def);
  19766. }
  19767. }
  19768. initializations.add(node.name.name, node);
  19769. return true; // don't go in nested scopes
  19770. }
  19771. if (node instanceof AST_Definitions && scope === self) {
  19772. node.definitions.forEach(function(def){
  19773. if (!drop_vars) {
  19774. var node_def = def.name.definition();
  19775. if (!(node_def.id in in_use_ids)) {
  19776. in_use_ids[node_def.id] = true;
  19777. in_use.push(node_def);
  19778. }
  19779. }
  19780. if (def.value) {
  19781. initializations.add(def.name.name, def.value);
  19782. if (def.value.has_side_effects(compressor)) {
  19783. def.value.walk(tw);
  19784. }
  19785. }
  19786. });
  19787. return true;
  19788. }
  19789. if (assign_as_unused
  19790. && node instanceof AST_Assign
  19791. && node.operator == "="
  19792. && node.left instanceof AST_SymbolRef
  19793. && !is_reference_const(node.left)
  19794. && scope === self) {
  19795. node.right.walk(tw);
  19796. return true;
  19797. }
  19798. if (node instanceof AST_SymbolRef) {
  19799. var node_def = node.definition();
  19800. if (!(node_def.id in in_use_ids)) {
  19801. in_use_ids[node_def.id] = true;
  19802. in_use.push(node_def);
  19803. }
  19804. return true;
  19805. }
  19806. if (node instanceof AST_Scope) {
  19807. var save_scope = scope;
  19808. scope = node;
  19809. descend();
  19810. scope = save_scope;
  19811. return true;
  19812. }
  19813. }
  19814. });
  19815. self.walk(tw);
  19816. // pass 2: for every used symbol we need to walk its
  19817. // initialization code to figure out if it uses other
  19818. // symbols (that may not be in_use).
  19819. for (var i = 0; i < in_use.length; ++i) {
  19820. in_use[i].orig.forEach(function(decl){
  19821. // undeclared globals will be instanceof AST_SymbolRef
  19822. var init = initializations.get(decl.name);
  19823. if (init) init.forEach(function(init){
  19824. var tw = new TreeWalker(function(node){
  19825. if (node instanceof AST_SymbolRef) {
  19826. var node_def = node.definition();
  19827. if (!(node_def.id in in_use_ids)) {
  19828. in_use_ids[node_def.id] = true;
  19829. in_use.push(node_def);
  19830. }
  19831. }
  19832. });
  19833. init.walk(tw);
  19834. });
  19835. });
  19836. }
  19837. // pass 3: we should drop declarations not in_use
  19838. var tt = new TreeTransformer(
  19839. function before(node, descend, in_list) {
  19840. if (node instanceof AST_Function
  19841. && node.name
  19842. && !compressor.option("keep_fnames")) {
  19843. var def = node.name.definition();
  19844. // any declarations with same name will overshadow
  19845. // name of this anonymous function and can therefore
  19846. // never be used anywhere
  19847. if (!(def.id in in_use_ids) || def.orig.length > 1)
  19848. node.name = null;
  19849. }
  19850. if (node instanceof AST_Lambda && !(node instanceof AST_Accessor)) {
  19851. var trim = !compressor.option("keep_fargs");
  19852. for (var a = node.argnames, i = a.length; --i >= 0;) {
  19853. var sym = a[i];
  19854. if (!(sym.definition().id in in_use_ids)) {
  19855. sym.__unused = true;
  19856. if (trim) {
  19857. a.pop();
  19858. compressor[sym.unreferenced() ? "warn" : "info"]("Dropping unused function argument {name} [{file}:{line},{col}]", {
  19859. name : sym.name,
  19860. file : sym.start.file,
  19861. line : sym.start.line,
  19862. col : sym.start.col
  19863. });
  19864. }
  19865. }
  19866. else {
  19867. trim = false;
  19868. }
  19869. }
  19870. }
  19871. if (drop_funcs && node instanceof AST_Defun && node !== self) {
  19872. if (!(node.name.definition().id in in_use_ids)) {
  19873. compressor[node.name.unreferenced() ? "warn" : "info"]("Dropping unused function {name} [{file}:{line},{col}]", {
  19874. name : node.name.name,
  19875. file : node.name.start.file,
  19876. line : node.name.start.line,
  19877. col : node.name.start.col
  19878. });
  19879. return make_node(AST_EmptyStatement, node);
  19880. }
  19881. return node;
  19882. }
  19883. if (drop_vars && node instanceof AST_Definitions && !(tt.parent() instanceof AST_ForIn && tt.parent().init === node)) {
  19884. var def = node.definitions.filter(function(def){
  19885. if (def.value) def.value = def.value.transform(tt);
  19886. var sym = def.name.definition();
  19887. if (sym.id in in_use_ids) return true;
  19888. if (sym.orig[0] instanceof AST_SymbolCatch) {
  19889. def.value = def.value && def.value.drop_side_effect_free(compressor);
  19890. return true;
  19891. }
  19892. var w = {
  19893. name : def.name.name,
  19894. file : def.name.start.file,
  19895. line : def.name.start.line,
  19896. col : def.name.start.col
  19897. };
  19898. if (def.value && (def._unused_side_effects = def.value.drop_side_effect_free(compressor))) {
  19899. compressor.warn("Side effects in initialization of unused variable {name} [{file}:{line},{col}]", w);
  19900. return true;
  19901. }
  19902. compressor[def.name.unreferenced() ? "warn" : "info"]("Dropping unused variable {name} [{file}:{line},{col}]", w);
  19903. return false;
  19904. });
  19905. // place uninitialized names at the start
  19906. def = mergeSort(def, function(a, b){
  19907. if (!a.value && b.value) return -1;
  19908. if (!b.value && a.value) return 1;
  19909. return 0;
  19910. });
  19911. // for unused names whose initialization has
  19912. // side effects, we can cascade the init. code
  19913. // into the next one, or next statement.
  19914. var side_effects = [];
  19915. for (var i = 0; i < def.length;) {
  19916. var x = def[i];
  19917. if (x._unused_side_effects) {
  19918. side_effects.push(x._unused_side_effects);
  19919. def.splice(i, 1);
  19920. } else {
  19921. if (side_effects.length > 0) {
  19922. side_effects.push(x.value);
  19923. x.value = AST_Seq.from_array(side_effects);
  19924. side_effects = [];
  19925. }
  19926. ++i;
  19927. }
  19928. }
  19929. if (side_effects.length > 0) {
  19930. side_effects = make_node(AST_BlockStatement, node, {
  19931. body: [ make_node(AST_SimpleStatement, node, {
  19932. body: AST_Seq.from_array(side_effects)
  19933. }) ]
  19934. });
  19935. } else {
  19936. side_effects = null;
  19937. }
  19938. if (def.length == 0 && !side_effects) {
  19939. return make_node(AST_EmptyStatement, node);
  19940. }
  19941. if (def.length == 0) {
  19942. return in_list ? MAP.splice(side_effects.body) : side_effects;
  19943. }
  19944. node.definitions = def;
  19945. if (side_effects) {
  19946. side_effects.body.unshift(node);
  19947. return in_list ? MAP.splice(side_effects.body) : side_effects;
  19948. }
  19949. return node;
  19950. }
  19951. if (drop_vars && assign_as_unused
  19952. && node instanceof AST_Assign
  19953. && node.operator == "="
  19954. && node.left instanceof AST_SymbolRef) {
  19955. var def = node.left.definition();
  19956. if (!(def.id in in_use_ids)
  19957. && self.variables.get(def.name) === def) {
  19958. return maintain_this_binding(tt.parent(), node, node.right.transform(tt));
  19959. }
  19960. }
  19961. // certain combination of unused name + side effect leads to:
  19962. // https://github.com/mishoo/UglifyJS2/issues/44
  19963. // https://github.com/mishoo/UglifyJS2/issues/1830
  19964. // that's an invalid AST.
  19965. // We fix it at this stage by moving the `var` outside the `for`.
  19966. if (node instanceof AST_For) {
  19967. descend(node, this);
  19968. if (node.init instanceof AST_BlockStatement) {
  19969. var block = node.init;
  19970. node.init = block.body.pop();
  19971. block.body.push(node);
  19972. return in_list ? MAP.splice(block.body) : block;
  19973. } else if (is_empty(node.init)) {
  19974. node.init = null;
  19975. }
  19976. return node;
  19977. }
  19978. if (node instanceof AST_LabeledStatement && node.body instanceof AST_For) {
  19979. descend(node, this);
  19980. if (node.body instanceof AST_BlockStatement) {
  19981. var block = node.body;
  19982. node.body = block.body.pop();
  19983. block.body.push(node);
  19984. return in_list ? MAP.splice(block.body) : block;
  19985. }
  19986. return node;
  19987. }
  19988. if (node instanceof AST_Scope && node !== self)
  19989. return node;
  19990. }
  19991. );
  19992. self.transform(tt);
  19993. }
  19994. });
  19995. AST_Scope.DEFMETHOD("hoist_declarations", function(compressor){
  19996. var self = this;
  19997. if (compressor.has_directive("use asm")) return self;
  19998. var hoist_funs = compressor.option("hoist_funs");
  19999. var hoist_vars = compressor.option("hoist_vars");
  20000. if (hoist_funs || hoist_vars) {
  20001. var dirs = [];
  20002. var hoisted = [];
  20003. var vars = new Dictionary(), vars_found = 0, var_decl = 0;
  20004. // let's count var_decl first, we seem to waste a lot of
  20005. // space if we hoist `var` when there's only one.
  20006. self.walk(new TreeWalker(function(node){
  20007. if (node instanceof AST_Scope && node !== self)
  20008. return true;
  20009. if (node instanceof AST_Var) {
  20010. ++var_decl;
  20011. return true;
  20012. }
  20013. }));
  20014. hoist_vars = hoist_vars && var_decl > 1;
  20015. var tt = new TreeTransformer(
  20016. function before(node) {
  20017. if (node !== self) {
  20018. if (node instanceof AST_Directive) {
  20019. dirs.push(node);
  20020. return make_node(AST_EmptyStatement, node);
  20021. }
  20022. if (node instanceof AST_Defun && hoist_funs) {
  20023. hoisted.push(node);
  20024. return make_node(AST_EmptyStatement, node);
  20025. }
  20026. if (node instanceof AST_Var && hoist_vars) {
  20027. node.definitions.forEach(function(def){
  20028. vars.set(def.name.name, def);
  20029. ++vars_found;
  20030. });
  20031. var seq = node.to_assignments(compressor);
  20032. var p = tt.parent();
  20033. if (p instanceof AST_ForIn && p.init === node) {
  20034. if (seq == null) {
  20035. var def = node.definitions[0].name;
  20036. return make_node(AST_SymbolRef, def, def);
  20037. }
  20038. return seq;
  20039. }
  20040. if (p instanceof AST_For && p.init === node) {
  20041. return seq;
  20042. }
  20043. if (!seq) return make_node(AST_EmptyStatement, node);
  20044. return make_node(AST_SimpleStatement, node, {
  20045. body: seq
  20046. });
  20047. }
  20048. if (node instanceof AST_Scope)
  20049. return node; // to avoid descending in nested scopes
  20050. }
  20051. }
  20052. );
  20053. self = self.transform(tt);
  20054. if (vars_found > 0) {
  20055. // collect only vars which don't show up in self's arguments list
  20056. var defs = [];
  20057. vars.each(function(def, name){
  20058. if (self instanceof AST_Lambda
  20059. && find_if(function(x){ return x.name == def.name.name },
  20060. self.argnames)) {
  20061. vars.del(name);
  20062. } else {
  20063. def = def.clone();
  20064. def.value = null;
  20065. defs.push(def);
  20066. vars.set(name, def);
  20067. }
  20068. });
  20069. if (defs.length > 0) {
  20070. // try to merge in assignments
  20071. for (var i = 0; i < self.body.length;) {
  20072. if (self.body[i] instanceof AST_SimpleStatement) {
  20073. var expr = self.body[i].body, sym, assign;
  20074. if (expr instanceof AST_Assign
  20075. && expr.operator == "="
  20076. && (sym = expr.left) instanceof AST_Symbol
  20077. && vars.has(sym.name))
  20078. {
  20079. var def = vars.get(sym.name);
  20080. if (def.value) break;
  20081. def.value = expr.right;
  20082. remove(defs, def);
  20083. defs.push(def);
  20084. self.body.splice(i, 1);
  20085. continue;
  20086. }
  20087. if (expr instanceof AST_Seq
  20088. && (assign = expr.car) instanceof AST_Assign
  20089. && assign.operator == "="
  20090. && (sym = assign.left) instanceof AST_Symbol
  20091. && vars.has(sym.name))
  20092. {
  20093. var def = vars.get(sym.name);
  20094. if (def.value) break;
  20095. def.value = assign.right;
  20096. remove(defs, def);
  20097. defs.push(def);
  20098. self.body[i].body = expr.cdr;
  20099. continue;
  20100. }
  20101. }
  20102. if (self.body[i] instanceof AST_EmptyStatement) {
  20103. self.body.splice(i, 1);
  20104. continue;
  20105. }
  20106. if (self.body[i] instanceof AST_BlockStatement) {
  20107. var tmp = [ i, 1 ].concat(self.body[i].body);
  20108. self.body.splice.apply(self.body, tmp);
  20109. continue;
  20110. }
  20111. break;
  20112. }
  20113. defs = make_node(AST_Var, self, {
  20114. definitions: defs
  20115. });
  20116. hoisted.push(defs);
  20117. };
  20118. }
  20119. self.body = dirs.concat(hoisted, self.body);
  20120. }
  20121. return self;
  20122. });
  20123. // drop_side_effect_free()
  20124. // remove side-effect-free parts which only affects return value
  20125. (function(def){
  20126. // Drop side-effect-free elements from an array of expressions.
  20127. // Returns an array of expressions with side-effects or null
  20128. // if all elements were dropped. Note: original array may be
  20129. // returned if nothing changed.
  20130. function trim(nodes, compressor, first_in_statement) {
  20131. var ret = [], changed = false;
  20132. for (var i = 0, len = nodes.length; i < len; i++) {
  20133. var node = nodes[i].drop_side_effect_free(compressor, first_in_statement);
  20134. changed |= node !== nodes[i];
  20135. if (node) {
  20136. ret.push(node);
  20137. first_in_statement = false;
  20138. }
  20139. }
  20140. return changed ? ret.length ? ret : null : nodes;
  20141. }
  20142. def(AST_Node, return_this);
  20143. def(AST_Constant, return_null);
  20144. def(AST_This, return_null);
  20145. def(AST_Call, function(compressor, first_in_statement){
  20146. if (!this.has_pure_annotation(compressor) && compressor.pure_funcs(this)) {
  20147. if (this.expression instanceof AST_Function
  20148. && (!this.expression.name || !this.expression.name.definition().references.length)) {
  20149. var node = this.clone();
  20150. node.expression = node.expression.process_expression(false, compressor);
  20151. return node;
  20152. }
  20153. return this;
  20154. }
  20155. if (this.pure) {
  20156. compressor.warn("Dropping __PURE__ call [{file}:{line},{col}]", this.start);
  20157. this.pure.value = this.pure.value.replace(/[@#]__PURE__/g, ' ');
  20158. }
  20159. var args = trim(this.args, compressor, first_in_statement);
  20160. return args && AST_Seq.from_array(args);
  20161. });
  20162. def(AST_Accessor, return_null);
  20163. def(AST_Function, return_null);
  20164. def(AST_Binary, function(compressor, first_in_statement){
  20165. var right = this.right.drop_side_effect_free(compressor);
  20166. if (!right) return this.left.drop_side_effect_free(compressor, first_in_statement);
  20167. switch (this.operator) {
  20168. case "&&":
  20169. case "||":
  20170. if (right === this.right) return this;
  20171. var node = this.clone();
  20172. node.right = right;
  20173. return node;
  20174. default:
  20175. var left = this.left.drop_side_effect_free(compressor, first_in_statement);
  20176. if (!left) return this.right.drop_side_effect_free(compressor, first_in_statement);
  20177. return make_node(AST_Seq, this, {
  20178. car: left,
  20179. cdr: right
  20180. });
  20181. }
  20182. });
  20183. def(AST_Assign, return_this);
  20184. def(AST_Conditional, function(compressor){
  20185. var consequent = this.consequent.drop_side_effect_free(compressor);
  20186. var alternative = this.alternative.drop_side_effect_free(compressor);
  20187. if (consequent === this.consequent && alternative === this.alternative) return this;
  20188. if (!consequent) return alternative ? make_node(AST_Binary, this, {
  20189. operator: "||",
  20190. left: this.condition,
  20191. right: alternative
  20192. }) : this.condition.drop_side_effect_free(compressor);
  20193. if (!alternative) return make_node(AST_Binary, this, {
  20194. operator: "&&",
  20195. left: this.condition,
  20196. right: consequent
  20197. });
  20198. var node = this.clone();
  20199. node.consequent = consequent;
  20200. node.alternative = alternative;
  20201. return node;
  20202. });
  20203. def(AST_Unary, function(compressor, first_in_statement){
  20204. if (unary_side_effects(this.operator)) return this;
  20205. if (this.operator == "typeof" && this.expression instanceof AST_SymbolRef) return null;
  20206. var expression = this.expression.drop_side_effect_free(compressor, first_in_statement);
  20207. if (first_in_statement
  20208. && this instanceof AST_UnaryPrefix
  20209. && is_iife_call(expression)) {
  20210. if (expression === this.expression && this.operator.length === 1) return this;
  20211. return make_node(AST_UnaryPrefix, this, {
  20212. operator: this.operator.length === 1 ? this.operator : "!",
  20213. expression: expression
  20214. });
  20215. }
  20216. return expression;
  20217. });
  20218. def(AST_SymbolRef, function() {
  20219. return this.undeclared() ? this : null;
  20220. });
  20221. def(AST_Object, function(compressor, first_in_statement){
  20222. var values = trim(this.properties, compressor, first_in_statement);
  20223. return values && AST_Seq.from_array(values);
  20224. });
  20225. def(AST_ObjectProperty, function(compressor, first_in_statement){
  20226. return this.value.drop_side_effect_free(compressor, first_in_statement);
  20227. });
  20228. def(AST_Array, function(compressor, first_in_statement){
  20229. var values = trim(this.elements, compressor, first_in_statement);
  20230. return values && AST_Seq.from_array(values);
  20231. });
  20232. def(AST_Dot, function(compressor, first_in_statement){
  20233. if (this.expression.may_throw_on_access(compressor)) return this;
  20234. return this.expression.drop_side_effect_free(compressor, first_in_statement);
  20235. });
  20236. def(AST_Sub, function(compressor, first_in_statement){
  20237. if (this.expression.may_throw_on_access(compressor)) return this;
  20238. var expression = this.expression.drop_side_effect_free(compressor, first_in_statement);
  20239. if (!expression) return this.property.drop_side_effect_free(compressor, first_in_statement);
  20240. var property = this.property.drop_side_effect_free(compressor);
  20241. if (!property) return expression;
  20242. return make_node(AST_Seq, this, {
  20243. car: expression,
  20244. cdr: property
  20245. });
  20246. });
  20247. def(AST_Seq, function(compressor){
  20248. var cdr = this.cdr.drop_side_effect_free(compressor);
  20249. if (cdr === this.cdr) return this;
  20250. if (!cdr) return this.car;
  20251. return make_node(AST_Seq, this, {
  20252. car: this.car,
  20253. cdr: cdr
  20254. });
  20255. });
  20256. })(function(node, func){
  20257. node.DEFMETHOD("drop_side_effect_free", func);
  20258. });
  20259. OPT(AST_SimpleStatement, function(self, compressor){
  20260. if (compressor.option("side_effects")) {
  20261. var body = self.body;
  20262. var node = body.drop_side_effect_free(compressor, true);
  20263. if (!node) {
  20264. compressor.warn("Dropping side-effect-free statement [{file}:{line},{col}]", self.start);
  20265. return make_node(AST_EmptyStatement, self);
  20266. }
  20267. if (node !== body) {
  20268. return make_node(AST_SimpleStatement, self, { body: node });
  20269. }
  20270. }
  20271. return self;
  20272. });
  20273. OPT(AST_DWLoop, function(self, compressor){
  20274. if (!compressor.option("loops")) return self;
  20275. var cond = self.condition.evaluate(compressor);
  20276. if (cond !== self.condition) {
  20277. if (cond) {
  20278. return make_node(AST_For, self, {
  20279. body: self.body
  20280. });
  20281. }
  20282. if (compressor.option("dead_code") && self instanceof AST_While) {
  20283. var a = [];
  20284. extract_declarations_from_unreachable_code(compressor, self.body, a);
  20285. return make_node(AST_BlockStatement, self, { body: a }).optimize(compressor);
  20286. }
  20287. if (self instanceof AST_Do) {
  20288. var has_loop_control = false;
  20289. var tw = new TreeWalker(function(node) {
  20290. if (node instanceof AST_Scope || has_loop_control) return true;
  20291. if (node instanceof AST_LoopControl && tw.loopcontrol_target(node) === self)
  20292. return has_loop_control = true;
  20293. });
  20294. var parent = compressor.parent();
  20295. (parent instanceof AST_LabeledStatement ? parent : self).walk(tw);
  20296. if (!has_loop_control) return self.body;
  20297. }
  20298. }
  20299. if (self instanceof AST_While) {
  20300. return make_node(AST_For, self, self).optimize(compressor);
  20301. }
  20302. return self;
  20303. });
  20304. function if_break_in_loop(self, compressor) {
  20305. function drop_it(rest) {
  20306. rest = as_statement_array(rest);
  20307. if (self.body instanceof AST_BlockStatement) {
  20308. self.body = self.body.clone();
  20309. self.body.body = rest.concat(self.body.body.slice(1));
  20310. self.body = self.body.transform(compressor);
  20311. } else {
  20312. self.body = make_node(AST_BlockStatement, self.body, {
  20313. body: rest
  20314. }).transform(compressor);
  20315. }
  20316. if_break_in_loop(self, compressor);
  20317. }
  20318. var first = self.body instanceof AST_BlockStatement ? self.body.body[0] : self.body;
  20319. if (first instanceof AST_If) {
  20320. if (first.body instanceof AST_Break
  20321. && compressor.loopcontrol_target(first.body) === compressor.self()) {
  20322. if (self.condition) {
  20323. self.condition = make_node(AST_Binary, self.condition, {
  20324. left: self.condition,
  20325. operator: "&&",
  20326. right: first.condition.negate(compressor),
  20327. });
  20328. } else {
  20329. self.condition = first.condition.negate(compressor);
  20330. }
  20331. drop_it(first.alternative);
  20332. }
  20333. else if (first.alternative instanceof AST_Break
  20334. && compressor.loopcontrol_target(first.alternative) === compressor.self()) {
  20335. if (self.condition) {
  20336. self.condition = make_node(AST_Binary, self.condition, {
  20337. left: self.condition,
  20338. operator: "&&",
  20339. right: first.condition,
  20340. });
  20341. } else {
  20342. self.condition = first.condition;
  20343. }
  20344. drop_it(first.body);
  20345. }
  20346. }
  20347. };
  20348. OPT(AST_For, function(self, compressor){
  20349. if (!compressor.option("loops")) return self;
  20350. if (self.condition) {
  20351. var cond = self.condition.evaluate(compressor);
  20352. if (compressor.option("dead_code") && !cond) {
  20353. var a = [];
  20354. if (self.init instanceof AST_Statement) {
  20355. a.push(self.init);
  20356. }
  20357. else if (self.init) {
  20358. a.push(make_node(AST_SimpleStatement, self.init, {
  20359. body: self.init
  20360. }));
  20361. }
  20362. extract_declarations_from_unreachable_code(compressor, self.body, a);
  20363. return make_node(AST_BlockStatement, self, { body: a }).optimize(compressor);
  20364. }
  20365. if (cond !== self.condition) {
  20366. cond = make_node_from_constant(cond, self.condition).transform(compressor);
  20367. self.condition = best_of_expression(cond, self.condition);
  20368. }
  20369. }
  20370. if_break_in_loop(self, compressor);
  20371. return self;
  20372. });
  20373. OPT(AST_If, function(self, compressor){
  20374. if (is_empty(self.alternative)) self.alternative = null;
  20375. if (!compressor.option("conditionals")) return self;
  20376. // if condition can be statically determined, warn and drop
  20377. // one of the blocks. note, statically determined implies
  20378. // “has no side effects”; also it doesn't work for cases like
  20379. // `x && true`, though it probably should.
  20380. var cond = self.condition.evaluate(compressor);
  20381. if (cond !== self.condition) {
  20382. if (cond) {
  20383. compressor.warn("Condition always true [{file}:{line},{col}]", self.condition.start);
  20384. if (compressor.option("dead_code")) {
  20385. var a = [];
  20386. if (self.alternative) {
  20387. extract_declarations_from_unreachable_code(compressor, self.alternative, a);
  20388. }
  20389. a.push(self.body);
  20390. return make_node(AST_BlockStatement, self, { body: a }).optimize(compressor);
  20391. }
  20392. } else {
  20393. compressor.warn("Condition always false [{file}:{line},{col}]", self.condition.start);
  20394. if (compressor.option("dead_code")) {
  20395. var a = [];
  20396. extract_declarations_from_unreachable_code(compressor, self.body, a);
  20397. if (self.alternative) a.push(self.alternative);
  20398. return make_node(AST_BlockStatement, self, { body: a }).optimize(compressor);
  20399. }
  20400. }
  20401. cond = make_node_from_constant(cond, self.condition).transform(compressor);
  20402. self.condition = best_of_expression(cond, self.condition);
  20403. }
  20404. var negated = self.condition.negate(compressor);
  20405. var self_condition_length = self.condition.print_to_string().length;
  20406. var negated_length = negated.print_to_string().length;
  20407. var negated_is_best = negated_length < self_condition_length;
  20408. if (self.alternative && negated_is_best) {
  20409. negated_is_best = false; // because we already do the switch here.
  20410. // no need to swap values of self_condition_length and negated_length
  20411. // here because they are only used in an equality comparison later on.
  20412. self.condition = negated;
  20413. var tmp = self.body;
  20414. self.body = self.alternative || make_node(AST_EmptyStatement, self);
  20415. self.alternative = tmp;
  20416. }
  20417. if (is_empty(self.body) && is_empty(self.alternative)) {
  20418. return make_node(AST_SimpleStatement, self.condition, {
  20419. body: self.condition.clone()
  20420. }).optimize(compressor);
  20421. }
  20422. if (self.body instanceof AST_SimpleStatement
  20423. && self.alternative instanceof AST_SimpleStatement) {
  20424. return make_node(AST_SimpleStatement, self, {
  20425. body: make_node(AST_Conditional, self, {
  20426. condition : self.condition,
  20427. consequent : self.body.body,
  20428. alternative : self.alternative.body
  20429. })
  20430. }).optimize(compressor);
  20431. }
  20432. if (is_empty(self.alternative) && self.body instanceof AST_SimpleStatement) {
  20433. if (self_condition_length === negated_length && !negated_is_best
  20434. && self.condition instanceof AST_Binary && self.condition.operator == "||") {
  20435. // although the code length of self.condition and negated are the same,
  20436. // negated does not require additional surrounding parentheses.
  20437. // see https://github.com/mishoo/UglifyJS2/issues/979
  20438. negated_is_best = true;
  20439. }
  20440. if (negated_is_best) return make_node(AST_SimpleStatement, self, {
  20441. body: make_node(AST_Binary, self, {
  20442. operator : "||",
  20443. left : negated,
  20444. right : self.body.body
  20445. })
  20446. }).optimize(compressor);
  20447. return make_node(AST_SimpleStatement, self, {
  20448. body: make_node(AST_Binary, self, {
  20449. operator : "&&",
  20450. left : self.condition,
  20451. right : self.body.body
  20452. })
  20453. }).optimize(compressor);
  20454. }
  20455. if (self.body instanceof AST_EmptyStatement
  20456. && self.alternative instanceof AST_SimpleStatement) {
  20457. return make_node(AST_SimpleStatement, self, {
  20458. body: make_node(AST_Binary, self, {
  20459. operator : "||",
  20460. left : self.condition,
  20461. right : self.alternative.body
  20462. })
  20463. }).optimize(compressor);
  20464. }
  20465. if (self.body instanceof AST_Exit
  20466. && self.alternative instanceof AST_Exit
  20467. && self.body.TYPE == self.alternative.TYPE) {
  20468. return make_node(self.body.CTOR, self, {
  20469. value: make_node(AST_Conditional, self, {
  20470. condition : self.condition,
  20471. consequent : self.body.value || make_node(AST_Undefined, self.body),
  20472. alternative : self.alternative.value || make_node(AST_Undefined, self.alternative)
  20473. }).transform(compressor)
  20474. }).optimize(compressor);
  20475. }
  20476. if (self.body instanceof AST_If
  20477. && !self.body.alternative
  20478. && !self.alternative) {
  20479. self = make_node(AST_If, self, {
  20480. condition: make_node(AST_Binary, self.condition, {
  20481. operator: "&&",
  20482. left: self.condition,
  20483. right: self.body.condition
  20484. }),
  20485. body: self.body.body,
  20486. alternative: null
  20487. });
  20488. }
  20489. if (aborts(self.body)) {
  20490. if (self.alternative) {
  20491. var alt = self.alternative;
  20492. self.alternative = null;
  20493. return make_node(AST_BlockStatement, self, {
  20494. body: [ self, alt ]
  20495. }).optimize(compressor);
  20496. }
  20497. }
  20498. if (aborts(self.alternative)) {
  20499. var body = self.body;
  20500. self.body = self.alternative;
  20501. self.condition = negated_is_best ? negated : self.condition.negate(compressor);
  20502. self.alternative = null;
  20503. return make_node(AST_BlockStatement, self, {
  20504. body: [ self, body ]
  20505. }).optimize(compressor);
  20506. }
  20507. return self;
  20508. });
  20509. OPT(AST_Switch, function(self, compressor){
  20510. if (!compressor.option("switches")) return self;
  20511. var branch;
  20512. var value = self.expression.evaluate(compressor);
  20513. if (value !== self.expression) {
  20514. var expression = make_node_from_constant(value, self.expression).transform(compressor);
  20515. self.expression = best_of_expression(expression, self.expression);
  20516. }
  20517. if (!compressor.option("dead_code")) return self;
  20518. var decl = [];
  20519. var body = [];
  20520. var default_branch;
  20521. var exact_match;
  20522. for (var i = 0, len = self.body.length; i < len && !exact_match; i++) {
  20523. branch = self.body[i];
  20524. if (branch instanceof AST_Default) {
  20525. if (!default_branch) {
  20526. default_branch = branch;
  20527. } else {
  20528. eliminate_branch(branch, body[body.length - 1]);
  20529. }
  20530. } else if (value !== self.expression) {
  20531. var exp = branch.expression.evaluate(compressor);
  20532. if (exp === value) {
  20533. exact_match = branch;
  20534. if (default_branch) {
  20535. var default_index = body.indexOf(default_branch);
  20536. body.splice(default_index, 1);
  20537. eliminate_branch(default_branch, body[default_index - 1]);
  20538. default_branch = null;
  20539. }
  20540. } else if (exp !== branch.expression) {
  20541. eliminate_branch(branch, body[body.length - 1]);
  20542. continue;
  20543. }
  20544. }
  20545. if (aborts(branch)) {
  20546. var prev = body[body.length - 1];
  20547. if (aborts(prev) && prev.body.length == branch.body.length
  20548. && make_node(AST_BlockStatement, prev, prev).equivalent_to(make_node(AST_BlockStatement, branch, branch))) {
  20549. prev.body = [];
  20550. }
  20551. }
  20552. body.push(branch);
  20553. }
  20554. while (i < len) eliminate_branch(self.body[i++], body[body.length - 1]);
  20555. if (body.length > 0) {
  20556. body[0].body = decl.concat(body[0].body);
  20557. }
  20558. self.body = body;
  20559. while (branch = body[body.length - 1]) {
  20560. var stat = branch.body[branch.body.length - 1];
  20561. if (stat instanceof AST_Break && compressor.loopcontrol_target(stat) === self)
  20562. branch.body.pop();
  20563. if (branch.body.length || branch instanceof AST_Case
  20564. && (default_branch || branch.expression.has_side_effects(compressor))) break;
  20565. if (body.pop() === default_branch) default_branch = null;
  20566. }
  20567. if (body.length == 0) {
  20568. return make_node(AST_BlockStatement, self, {
  20569. body: decl.concat(make_node(AST_SimpleStatement, self.expression, {
  20570. body: self.expression
  20571. }))
  20572. }).optimize(compressor);
  20573. }
  20574. if (body.length == 1 && (body[0] === exact_match || body[0] === default_branch)) {
  20575. var has_break = false;
  20576. var tw = new TreeWalker(function(node) {
  20577. if (has_break
  20578. || node instanceof AST_Lambda
  20579. || node instanceof AST_SimpleStatement) return true;
  20580. if (node instanceof AST_Break && tw.loopcontrol_target(node) === self)
  20581. has_break = true;
  20582. });
  20583. self.walk(tw);
  20584. if (!has_break) {
  20585. body = body[0].body.slice();
  20586. body.unshift(make_node(AST_SimpleStatement, self.expression, {
  20587. body: self.expression
  20588. }));
  20589. return make_node(AST_BlockStatement, self, {
  20590. body: body
  20591. }).optimize(compressor);
  20592. }
  20593. }
  20594. return self;
  20595. function eliminate_branch(branch, prev) {
  20596. if (prev && !aborts(prev)) {
  20597. prev.body = prev.body.concat(branch.body);
  20598. } else {
  20599. extract_declarations_from_unreachable_code(compressor, branch, decl);
  20600. }
  20601. }
  20602. });
  20603. OPT(AST_Try, function(self, compressor){
  20604. self.body = tighten_body(self.body, compressor);
  20605. if (self.bcatch && self.bfinally && all(self.bfinally.body, is_empty)) self.bfinally = null;
  20606. if (all(self.body, is_empty)) {
  20607. var body = [];
  20608. if (self.bcatch) extract_declarations_from_unreachable_code(compressor, self.bcatch, body);
  20609. if (self.bfinally) body = body.concat(self.bfinally.body);
  20610. return make_node(AST_BlockStatement, self, {
  20611. body: body
  20612. }).optimize(compressor);
  20613. }
  20614. return self;
  20615. });
  20616. AST_Definitions.DEFMETHOD("remove_initializers", function(){
  20617. this.definitions.forEach(function(def){ def.value = null });
  20618. });
  20619. AST_Definitions.DEFMETHOD("to_assignments", function(compressor){
  20620. var reduce_vars = compressor.option("reduce_vars");
  20621. var assignments = this.definitions.reduce(function(a, def){
  20622. if (def.value) {
  20623. var name = make_node(AST_SymbolRef, def.name, def.name);
  20624. a.push(make_node(AST_Assign, def, {
  20625. operator : "=",
  20626. left : name,
  20627. right : def.value
  20628. }));
  20629. if (reduce_vars) name.definition().fixed = false;
  20630. }
  20631. return a;
  20632. }, []);
  20633. if (assignments.length == 0) return null;
  20634. return AST_Seq.from_array(assignments);
  20635. });
  20636. OPT(AST_Definitions, function(self, compressor){
  20637. if (self.definitions.length == 0)
  20638. return make_node(AST_EmptyStatement, self);
  20639. return self;
  20640. });
  20641. OPT(AST_Call, function(self, compressor){
  20642. var exp = self.expression;
  20643. if (compressor.option("reduce_vars")
  20644. && exp instanceof AST_SymbolRef) {
  20645. var def = exp.definition();
  20646. var fixed = exp.fixed_value();
  20647. if (fixed instanceof AST_Defun) {
  20648. def.fixed = fixed = make_node(AST_Function, fixed, fixed).clone(true);
  20649. }
  20650. if (fixed instanceof AST_Function) {
  20651. exp = fixed;
  20652. if (compressor.option("unused")
  20653. && def.references.length == 1
  20654. && !(def.scope.uses_arguments
  20655. && def.orig[0] instanceof AST_SymbolFunarg)
  20656. && !def.scope.uses_eval
  20657. && compressor.find_parent(AST_Scope) === def.scope) {
  20658. self.expression = exp;
  20659. }
  20660. }
  20661. }
  20662. if (compressor.option("unused")
  20663. && exp instanceof AST_Function
  20664. && !exp.uses_arguments
  20665. && !exp.uses_eval) {
  20666. var pos = 0, last = 0;
  20667. for (var i = 0, len = self.args.length; i < len; i++) {
  20668. var trim = i >= exp.argnames.length;
  20669. if (trim || exp.argnames[i].__unused) {
  20670. var node = self.args[i].drop_side_effect_free(compressor);
  20671. if (node) {
  20672. self.args[pos++] = node;
  20673. } else if (!trim) {
  20674. self.args[pos++] = make_node(AST_Number, self.args[i], {
  20675. value: 0
  20676. });
  20677. continue;
  20678. }
  20679. } else {
  20680. self.args[pos++] = self.args[i];
  20681. }
  20682. last = pos;
  20683. }
  20684. self.args.length = last;
  20685. }
  20686. if (compressor.option("unsafe")) {
  20687. if (exp instanceof AST_SymbolRef && exp.undeclared()) {
  20688. switch (exp.name) {
  20689. case "Array":
  20690. if (self.args.length != 1) {
  20691. return make_node(AST_Array, self, {
  20692. elements: self.args
  20693. }).optimize(compressor);
  20694. }
  20695. break;
  20696. case "Object":
  20697. if (self.args.length == 0) {
  20698. return make_node(AST_Object, self, {
  20699. properties: []
  20700. });
  20701. }
  20702. break;
  20703. case "String":
  20704. if (self.args.length == 0) return make_node(AST_String, self, {
  20705. value: ""
  20706. });
  20707. if (self.args.length <= 1) return make_node(AST_Binary, self, {
  20708. left: self.args[0],
  20709. operator: "+",
  20710. right: make_node(AST_String, self, { value: "" })
  20711. }).optimize(compressor);
  20712. break;
  20713. case "Number":
  20714. if (self.args.length == 0) return make_node(AST_Number, self, {
  20715. value: 0
  20716. });
  20717. if (self.args.length == 1) return make_node(AST_UnaryPrefix, self, {
  20718. expression: self.args[0],
  20719. operator: "+"
  20720. }).optimize(compressor);
  20721. case "Boolean":
  20722. if (self.args.length == 0) return make_node(AST_False, self);
  20723. if (self.args.length == 1) return make_node(AST_UnaryPrefix, self, {
  20724. expression: make_node(AST_UnaryPrefix, self, {
  20725. expression: self.args[0],
  20726. operator: "!"
  20727. }),
  20728. operator: "!"
  20729. }).optimize(compressor);
  20730. break;
  20731. case "Function":
  20732. // new Function() => function(){}
  20733. if (self.args.length == 0) return make_node(AST_Function, self, {
  20734. argnames: [],
  20735. body: []
  20736. });
  20737. if (all(self.args, function(x){ return x instanceof AST_String })) {
  20738. // quite a corner-case, but we can handle it:
  20739. // https://github.com/mishoo/UglifyJS2/issues/203
  20740. // if the code argument is a constant, then we can minify it.
  20741. try {
  20742. var code = "(function(" + self.args.slice(0, -1).map(function(arg){
  20743. return arg.value;
  20744. }).join(",") + "){" + self.args[self.args.length - 1].value + "})()";
  20745. var ast = parse(code);
  20746. ast.figure_out_scope({ screw_ie8: compressor.option("screw_ie8") });
  20747. var comp = new Compressor(compressor.options);
  20748. ast = ast.transform(comp);
  20749. ast.figure_out_scope({ screw_ie8: compressor.option("screw_ie8") });
  20750. ast.mangle_names();
  20751. var fun;
  20752. try {
  20753. ast.walk(new TreeWalker(function(node){
  20754. if (node instanceof AST_Lambda) {
  20755. fun = node;
  20756. throw ast;
  20757. }
  20758. }));
  20759. } catch(ex) {
  20760. if (ex !== ast) throw ex;
  20761. };
  20762. if (!fun) return self;
  20763. var args = fun.argnames.map(function(arg, i){
  20764. return make_node(AST_String, self.args[i], {
  20765. value: arg.print_to_string()
  20766. });
  20767. });
  20768. var code = OutputStream();
  20769. AST_BlockStatement.prototype._codegen.call(fun, fun, code);
  20770. code = code.toString().replace(/^\{|\}$/g, "");
  20771. args.push(make_node(AST_String, self.args[self.args.length - 1], {
  20772. value: code
  20773. }));
  20774. self.args = args;
  20775. return self;
  20776. } catch(ex) {
  20777. if (ex instanceof JS_Parse_Error) {
  20778. compressor.warn("Error parsing code passed to new Function [{file}:{line},{col}]", self.args[self.args.length - 1].start);
  20779. compressor.warn(ex.toString());
  20780. } else {
  20781. console.log(ex);
  20782. throw ex;
  20783. }
  20784. }
  20785. }
  20786. break;
  20787. }
  20788. }
  20789. else if (exp instanceof AST_Dot && exp.property == "toString" && self.args.length == 0) {
  20790. return make_node(AST_Binary, self, {
  20791. left: make_node(AST_String, self, { value: "" }),
  20792. operator: "+",
  20793. right: exp.expression
  20794. }).optimize(compressor);
  20795. }
  20796. else if (exp instanceof AST_Dot && exp.expression instanceof AST_Array && exp.property == "join") EXIT: {
  20797. var separator;
  20798. if (self.args.length > 0) {
  20799. separator = self.args[0].evaluate(compressor);
  20800. if (separator === self.args[0]) break EXIT; // not a constant
  20801. }
  20802. var elements = [];
  20803. var consts = [];
  20804. exp.expression.elements.forEach(function(el) {
  20805. var value = el.evaluate(compressor);
  20806. if (value !== el) {
  20807. consts.push(value);
  20808. } else {
  20809. if (consts.length > 0) {
  20810. elements.push(make_node(AST_String, self, {
  20811. value: consts.join(separator)
  20812. }));
  20813. consts.length = 0;
  20814. }
  20815. elements.push(el);
  20816. }
  20817. });
  20818. if (consts.length > 0) {
  20819. elements.push(make_node(AST_String, self, {
  20820. value: consts.join(separator)
  20821. }));
  20822. }
  20823. if (elements.length == 0) return make_node(AST_String, self, { value: "" });
  20824. if (elements.length == 1) {
  20825. if (elements[0].is_string(compressor)) {
  20826. return elements[0];
  20827. }
  20828. return make_node(AST_Binary, elements[0], {
  20829. operator : "+",
  20830. left : make_node(AST_String, self, { value: "" }),
  20831. right : elements[0]
  20832. });
  20833. }
  20834. if (separator == "") {
  20835. var first;
  20836. if (elements[0].is_string(compressor)
  20837. || elements[1].is_string(compressor)) {
  20838. first = elements.shift();
  20839. } else {
  20840. first = make_node(AST_String, self, { value: "" });
  20841. }
  20842. return elements.reduce(function(prev, el){
  20843. return make_node(AST_Binary, el, {
  20844. operator : "+",
  20845. left : prev,
  20846. right : el
  20847. });
  20848. }, first).optimize(compressor);
  20849. }
  20850. // need this awkward cloning to not affect original element
  20851. // best_of will decide which one to get through.
  20852. var node = self.clone();
  20853. node.expression = node.expression.clone();
  20854. node.expression.expression = node.expression.expression.clone();
  20855. node.expression.expression.elements = elements;
  20856. return best_of(compressor, self, node);
  20857. }
  20858. else if (exp instanceof AST_Dot && exp.expression.is_string(compressor) && exp.property == "charAt") {
  20859. var arg = self.args[0];
  20860. var index = arg ? arg.evaluate(compressor) : 0;
  20861. if (index !== arg) {
  20862. return make_node(AST_Sub, exp, {
  20863. expression: exp.expression,
  20864. property: make_node_from_constant(index | 0, arg || exp)
  20865. }).optimize(compressor);
  20866. }
  20867. }
  20868. }
  20869. if (exp instanceof AST_Function) {
  20870. if (exp.body[0] instanceof AST_Return) {
  20871. var value = exp.body[0].value;
  20872. if (!value || value.is_constant()) {
  20873. var args = self.args.concat(value || make_node(AST_Undefined, self));
  20874. return AST_Seq.from_array(args).transform(compressor);
  20875. }
  20876. }
  20877. if (compressor.option("side_effects") && all(exp.body, is_empty)) {
  20878. var args = self.args.concat(make_node(AST_Undefined, self));
  20879. return AST_Seq.from_array(args).transform(compressor);
  20880. }
  20881. }
  20882. if (compressor.option("drop_console")) {
  20883. if (exp instanceof AST_PropAccess) {
  20884. var name = exp.expression;
  20885. while (name.expression) {
  20886. name = name.expression;
  20887. }
  20888. if (name instanceof AST_SymbolRef
  20889. && name.name == "console"
  20890. && name.undeclared()) {
  20891. return make_node(AST_Undefined, self).optimize(compressor);
  20892. }
  20893. }
  20894. }
  20895. if (compressor.option("negate_iife")
  20896. && compressor.parent() instanceof AST_SimpleStatement
  20897. && is_iife_call(self)) {
  20898. return self.negate(compressor, true);
  20899. }
  20900. return self;
  20901. });
  20902. OPT(AST_New, function(self, compressor){
  20903. if (compressor.option("unsafe")) {
  20904. var exp = self.expression;
  20905. if (exp instanceof AST_SymbolRef && exp.undeclared()) {
  20906. switch (exp.name) {
  20907. case "Object":
  20908. case "RegExp":
  20909. case "Function":
  20910. case "Error":
  20911. case "Array":
  20912. return make_node(AST_Call, self, self).transform(compressor);
  20913. }
  20914. }
  20915. }
  20916. return self;
  20917. });
  20918. OPT(AST_Seq, function(self, compressor){
  20919. if (!compressor.option("side_effects"))
  20920. return self;
  20921. self.car = self.car.drop_side_effect_free(compressor, first_in_statement(compressor));
  20922. if (!self.car) return maintain_this_binding(compressor.parent(), self, self.cdr);
  20923. if (compressor.option("cascade")) {
  20924. var left;
  20925. if (self.car instanceof AST_Assign
  20926. && !self.car.left.has_side_effects(compressor)) {
  20927. left = self.car.left;
  20928. } else if (self.car instanceof AST_Unary
  20929. && (self.car.operator == "++" || self.car.operator == "--")) {
  20930. left = self.car.expression;
  20931. }
  20932. if (left
  20933. && !(left instanceof AST_SymbolRef
  20934. && (left.definition().orig[0] instanceof AST_SymbolLambda
  20935. || is_reference_const(left)))) {
  20936. var parent, field;
  20937. var cdr = self.cdr;
  20938. while (true) {
  20939. if (cdr.equivalent_to(left)) {
  20940. var car = self.car instanceof AST_UnaryPostfix ? make_node(AST_UnaryPrefix, self.car, {
  20941. operator: self.car.operator,
  20942. expression: left
  20943. }) : self.car;
  20944. if (parent) {
  20945. parent[field] = car;
  20946. return self.cdr;
  20947. }
  20948. return car;
  20949. }
  20950. if (cdr instanceof AST_Binary && !(cdr instanceof AST_Assign)) {
  20951. if (cdr.left.is_constant()) {
  20952. if (cdr.operator == "||" || cdr.operator == "&&") break;
  20953. field = "right";
  20954. } else {
  20955. field = "left";
  20956. }
  20957. } else if (cdr instanceof AST_Call
  20958. || cdr instanceof AST_Unary && !unary_side_effects(cdr.operator)) {
  20959. field = "expression";
  20960. } else break;
  20961. parent = cdr;
  20962. cdr = cdr[field];
  20963. }
  20964. }
  20965. }
  20966. if (is_undefined(self.cdr, compressor)) {
  20967. return make_node(AST_UnaryPrefix, self, {
  20968. operator : "void",
  20969. expression : self.car
  20970. });
  20971. }
  20972. return self;
  20973. });
  20974. AST_Unary.DEFMETHOD("lift_sequences", function(compressor){
  20975. if (compressor.option("sequences")) {
  20976. if (this.expression instanceof AST_Seq) {
  20977. var seq = this.expression;
  20978. var x = seq.to_array();
  20979. var e = this.clone();
  20980. e.expression = x.pop();
  20981. x.push(e);
  20982. seq = AST_Seq.from_array(x).transform(compressor);
  20983. return seq;
  20984. }
  20985. }
  20986. return this;
  20987. });
  20988. OPT(AST_UnaryPostfix, function(self, compressor){
  20989. return self.lift_sequences(compressor);
  20990. });
  20991. OPT(AST_UnaryPrefix, function(self, compressor){
  20992. var e = self.expression;
  20993. if (self.operator == "delete"
  20994. && !(e instanceof AST_SymbolRef
  20995. || e instanceof AST_PropAccess
  20996. || e instanceof AST_NaN
  20997. || e instanceof AST_Infinity
  20998. || e instanceof AST_Undefined)) {
  20999. if (e instanceof AST_Seq) {
  21000. e = e.to_array();
  21001. e.push(make_node(AST_True, self));
  21002. return AST_Seq.from_array(e).optimize(compressor);
  21003. }
  21004. return make_node(AST_Seq, self, {
  21005. car: e,
  21006. cdr: make_node(AST_True, self)
  21007. }).optimize(compressor);
  21008. }
  21009. var seq = self.lift_sequences(compressor);
  21010. if (seq !== self) {
  21011. return seq;
  21012. }
  21013. if (compressor.option("side_effects") && self.operator == "void") {
  21014. e = e.drop_side_effect_free(compressor);
  21015. if (e) {
  21016. self.expression = e;
  21017. return self;
  21018. } else {
  21019. return make_node(AST_Undefined, self).optimize(compressor);
  21020. }
  21021. }
  21022. if (compressor.option("booleans") && compressor.in_boolean_context()) {
  21023. switch (self.operator) {
  21024. case "!":
  21025. if (e instanceof AST_UnaryPrefix && e.operator == "!") {
  21026. // !!foo ==> foo, if we're in boolean context
  21027. return e.expression;
  21028. }
  21029. if (e instanceof AST_Binary) {
  21030. self = best_of(compressor, self, e.negate(compressor, first_in_statement(compressor)));
  21031. }
  21032. break;
  21033. case "typeof":
  21034. // typeof always returns a non-empty string, thus it's
  21035. // always true in booleans
  21036. compressor.warn("Boolean expression always true [{file}:{line},{col}]", self.start);
  21037. return (e instanceof AST_SymbolRef ? make_node(AST_True, self) : make_node(AST_Seq, self, {
  21038. car: e,
  21039. cdr: make_node(AST_True, self)
  21040. })).optimize(compressor);
  21041. }
  21042. }
  21043. if (self.operator == "-" && e instanceof AST_Infinity) {
  21044. e = e.transform(compressor);
  21045. }
  21046. if (e instanceof AST_Binary
  21047. && (self.operator == "+" || self.operator == "-")
  21048. && (e.operator == "*" || e.operator == "/" || e.operator == "%")) {
  21049. return make_node(AST_Binary, self, {
  21050. operator: e.operator,
  21051. left: make_node(AST_UnaryPrefix, e.left, {
  21052. operator: self.operator,
  21053. expression: e.left
  21054. }),
  21055. right: e.right
  21056. });
  21057. }
  21058. // avoids infinite recursion of numerals
  21059. if (self.operator != "-"
  21060. || !(e instanceof AST_Number || e instanceof AST_Infinity)) {
  21061. var ev = self.evaluate(compressor);
  21062. if (ev !== self) {
  21063. ev = make_node_from_constant(ev, self).optimize(compressor);
  21064. return best_of(compressor, ev, self);
  21065. }
  21066. }
  21067. return self;
  21068. });
  21069. AST_Binary.DEFMETHOD("lift_sequences", function(compressor){
  21070. if (compressor.option("sequences")) {
  21071. if (this.left instanceof AST_Seq) {
  21072. var seq = this.left;
  21073. var x = seq.to_array();
  21074. var e = this.clone();
  21075. e.left = x.pop();
  21076. x.push(e);
  21077. return AST_Seq.from_array(x).optimize(compressor);
  21078. }
  21079. if (this.right instanceof AST_Seq && !this.left.has_side_effects(compressor)) {
  21080. var assign = this.operator == "=" && this.left instanceof AST_SymbolRef;
  21081. var root = this.right.clone();
  21082. var cursor, seq = root;
  21083. while (assign || !seq.car.has_side_effects(compressor)) {
  21084. cursor = seq;
  21085. if (seq.cdr instanceof AST_Seq) {
  21086. seq = seq.cdr = seq.cdr.clone();
  21087. } else break;
  21088. }
  21089. if (cursor) {
  21090. var e = this.clone();
  21091. e.right = cursor.cdr;
  21092. cursor.cdr = e;
  21093. return root.optimize(compressor);
  21094. }
  21095. }
  21096. }
  21097. return this;
  21098. });
  21099. var commutativeOperators = makePredicate("== === != !== * & | ^");
  21100. OPT(AST_Binary, function(self, compressor){
  21101. function reversible() {
  21102. return self.left.is_constant()
  21103. || self.right.is_constant()
  21104. || !self.left.has_side_effects(compressor)
  21105. && !self.right.has_side_effects(compressor);
  21106. }
  21107. function reverse(op) {
  21108. if (reversible()) {
  21109. if (op) self.operator = op;
  21110. var tmp = self.left;
  21111. self.left = self.right;
  21112. self.right = tmp;
  21113. }
  21114. }
  21115. if (commutativeOperators(self.operator)) {
  21116. if (self.right.is_constant()
  21117. && !self.left.is_constant()) {
  21118. // if right is a constant, whatever side effects the
  21119. // left side might have could not influence the
  21120. // result. hence, force switch.
  21121. if (!(self.left instanceof AST_Binary
  21122. && PRECEDENCE[self.left.operator] >= PRECEDENCE[self.operator])) {
  21123. reverse();
  21124. }
  21125. }
  21126. }
  21127. self = self.lift_sequences(compressor);
  21128. if (compressor.option("comparisons")) switch (self.operator) {
  21129. case "===":
  21130. case "!==":
  21131. if ((self.left.is_string(compressor) && self.right.is_string(compressor)) ||
  21132. (self.left.is_number(compressor) && self.right.is_number(compressor)) ||
  21133. (self.left.is_boolean() && self.right.is_boolean())) {
  21134. self.operator = self.operator.substr(0, 2);
  21135. }
  21136. // XXX: intentionally falling down to the next case
  21137. case "==":
  21138. case "!=":
  21139. // "undefined" == typeof x => undefined === x
  21140. if (self.left instanceof AST_String
  21141. && self.left.value == "undefined"
  21142. && self.right instanceof AST_UnaryPrefix
  21143. && self.right.operator == "typeof") {
  21144. var expr = self.right.expression;
  21145. if (expr instanceof AST_SymbolRef ? !expr.undeclared()
  21146. : !(expr instanceof AST_PropAccess) || compressor.option("screw_ie8")) {
  21147. self.right = expr;
  21148. self.left = make_node(AST_Undefined, self.left).optimize(compressor);
  21149. if (self.operator.length == 2) self.operator += "=";
  21150. }
  21151. }
  21152. break;
  21153. }
  21154. if (compressor.option("booleans") && self.operator == "+" && compressor.in_boolean_context()) {
  21155. var ll = self.left.evaluate(compressor);
  21156. var rr = self.right.evaluate(compressor);
  21157. if (ll && typeof ll == "string") {
  21158. compressor.warn("+ in boolean context always true [{file}:{line},{col}]", self.start);
  21159. return make_node(AST_Seq, self, {
  21160. car: self.right,
  21161. cdr: make_node(AST_True, self)
  21162. }).optimize(compressor);
  21163. }
  21164. if (rr && typeof rr == "string") {
  21165. compressor.warn("+ in boolean context always true [{file}:{line},{col}]", self.start);
  21166. return make_node(AST_Seq, self, {
  21167. car: self.left,
  21168. cdr: make_node(AST_True, self)
  21169. }).optimize(compressor);
  21170. }
  21171. }
  21172. if (compressor.option("comparisons") && self.is_boolean()) {
  21173. if (!(compressor.parent() instanceof AST_Binary)
  21174. || compressor.parent() instanceof AST_Assign) {
  21175. var negated = make_node(AST_UnaryPrefix, self, {
  21176. operator: "!",
  21177. expression: self.negate(compressor, first_in_statement(compressor))
  21178. });
  21179. self = best_of(compressor, self, negated);
  21180. }
  21181. if (compressor.option("unsafe_comps")) {
  21182. switch (self.operator) {
  21183. case "<": reverse(">"); break;
  21184. case "<=": reverse(">="); break;
  21185. }
  21186. }
  21187. }
  21188. if (self.operator == "+") {
  21189. if (self.right instanceof AST_String
  21190. && self.right.getValue() == ""
  21191. && self.left.is_string(compressor)) {
  21192. return self.left;
  21193. }
  21194. if (self.left instanceof AST_String
  21195. && self.left.getValue() == ""
  21196. && self.right.is_string(compressor)) {
  21197. return self.right;
  21198. }
  21199. if (self.left instanceof AST_Binary
  21200. && self.left.operator == "+"
  21201. && self.left.left instanceof AST_String
  21202. && self.left.left.getValue() == ""
  21203. && self.right.is_string(compressor)) {
  21204. self.left = self.left.right;
  21205. return self.transform(compressor);
  21206. }
  21207. }
  21208. if (compressor.option("evaluate")) {
  21209. switch (self.operator) {
  21210. case "&&":
  21211. var ll = self.left.evaluate(compressor);
  21212. if (!ll) {
  21213. compressor.warn("Condition left of && always false [{file}:{line},{col}]", self.start);
  21214. return maintain_this_binding(compressor.parent(), self, self.left).optimize(compressor);
  21215. } else if (ll !== self.left) {
  21216. compressor.warn("Condition left of && always true [{file}:{line},{col}]", self.start);
  21217. return maintain_this_binding(compressor.parent(), self, self.right).optimize(compressor);
  21218. }
  21219. if (compressor.option("booleans") && compressor.in_boolean_context()) {
  21220. var rr = self.right.evaluate(compressor);
  21221. if (!rr) {
  21222. compressor.warn("Boolean && always false [{file}:{line},{col}]", self.start);
  21223. return make_node(AST_Seq, self, {
  21224. car: self.left,
  21225. cdr: make_node(AST_False, self)
  21226. }).optimize(compressor);
  21227. } else if (rr !== self.right) {
  21228. compressor.warn("Dropping side-effect-free && in boolean context [{file}:{line},{col}]", self.start);
  21229. return self.left.optimize(compressor);
  21230. }
  21231. }
  21232. break;
  21233. case "||":
  21234. var ll = self.left.evaluate(compressor);
  21235. if (!ll) {
  21236. compressor.warn("Condition left of || always false [{file}:{line},{col}]", self.start);
  21237. return maintain_this_binding(compressor.parent(), self, self.right).optimize(compressor);
  21238. } else if (ll !== self.left) {
  21239. compressor.warn("Condition left of || always true [{file}:{line},{col}]", self.start);
  21240. return maintain_this_binding(compressor.parent(), self, self.left).optimize(compressor);
  21241. }
  21242. if (compressor.option("booleans") && compressor.in_boolean_context()) {
  21243. var rr = self.right.evaluate(compressor);
  21244. if (!rr) {
  21245. compressor.warn("Dropping side-effect-free || in boolean context [{file}:{line},{col}]", self.start);
  21246. return self.left.optimize(compressor);
  21247. } else if (rr !== self.right) {
  21248. compressor.warn("Boolean || always true [{file}:{line},{col}]", self.start);
  21249. return make_node(AST_Seq, self, {
  21250. car: self.left,
  21251. cdr: make_node(AST_True, self)
  21252. }).optimize(compressor);
  21253. }
  21254. }
  21255. break;
  21256. }
  21257. var associative = true;
  21258. switch (self.operator) {
  21259. case "+":
  21260. // "foo" + ("bar" + x) => "foobar" + x
  21261. if (self.left instanceof AST_Constant
  21262. && self.right instanceof AST_Binary
  21263. && self.right.operator == "+"
  21264. && self.right.left instanceof AST_Constant
  21265. && self.right.is_string(compressor)) {
  21266. self = make_node(AST_Binary, self, {
  21267. operator: "+",
  21268. left: make_node(AST_String, self.left, {
  21269. value: "" + self.left.getValue() + self.right.left.getValue(),
  21270. start: self.left.start,
  21271. end: self.right.left.end
  21272. }),
  21273. right: self.right.right
  21274. });
  21275. }
  21276. // (x + "foo") + "bar" => x + "foobar"
  21277. if (self.right instanceof AST_Constant
  21278. && self.left instanceof AST_Binary
  21279. && self.left.operator == "+"
  21280. && self.left.right instanceof AST_Constant
  21281. && self.left.is_string(compressor)) {
  21282. self = make_node(AST_Binary, self, {
  21283. operator: "+",
  21284. left: self.left.left,
  21285. right: make_node(AST_String, self.right, {
  21286. value: "" + self.left.right.getValue() + self.right.getValue(),
  21287. start: self.left.right.start,
  21288. end: self.right.end
  21289. })
  21290. });
  21291. }
  21292. // (x + "foo") + ("bar" + y) => (x + "foobar") + y
  21293. if (self.left instanceof AST_Binary
  21294. && self.left.operator == "+"
  21295. && self.left.is_string(compressor)
  21296. && self.left.right instanceof AST_Constant
  21297. && self.right instanceof AST_Binary
  21298. && self.right.operator == "+"
  21299. && self.right.left instanceof AST_Constant
  21300. && self.right.is_string(compressor)) {
  21301. self = make_node(AST_Binary, self, {
  21302. operator: "+",
  21303. left: make_node(AST_Binary, self.left, {
  21304. operator: "+",
  21305. left: self.left.left,
  21306. right: make_node(AST_String, self.left.right, {
  21307. value: "" + self.left.right.getValue() + self.right.left.getValue(),
  21308. start: self.left.right.start,
  21309. end: self.right.left.end
  21310. })
  21311. }),
  21312. right: self.right.right
  21313. });
  21314. }
  21315. // a + -b => a - b
  21316. if (self.right instanceof AST_UnaryPrefix
  21317. && self.right.operator == "-"
  21318. && self.left.is_number(compressor)) {
  21319. self = make_node(AST_Binary, self, {
  21320. operator: "-",
  21321. left: self.left,
  21322. right: self.right.expression
  21323. });
  21324. break;
  21325. }
  21326. // -a + b => b - a
  21327. if (self.left instanceof AST_UnaryPrefix
  21328. && self.left.operator == "-"
  21329. && reversible()
  21330. && self.right.is_number(compressor)) {
  21331. self = make_node(AST_Binary, self, {
  21332. operator: "-",
  21333. left: self.right,
  21334. right: self.left.expression
  21335. });
  21336. break;
  21337. }
  21338. case "*":
  21339. associative = compressor.option("unsafe_math");
  21340. case "&":
  21341. case "|":
  21342. case "^":
  21343. // a + +b => +b + a
  21344. if (self.left.is_number(compressor)
  21345. && self.right.is_number(compressor)
  21346. && reversible()
  21347. && !(self.left instanceof AST_Binary
  21348. && self.left.operator != self.operator
  21349. && PRECEDENCE[self.left.operator] >= PRECEDENCE[self.operator])) {
  21350. var reversed = make_node(AST_Binary, self, {
  21351. operator: self.operator,
  21352. left: self.right,
  21353. right: self.left
  21354. });
  21355. if (self.right instanceof AST_Constant
  21356. && !(self.left instanceof AST_Constant)) {
  21357. self = best_of(compressor, reversed, self);
  21358. } else {
  21359. self = best_of(compressor, self, reversed);
  21360. }
  21361. }
  21362. if (associative && self.is_number(compressor)) {
  21363. // a + (b + c) => (a + b) + c
  21364. if (self.right instanceof AST_Binary
  21365. && self.right.operator == self.operator) {
  21366. self = make_node(AST_Binary, self, {
  21367. operator: self.operator,
  21368. left: make_node(AST_Binary, self.left, {
  21369. operator: self.operator,
  21370. left: self.left,
  21371. right: self.right.left,
  21372. start: self.left.start,
  21373. end: self.right.left.end
  21374. }),
  21375. right: self.right.right
  21376. });
  21377. }
  21378. // (n + 2) + 3 => 5 + n
  21379. // (2 * n) * 3 => 6 + n
  21380. if (self.right instanceof AST_Constant
  21381. && self.left instanceof AST_Binary
  21382. && self.left.operator == self.operator) {
  21383. if (self.left.left instanceof AST_Constant) {
  21384. self = make_node(AST_Binary, self, {
  21385. operator: self.operator,
  21386. left: make_node(AST_Binary, self.left, {
  21387. operator: self.operator,
  21388. left: self.left.left,
  21389. right: self.right,
  21390. start: self.left.left.start,
  21391. end: self.right.end
  21392. }),
  21393. right: self.left.right
  21394. });
  21395. } else if (self.left.right instanceof AST_Constant) {
  21396. self = make_node(AST_Binary, self, {
  21397. operator: self.operator,
  21398. left: make_node(AST_Binary, self.left, {
  21399. operator: self.operator,
  21400. left: self.left.right,
  21401. right: self.right,
  21402. start: self.left.right.start,
  21403. end: self.right.end
  21404. }),
  21405. right: self.left.left
  21406. });
  21407. }
  21408. }
  21409. // (a | 1) | (2 | d) => (3 | a) | b
  21410. if (self.left instanceof AST_Binary
  21411. && self.left.operator == self.operator
  21412. && self.left.right instanceof AST_Constant
  21413. && self.right instanceof AST_Binary
  21414. && self.right.operator == self.operator
  21415. && self.right.left instanceof AST_Constant) {
  21416. self = make_node(AST_Binary, self, {
  21417. operator: self.operator,
  21418. left: make_node(AST_Binary, self.left, {
  21419. operator: self.operator,
  21420. left: make_node(AST_Binary, self.left.left, {
  21421. operator: self.operator,
  21422. left: self.left.right,
  21423. right: self.right.left,
  21424. start: self.left.right.start,
  21425. end: self.right.left.end
  21426. }),
  21427. right: self.left.left
  21428. }),
  21429. right: self.right.right
  21430. });
  21431. }
  21432. }
  21433. }
  21434. }
  21435. // x && (y && z) ==> x && y && z
  21436. // x || (y || z) ==> x || y || z
  21437. // x + ("y" + z) ==> x + "y" + z
  21438. // "x" + (y + "z")==> "x" + y + "z"
  21439. if (self.right instanceof AST_Binary
  21440. && self.right.operator == self.operator
  21441. && (self.operator == "&&"
  21442. || self.operator == "||"
  21443. || (self.operator == "+"
  21444. && (self.right.left.is_string(compressor)
  21445. || (self.left.is_string(compressor)
  21446. && self.right.right.is_string(compressor))))))
  21447. {
  21448. self.left = make_node(AST_Binary, self.left, {
  21449. operator : self.operator,
  21450. left : self.left,
  21451. right : self.right.left
  21452. });
  21453. self.right = self.right.right;
  21454. return self.transform(compressor);
  21455. }
  21456. var ev = self.evaluate(compressor);
  21457. if (ev !== self) {
  21458. ev = make_node_from_constant(ev, self).optimize(compressor);
  21459. return best_of(compressor, ev, self);
  21460. }
  21461. return self;
  21462. });
  21463. OPT(AST_SymbolRef, function(self, compressor){
  21464. var def = self.resolve_defines(compressor);
  21465. if (def) {
  21466. return def.optimize(compressor);
  21467. }
  21468. // testing against !self.scope.uses_with first is an optimization
  21469. if (compressor.option("screw_ie8")
  21470. && self.undeclared()
  21471. && (!self.scope.uses_with || !compressor.find_parent(AST_With))) {
  21472. switch (self.name) {
  21473. case "undefined":
  21474. return make_node(AST_Undefined, self).optimize(compressor);
  21475. case "NaN":
  21476. return make_node(AST_NaN, self).optimize(compressor);
  21477. case "Infinity":
  21478. return make_node(AST_Infinity, self).optimize(compressor);
  21479. }
  21480. }
  21481. if (compressor.option("evaluate")
  21482. && compressor.option("reduce_vars")
  21483. && is_lhs(self, compressor.parent()) !== self) {
  21484. var d = self.definition();
  21485. var fixed = self.fixed_value();
  21486. if (fixed) {
  21487. if (d.should_replace === undefined) {
  21488. var init = fixed.evaluate(compressor);
  21489. if (init !== fixed && (compressor.option("unsafe_regexp") || !(init instanceof RegExp))) {
  21490. init = make_node_from_constant(init, fixed);
  21491. var value = init.optimize(compressor).print_to_string().length;
  21492. var fn;
  21493. if (has_symbol_ref(fixed)) {
  21494. fn = function() {
  21495. var result = init.optimize(compressor);
  21496. return result === init ? result.clone(true) : result;
  21497. };
  21498. } else {
  21499. value = Math.min(value, fixed.print_to_string().length);
  21500. fn = function() {
  21501. var result = best_of_expression(init.optimize(compressor), fixed);
  21502. return result === init || result === fixed ? result.clone(true) : result;
  21503. };
  21504. }
  21505. var name = d.name.length;
  21506. var overhead = 0;
  21507. if (compressor.option("unused") && (!d.global || compressor.option("toplevel"))) {
  21508. overhead = (name + 2 + value) / d.references.length;
  21509. }
  21510. d.should_replace = value <= name + overhead ? fn : false;
  21511. } else {
  21512. d.should_replace = false;
  21513. }
  21514. }
  21515. if (d.should_replace) {
  21516. return d.should_replace();
  21517. }
  21518. }
  21519. }
  21520. return self;
  21521. function has_symbol_ref(value) {
  21522. var found;
  21523. value.walk(new TreeWalker(function(node) {
  21524. if (node instanceof AST_SymbolRef) found = true;
  21525. if (found) return true;
  21526. }));
  21527. return found;
  21528. }
  21529. });
  21530. function is_atomic(lhs, self) {
  21531. return lhs instanceof AST_SymbolRef || lhs.TYPE === self.TYPE;
  21532. }
  21533. OPT(AST_Undefined, function(self, compressor){
  21534. if (compressor.option("unsafe")) {
  21535. var undef = find_variable(compressor, "undefined");
  21536. if (undef) {
  21537. var ref = make_node(AST_SymbolRef, self, {
  21538. name : "undefined",
  21539. scope : undef.scope,
  21540. thedef : undef
  21541. });
  21542. ref.is_undefined = true;
  21543. return ref;
  21544. }
  21545. }
  21546. var lhs = is_lhs(compressor.self(), compressor.parent());
  21547. if (lhs && is_atomic(lhs, self)) return self;
  21548. return make_node(AST_UnaryPrefix, self, {
  21549. operator: "void",
  21550. expression: make_node(AST_Number, self, {
  21551. value: 0
  21552. })
  21553. });
  21554. });
  21555. OPT(AST_Infinity, function(self, compressor){
  21556. var lhs = is_lhs(compressor.self(), compressor.parent());
  21557. if (lhs && is_atomic(lhs, self)) return self;
  21558. if (compressor.option("keep_infinity")
  21559. && !(lhs && !is_atomic(lhs, self))
  21560. && !find_variable(compressor, "Infinity"))
  21561. return self;
  21562. return make_node(AST_Binary, self, {
  21563. operator: "/",
  21564. left: make_node(AST_Number, self, {
  21565. value: 1
  21566. }),
  21567. right: make_node(AST_Number, self, {
  21568. value: 0
  21569. })
  21570. });
  21571. });
  21572. OPT(AST_NaN, function(self, compressor){
  21573. var lhs = is_lhs(compressor.self(), compressor.parent());
  21574. if (lhs && !is_atomic(lhs, self)
  21575. || find_variable(compressor, "NaN")) {
  21576. return make_node(AST_Binary, self, {
  21577. operator: "/",
  21578. left: make_node(AST_Number, self, {
  21579. value: 0
  21580. }),
  21581. right: make_node(AST_Number, self, {
  21582. value: 0
  21583. })
  21584. });
  21585. }
  21586. return self;
  21587. });
  21588. var ASSIGN_OPS = [ '+', '-', '/', '*', '%', '>>', '<<', '>>>', '|', '^', '&' ];
  21589. var ASSIGN_OPS_COMMUTATIVE = [ '*', '|', '^', '&' ];
  21590. OPT(AST_Assign, function(self, compressor){
  21591. self = self.lift_sequences(compressor);
  21592. if (self.operator == "=" && self.left instanceof AST_SymbolRef && self.right instanceof AST_Binary) {
  21593. // x = expr1 OP expr2
  21594. if (self.right.left instanceof AST_SymbolRef
  21595. && self.right.left.name == self.left.name
  21596. && member(self.right.operator, ASSIGN_OPS)) {
  21597. // x = x - 2 ---> x -= 2
  21598. self.operator = self.right.operator + "=";
  21599. self.right = self.right.right;
  21600. }
  21601. else if (self.right.right instanceof AST_SymbolRef
  21602. && self.right.right.name == self.left.name
  21603. && member(self.right.operator, ASSIGN_OPS_COMMUTATIVE)
  21604. && !self.right.left.has_side_effects(compressor)) {
  21605. // x = 2 & x ---> x &= 2
  21606. self.operator = self.right.operator + "=";
  21607. self.right = self.right.left;
  21608. }
  21609. }
  21610. return self;
  21611. });
  21612. OPT(AST_Conditional, function(self, compressor){
  21613. if (!compressor.option("conditionals")) return self;
  21614. if (self.condition instanceof AST_Seq) {
  21615. var car = self.condition.car;
  21616. self.condition = self.condition.cdr;
  21617. return AST_Seq.cons(car, self);
  21618. }
  21619. var cond = self.condition.evaluate(compressor);
  21620. if (cond !== self.condition) {
  21621. if (cond) {
  21622. compressor.warn("Condition always true [{file}:{line},{col}]", self.start);
  21623. return maintain_this_binding(compressor.parent(), self, self.consequent);
  21624. } else {
  21625. compressor.warn("Condition always false [{file}:{line},{col}]", self.start);
  21626. return maintain_this_binding(compressor.parent(), self, self.alternative);
  21627. }
  21628. }
  21629. var negated = cond.negate(compressor, first_in_statement(compressor));
  21630. if (best_of(compressor, cond, negated) === negated) {
  21631. self = make_node(AST_Conditional, self, {
  21632. condition: negated,
  21633. consequent: self.alternative,
  21634. alternative: self.consequent
  21635. });
  21636. }
  21637. var condition = self.condition;
  21638. var consequent = self.consequent;
  21639. var alternative = self.alternative;
  21640. // x?x:y --> x||y
  21641. if (condition instanceof AST_SymbolRef
  21642. && consequent instanceof AST_SymbolRef
  21643. && condition.definition() === consequent.definition()) {
  21644. return make_node(AST_Binary, self, {
  21645. operator: "||",
  21646. left: condition,
  21647. right: alternative
  21648. });
  21649. }
  21650. // if (foo) exp = something; else exp = something_else;
  21651. // |
  21652. // v
  21653. // exp = foo ? something : something_else;
  21654. if (consequent instanceof AST_Assign
  21655. && alternative instanceof AST_Assign
  21656. && consequent.operator == alternative.operator
  21657. && consequent.left.equivalent_to(alternative.left)
  21658. && (!self.condition.has_side_effects(compressor)
  21659. || consequent.operator == "="
  21660. && !consequent.left.has_side_effects(compressor))) {
  21661. return make_node(AST_Assign, self, {
  21662. operator: consequent.operator,
  21663. left: consequent.left,
  21664. right: make_node(AST_Conditional, self, {
  21665. condition: self.condition,
  21666. consequent: consequent.right,
  21667. alternative: alternative.right
  21668. })
  21669. });
  21670. }
  21671. // x ? y(a) : y(b) --> y(x ? a : b)
  21672. if (consequent instanceof AST_Call
  21673. && alternative.TYPE === consequent.TYPE
  21674. && consequent.args.length == 1
  21675. && alternative.args.length == 1
  21676. && consequent.expression.equivalent_to(alternative.expression)
  21677. && !consequent.expression.has_side_effects(compressor)) {
  21678. consequent.args[0] = make_node(AST_Conditional, self, {
  21679. condition: self.condition,
  21680. consequent: consequent.args[0],
  21681. alternative: alternative.args[0]
  21682. });
  21683. return consequent;
  21684. }
  21685. // x?y?z:a:a --> x&&y?z:a
  21686. if (consequent instanceof AST_Conditional
  21687. && consequent.alternative.equivalent_to(alternative)) {
  21688. return make_node(AST_Conditional, self, {
  21689. condition: make_node(AST_Binary, self, {
  21690. left: self.condition,
  21691. operator: "&&",
  21692. right: consequent.condition
  21693. }),
  21694. consequent: consequent.consequent,
  21695. alternative: alternative
  21696. });
  21697. }
  21698. // x ? y : y --> x, y
  21699. if (consequent.equivalent_to(alternative)) {
  21700. return make_node(AST_Seq, self, {
  21701. car: self.condition,
  21702. cdr: consequent
  21703. }).optimize(compressor);
  21704. }
  21705. if (is_true(self.consequent)) {
  21706. if (is_false(self.alternative)) {
  21707. // c ? true : false ---> !!c
  21708. return booleanize(self.condition);
  21709. }
  21710. // c ? true : x ---> !!c || x
  21711. return make_node(AST_Binary, self, {
  21712. operator: "||",
  21713. left: booleanize(self.condition),
  21714. right: self.alternative
  21715. });
  21716. }
  21717. if (is_false(self.consequent)) {
  21718. if (is_true(self.alternative)) {
  21719. // c ? false : true ---> !c
  21720. return booleanize(self.condition.negate(compressor));
  21721. }
  21722. // c ? false : x ---> !c && x
  21723. return make_node(AST_Binary, self, {
  21724. operator: "&&",
  21725. left: booleanize(self.condition.negate(compressor)),
  21726. right: self.alternative
  21727. });
  21728. }
  21729. if (is_true(self.alternative)) {
  21730. // c ? x : true ---> !c || x
  21731. return make_node(AST_Binary, self, {
  21732. operator: "||",
  21733. left: booleanize(self.condition.negate(compressor)),
  21734. right: self.consequent
  21735. });
  21736. }
  21737. if (is_false(self.alternative)) {
  21738. // c ? x : false ---> !!c && x
  21739. return make_node(AST_Binary, self, {
  21740. operator: "&&",
  21741. left: booleanize(self.condition),
  21742. right: self.consequent
  21743. });
  21744. }
  21745. return self;
  21746. function booleanize(node) {
  21747. if (node.is_boolean()) return node;
  21748. // !!expression
  21749. return make_node(AST_UnaryPrefix, node, {
  21750. operator: "!",
  21751. expression: node.negate(compressor)
  21752. });
  21753. }
  21754. // AST_True or !0
  21755. function is_true(node) {
  21756. return node instanceof AST_True
  21757. || (node instanceof AST_UnaryPrefix
  21758. && node.operator == "!"
  21759. && node.expression instanceof AST_Constant
  21760. && !node.expression.value);
  21761. }
  21762. // AST_False or !1
  21763. function is_false(node) {
  21764. return node instanceof AST_False
  21765. || (node instanceof AST_UnaryPrefix
  21766. && node.operator == "!"
  21767. && node.expression instanceof AST_Constant
  21768. && !!node.expression.value);
  21769. }
  21770. });
  21771. OPT(AST_Boolean, function(self, compressor){
  21772. if (compressor.option("booleans")) {
  21773. var p = compressor.parent();
  21774. if (p instanceof AST_Binary && (p.operator == "=="
  21775. || p.operator == "!=")) {
  21776. compressor.warn("Non-strict equality against boolean: {operator} {value} [{file}:{line},{col}]", {
  21777. operator : p.operator,
  21778. value : self.value,
  21779. file : p.start.file,
  21780. line : p.start.line,
  21781. col : p.start.col,
  21782. });
  21783. return make_node(AST_Number, self, {
  21784. value: +self.value
  21785. });
  21786. }
  21787. return make_node(AST_UnaryPrefix, self, {
  21788. operator: "!",
  21789. expression: make_node(AST_Number, self, {
  21790. value: 1 - self.value
  21791. })
  21792. });
  21793. }
  21794. return self;
  21795. });
  21796. OPT(AST_Sub, function(self, compressor){
  21797. var prop = self.property;
  21798. if (prop instanceof AST_String && compressor.option("properties")) {
  21799. prop = prop.getValue();
  21800. if (RESERVED_WORDS(prop) ? compressor.option("screw_ie8") : is_identifier_string(prop)) {
  21801. return make_node(AST_Dot, self, {
  21802. expression : self.expression,
  21803. property : prop
  21804. }).optimize(compressor);
  21805. }
  21806. var v = parseFloat(prop);
  21807. if (!isNaN(v) && v.toString() == prop) {
  21808. self.property = make_node(AST_Number, self.property, {
  21809. value: v
  21810. });
  21811. }
  21812. }
  21813. var ev = self.evaluate(compressor);
  21814. if (ev !== self) {
  21815. ev = make_node_from_constant(ev, self).optimize(compressor);
  21816. return best_of(compressor, ev, self);
  21817. }
  21818. return self;
  21819. });
  21820. OPT(AST_Dot, function(self, compressor){
  21821. var def = self.resolve_defines(compressor);
  21822. if (def) {
  21823. return def.optimize(compressor);
  21824. }
  21825. var prop = self.property;
  21826. if (RESERVED_WORDS(prop) && !compressor.option("screw_ie8")) {
  21827. return make_node(AST_Sub, self, {
  21828. expression : self.expression,
  21829. property : make_node(AST_String, self, {
  21830. value: prop
  21831. })
  21832. }).optimize(compressor);
  21833. }
  21834. if (compressor.option("unsafe_proto")
  21835. && self.expression instanceof AST_Dot
  21836. && self.expression.property == "prototype") {
  21837. var exp = self.expression.expression;
  21838. if (exp instanceof AST_SymbolRef && exp.undeclared()) switch (exp.name) {
  21839. case "Array":
  21840. self.expression = make_node(AST_Array, self.expression, {
  21841. elements: []
  21842. });
  21843. break;
  21844. case "Object":
  21845. self.expression = make_node(AST_Object, self.expression, {
  21846. properties: []
  21847. });
  21848. break;
  21849. case "String":
  21850. self.expression = make_node(AST_String, self.expression, {
  21851. value: ""
  21852. });
  21853. break;
  21854. }
  21855. }
  21856. var ev = self.evaluate(compressor);
  21857. if (ev !== self) {
  21858. ev = make_node_from_constant(ev, self).optimize(compressor);
  21859. return best_of(compressor, ev, self);
  21860. }
  21861. return self;
  21862. });
  21863. function literals_in_boolean_context(self, compressor) {
  21864. if (compressor.option("booleans") && compressor.in_boolean_context()) {
  21865. return best_of(compressor, self, make_node(AST_Seq, self, {
  21866. car: self,
  21867. cdr: make_node(AST_True, self)
  21868. }).optimize(compressor));
  21869. }
  21870. return self;
  21871. };
  21872. OPT(AST_Array, literals_in_boolean_context);
  21873. OPT(AST_Object, literals_in_boolean_context);
  21874. OPT(AST_RegExp, literals_in_boolean_context);
  21875. OPT(AST_Return, function(self, compressor){
  21876. if (self.value && is_undefined(self.value, compressor)) {
  21877. self.value = null;
  21878. }
  21879. return self;
  21880. });
  21881. OPT(AST_VarDef, function(self, compressor){
  21882. var defines = compressor.option("global_defs");
  21883. if (defines && HOP(defines, self.name.name)) {
  21884. compressor.warn('global_defs ' + self.name.name + ' redefined [{file}:{line},{col}]', self.start);
  21885. }
  21886. return self;
  21887. });
  21888. })();
  21889. /***********************************************************************
  21890. A JavaScript tokenizer / parser / beautifier / compressor.
  21891. https://github.com/mishoo/UglifyJS2
  21892. -------------------------------- (C) ---------------------------------
  21893. Author: Mihai Bazon
  21894. <mihai.bazon@gmail.com>
  21895. http://mihai.bazon.net/blog
  21896. Distributed under the BSD license:
  21897. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  21898. Redistribution and use in source and binary forms, with or without
  21899. modification, are permitted provided that the following conditions
  21900. are met:
  21901. * Redistributions of source code must retain the above
  21902. copyright notice, this list of conditions and the following
  21903. disclaimer.
  21904. * Redistributions in binary form must reproduce the above
  21905. copyright notice, this list of conditions and the following
  21906. disclaimer in the documentation and/or other materials
  21907. provided with the distribution.
  21908. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  21909. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  21910. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  21911. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  21912. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  21913. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  21914. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  21915. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  21916. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  21917. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  21918. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  21919. SUCH DAMAGE.
  21920. ***********************************************************************/
  21921. "use strict";
  21922. // a small wrapper around fitzgen's source-map library
  21923. function SourceMap(options) {
  21924. options = defaults(options, {
  21925. file : null,
  21926. root : null,
  21927. orig : null,
  21928. orig_line_diff : 0,
  21929. dest_line_diff : 0,
  21930. });
  21931. var generator = new MOZ_SourceMap.SourceMapGenerator({
  21932. file : options.file,
  21933. sourceRoot : options.root
  21934. });
  21935. var orig_map = options.orig && new MOZ_SourceMap.SourceMapConsumer(options.orig);
  21936. if (orig_map && Array.isArray(options.orig.sources)) {
  21937. orig_map._sources.toArray().forEach(function(source) {
  21938. var sourceContent = orig_map.sourceContentFor(source, true);
  21939. if (sourceContent) {
  21940. generator.setSourceContent(source, sourceContent);
  21941. }
  21942. });
  21943. }
  21944. function add(source, gen_line, gen_col, orig_line, orig_col, name) {
  21945. if (orig_map) {
  21946. var info = orig_map.originalPositionFor({
  21947. line: orig_line,
  21948. column: orig_col
  21949. });
  21950. if (info.source === null) {
  21951. return;
  21952. }
  21953. source = info.source;
  21954. orig_line = info.line;
  21955. orig_col = info.column;
  21956. name = info.name || name;
  21957. }
  21958. generator.addMapping({
  21959. generated : { line: gen_line + options.dest_line_diff, column: gen_col },
  21960. original : { line: orig_line + options.orig_line_diff, column: orig_col },
  21961. source : source,
  21962. name : name
  21963. });
  21964. };
  21965. return {
  21966. add : add,
  21967. get : function() { return generator },
  21968. toString : function() { return JSON.stringify(generator.toJSON()); }
  21969. };
  21970. };
  21971. /***********************************************************************
  21972. A JavaScript tokenizer / parser / beautifier / compressor.
  21973. https://github.com/mishoo/UglifyJS2
  21974. -------------------------------- (C) ---------------------------------
  21975. Author: Mihai Bazon
  21976. <mihai.bazon@gmail.com>
  21977. http://mihai.bazon.net/blog
  21978. Distributed under the BSD license:
  21979. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  21980. Redistribution and use in source and binary forms, with or without
  21981. modification, are permitted provided that the following conditions
  21982. are met:
  21983. * Redistributions of source code must retain the above
  21984. copyright notice, this list of conditions and the following
  21985. disclaimer.
  21986. * Redistributions in binary form must reproduce the above
  21987. copyright notice, this list of conditions and the following
  21988. disclaimer in the documentation and/or other materials
  21989. provided with the distribution.
  21990. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  21991. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  21992. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  21993. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  21994. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  21995. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  21996. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  21997. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  21998. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  21999. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  22000. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  22001. SUCH DAMAGE.
  22002. ***********************************************************************/
  22003. "use strict";
  22004. (function(){
  22005. var normalize_directives = function(body) {
  22006. var in_directive = true;
  22007. for (var i = 0; i < body.length; i++) {
  22008. if (in_directive && body[i] instanceof AST_Statement && body[i].body instanceof AST_String) {
  22009. body[i] = new AST_Directive({
  22010. start: body[i].start,
  22011. end: body[i].end,
  22012. value: body[i].body.value
  22013. });
  22014. } else if (in_directive && !(body[i] instanceof AST_Statement && body[i].body instanceof AST_String)) {
  22015. in_directive = false;
  22016. }
  22017. }
  22018. return body;
  22019. };
  22020. var MOZ_TO_ME = {
  22021. Program: function(M) {
  22022. return new AST_Toplevel({
  22023. start: my_start_token(M),
  22024. end: my_end_token(M),
  22025. body: normalize_directives(M.body.map(from_moz))
  22026. });
  22027. },
  22028. FunctionDeclaration: function(M) {
  22029. return new AST_Defun({
  22030. start: my_start_token(M),
  22031. end: my_end_token(M),
  22032. name: from_moz(M.id),
  22033. argnames: M.params.map(from_moz),
  22034. body: normalize_directives(from_moz(M.body).body)
  22035. });
  22036. },
  22037. FunctionExpression: function(M) {
  22038. return new AST_Function({
  22039. start: my_start_token(M),
  22040. end: my_end_token(M),
  22041. name: from_moz(M.id),
  22042. argnames: M.params.map(from_moz),
  22043. body: normalize_directives(from_moz(M.body).body)
  22044. });
  22045. },
  22046. ExpressionStatement: function(M) {
  22047. return new AST_SimpleStatement({
  22048. start: my_start_token(M),
  22049. end: my_end_token(M),
  22050. body: from_moz(M.expression)
  22051. });
  22052. },
  22053. TryStatement: function(M) {
  22054. var handlers = M.handlers || [M.handler];
  22055. if (handlers.length > 1 || M.guardedHandlers && M.guardedHandlers.length) {
  22056. throw new Error("Multiple catch clauses are not supported.");
  22057. }
  22058. return new AST_Try({
  22059. start : my_start_token(M),
  22060. end : my_end_token(M),
  22061. body : from_moz(M.block).body,
  22062. bcatch : from_moz(handlers[0]),
  22063. bfinally : M.finalizer ? new AST_Finally(from_moz(M.finalizer)) : null
  22064. });
  22065. },
  22066. Property: function(M) {
  22067. var key = M.key;
  22068. var args = {
  22069. start : my_start_token(key),
  22070. end : my_end_token(M.value),
  22071. key : key.type == "Identifier" ? key.name : key.value,
  22072. value : from_moz(M.value)
  22073. };
  22074. if (M.kind == "init") return new AST_ObjectKeyVal(args);
  22075. args.key = new AST_SymbolAccessor({
  22076. name: args.key
  22077. });
  22078. args.value = new AST_Accessor(args.value);
  22079. if (M.kind == "get") return new AST_ObjectGetter(args);
  22080. if (M.kind == "set") return new AST_ObjectSetter(args);
  22081. },
  22082. ArrayExpression: function(M) {
  22083. return new AST_Array({
  22084. start : my_start_token(M),
  22085. end : my_end_token(M),
  22086. elements : M.elements.map(function(elem){
  22087. return elem === null ? new AST_Hole() : from_moz(elem);
  22088. })
  22089. });
  22090. },
  22091. ObjectExpression: function(M) {
  22092. return new AST_Object({
  22093. start : my_start_token(M),
  22094. end : my_end_token(M),
  22095. properties : M.properties.map(function(prop){
  22096. prop.type = "Property";
  22097. return from_moz(prop)
  22098. })
  22099. });
  22100. },
  22101. SequenceExpression: function(M) {
  22102. return AST_Seq.from_array(M.expressions.map(from_moz));
  22103. },
  22104. MemberExpression: function(M) {
  22105. return new (M.computed ? AST_Sub : AST_Dot)({
  22106. start : my_start_token(M),
  22107. end : my_end_token(M),
  22108. property : M.computed ? from_moz(M.property) : M.property.name,
  22109. expression : from_moz(M.object)
  22110. });
  22111. },
  22112. SwitchCase: function(M) {
  22113. return new (M.test ? AST_Case : AST_Default)({
  22114. start : my_start_token(M),
  22115. end : my_end_token(M),
  22116. expression : from_moz(M.test),
  22117. body : M.consequent.map(from_moz)
  22118. });
  22119. },
  22120. VariableDeclaration: function(M) {
  22121. return new (M.kind === "const" ? AST_Const : AST_Var)({
  22122. start : my_start_token(M),
  22123. end : my_end_token(M),
  22124. definitions : M.declarations.map(from_moz)
  22125. });
  22126. },
  22127. Literal: function(M) {
  22128. var val = M.value, args = {
  22129. start : my_start_token(M),
  22130. end : my_end_token(M)
  22131. };
  22132. if (val === null) return new AST_Null(args);
  22133. switch (typeof val) {
  22134. case "string":
  22135. args.value = val;
  22136. return new AST_String(args);
  22137. case "number":
  22138. args.value = val;
  22139. return new AST_Number(args);
  22140. case "boolean":
  22141. return new (val ? AST_True : AST_False)(args);
  22142. default:
  22143. var rx = M.regex;
  22144. if (rx && rx.pattern) {
  22145. // RegExpLiteral as per ESTree AST spec
  22146. args.value = new RegExp(rx.pattern, rx.flags).toString();
  22147. } else {
  22148. // support legacy RegExp
  22149. args.value = M.regex && M.raw ? M.raw : val;
  22150. }
  22151. return new AST_RegExp(args);
  22152. }
  22153. },
  22154. Identifier: function(M) {
  22155. var p = FROM_MOZ_STACK[FROM_MOZ_STACK.length - 2];
  22156. return new ( p.type == "LabeledStatement" ? AST_Label
  22157. : p.type == "VariableDeclarator" && p.id === M ? (p.kind == "const" ? AST_SymbolConst : AST_SymbolVar)
  22158. : p.type == "FunctionExpression" ? (p.id === M ? AST_SymbolLambda : AST_SymbolFunarg)
  22159. : p.type == "FunctionDeclaration" ? (p.id === M ? AST_SymbolDefun : AST_SymbolFunarg)
  22160. : p.type == "CatchClause" ? AST_SymbolCatch
  22161. : p.type == "BreakStatement" || p.type == "ContinueStatement" ? AST_LabelRef
  22162. : AST_SymbolRef)({
  22163. start : my_start_token(M),
  22164. end : my_end_token(M),
  22165. name : M.name
  22166. });
  22167. }
  22168. };
  22169. MOZ_TO_ME.UpdateExpression =
  22170. MOZ_TO_ME.UnaryExpression = function To_Moz_Unary(M) {
  22171. var prefix = "prefix" in M ? M.prefix
  22172. : M.type == "UnaryExpression" ? true : false;
  22173. return new (prefix ? AST_UnaryPrefix : AST_UnaryPostfix)({
  22174. start : my_start_token(M),
  22175. end : my_end_token(M),
  22176. operator : M.operator,
  22177. expression : from_moz(M.argument)
  22178. });
  22179. };
  22180. map("EmptyStatement", AST_EmptyStatement);
  22181. map("BlockStatement", AST_BlockStatement, "body@body");
  22182. map("IfStatement", AST_If, "test>condition, consequent>body, alternate>alternative");
  22183. map("LabeledStatement", AST_LabeledStatement, "label>label, body>body");
  22184. map("BreakStatement", AST_Break, "label>label");
  22185. map("ContinueStatement", AST_Continue, "label>label");
  22186. map("WithStatement", AST_With, "object>expression, body>body");
  22187. map("SwitchStatement", AST_Switch, "discriminant>expression, cases@body");
  22188. map("ReturnStatement", AST_Return, "argument>value");
  22189. map("ThrowStatement", AST_Throw, "argument>value");
  22190. map("WhileStatement", AST_While, "test>condition, body>body");
  22191. map("DoWhileStatement", AST_Do, "test>condition, body>body");
  22192. map("ForStatement", AST_For, "init>init, test>condition, update>step, body>body");
  22193. map("ForInStatement", AST_ForIn, "left>init, right>object, body>body");
  22194. map("DebuggerStatement", AST_Debugger);
  22195. map("VariableDeclarator", AST_VarDef, "id>name, init>value");
  22196. map("CatchClause", AST_Catch, "param>argname, body%body");
  22197. map("ThisExpression", AST_This);
  22198. map("BinaryExpression", AST_Binary, "operator=operator, left>left, right>right");
  22199. map("LogicalExpression", AST_Binary, "operator=operator, left>left, right>right");
  22200. map("AssignmentExpression", AST_Assign, "operator=operator, left>left, right>right");
  22201. map("ConditionalExpression", AST_Conditional, "test>condition, consequent>consequent, alternate>alternative");
  22202. map("NewExpression", AST_New, "callee>expression, arguments@args");
  22203. map("CallExpression", AST_Call, "callee>expression, arguments@args");
  22204. def_to_moz(AST_Toplevel, function To_Moz_Program(M) {
  22205. return to_moz_scope("Program", M);
  22206. });
  22207. def_to_moz(AST_Defun, function To_Moz_FunctionDeclaration(M) {
  22208. return {
  22209. type: "FunctionDeclaration",
  22210. id: to_moz(M.name),
  22211. params: M.argnames.map(to_moz),
  22212. body: to_moz_scope("BlockStatement", M)
  22213. }
  22214. });
  22215. def_to_moz(AST_Function, function To_Moz_FunctionExpression(M) {
  22216. return {
  22217. type: "FunctionExpression",
  22218. id: to_moz(M.name),
  22219. params: M.argnames.map(to_moz),
  22220. body: to_moz_scope("BlockStatement", M)
  22221. }
  22222. });
  22223. def_to_moz(AST_Directive, function To_Moz_Directive(M) {
  22224. return {
  22225. type: "ExpressionStatement",
  22226. expression: {
  22227. type: "Literal",
  22228. value: M.value
  22229. }
  22230. };
  22231. });
  22232. def_to_moz(AST_SimpleStatement, function To_Moz_ExpressionStatement(M) {
  22233. return {
  22234. type: "ExpressionStatement",
  22235. expression: to_moz(M.body)
  22236. };
  22237. });
  22238. def_to_moz(AST_SwitchBranch, function To_Moz_SwitchCase(M) {
  22239. return {
  22240. type: "SwitchCase",
  22241. test: to_moz(M.expression),
  22242. consequent: M.body.map(to_moz)
  22243. };
  22244. });
  22245. def_to_moz(AST_Try, function To_Moz_TryStatement(M) {
  22246. return {
  22247. type: "TryStatement",
  22248. block: to_moz_block(M),
  22249. handler: to_moz(M.bcatch),
  22250. guardedHandlers: [],
  22251. finalizer: to_moz(M.bfinally)
  22252. };
  22253. });
  22254. def_to_moz(AST_Catch, function To_Moz_CatchClause(M) {
  22255. return {
  22256. type: "CatchClause",
  22257. param: to_moz(M.argname),
  22258. guard: null,
  22259. body: to_moz_block(M)
  22260. };
  22261. });
  22262. def_to_moz(AST_Definitions, function To_Moz_VariableDeclaration(M) {
  22263. return {
  22264. type: "VariableDeclaration",
  22265. kind: M instanceof AST_Const ? "const" : "var",
  22266. declarations: M.definitions.map(to_moz)
  22267. };
  22268. });
  22269. def_to_moz(AST_Seq, function To_Moz_SequenceExpression(M) {
  22270. return {
  22271. type: "SequenceExpression",
  22272. expressions: M.to_array().map(to_moz)
  22273. };
  22274. });
  22275. def_to_moz(AST_PropAccess, function To_Moz_MemberExpression(M) {
  22276. var isComputed = M instanceof AST_Sub;
  22277. return {
  22278. type: "MemberExpression",
  22279. object: to_moz(M.expression),
  22280. computed: isComputed,
  22281. property: isComputed ? to_moz(M.property) : {type: "Identifier", name: M.property}
  22282. };
  22283. });
  22284. def_to_moz(AST_Unary, function To_Moz_Unary(M) {
  22285. return {
  22286. type: M.operator == "++" || M.operator == "--" ? "UpdateExpression" : "UnaryExpression",
  22287. operator: M.operator,
  22288. prefix: M instanceof AST_UnaryPrefix,
  22289. argument: to_moz(M.expression)
  22290. };
  22291. });
  22292. def_to_moz(AST_Binary, function To_Moz_BinaryExpression(M) {
  22293. return {
  22294. type: M.operator == "&&" || M.operator == "||" ? "LogicalExpression" : "BinaryExpression",
  22295. left: to_moz(M.left),
  22296. operator: M.operator,
  22297. right: to_moz(M.right)
  22298. };
  22299. });
  22300. def_to_moz(AST_Array, function To_Moz_ArrayExpression(M) {
  22301. return {
  22302. type: "ArrayExpression",
  22303. elements: M.elements.map(to_moz)
  22304. };
  22305. });
  22306. def_to_moz(AST_Object, function To_Moz_ObjectExpression(M) {
  22307. return {
  22308. type: "ObjectExpression",
  22309. properties: M.properties.map(to_moz)
  22310. };
  22311. });
  22312. def_to_moz(AST_ObjectProperty, function To_Moz_Property(M) {
  22313. var key = {
  22314. type: "Literal",
  22315. value: M.key instanceof AST_SymbolAccessor ? M.key.name : M.key
  22316. };
  22317. var kind;
  22318. if (M instanceof AST_ObjectKeyVal) {
  22319. kind = "init";
  22320. } else
  22321. if (M instanceof AST_ObjectGetter) {
  22322. kind = "get";
  22323. } else
  22324. if (M instanceof AST_ObjectSetter) {
  22325. kind = "set";
  22326. }
  22327. return {
  22328. type: "Property",
  22329. kind: kind,
  22330. key: key,
  22331. value: to_moz(M.value)
  22332. };
  22333. });
  22334. def_to_moz(AST_Symbol, function To_Moz_Identifier(M) {
  22335. var def = M.definition();
  22336. return {
  22337. type: "Identifier",
  22338. name: def ? def.mangled_name || def.name : M.name
  22339. };
  22340. });
  22341. def_to_moz(AST_RegExp, function To_Moz_RegExpLiteral(M) {
  22342. var value = M.value;
  22343. return {
  22344. type: "Literal",
  22345. value: value,
  22346. raw: value.toString(),
  22347. regex: {
  22348. pattern: value.source,
  22349. flags: value.toString().match(/[gimuy]*$/)[0]
  22350. }
  22351. };
  22352. });
  22353. def_to_moz(AST_Constant, function To_Moz_Literal(M) {
  22354. var value = M.value;
  22355. if (typeof value === 'number' && (value < 0 || (value === 0 && 1 / value < 0))) {
  22356. return {
  22357. type: "UnaryExpression",
  22358. operator: "-",
  22359. prefix: true,
  22360. argument: {
  22361. type: "Literal",
  22362. value: -value,
  22363. raw: M.start.raw
  22364. }
  22365. };
  22366. }
  22367. return {
  22368. type: "Literal",
  22369. value: value,
  22370. raw: M.start.raw
  22371. };
  22372. });
  22373. def_to_moz(AST_Atom, function To_Moz_Atom(M) {
  22374. return {
  22375. type: "Identifier",
  22376. name: String(M.value)
  22377. };
  22378. });
  22379. AST_Boolean.DEFMETHOD("to_mozilla_ast", AST_Constant.prototype.to_mozilla_ast);
  22380. AST_Null.DEFMETHOD("to_mozilla_ast", AST_Constant.prototype.to_mozilla_ast);
  22381. AST_Hole.DEFMETHOD("to_mozilla_ast", function To_Moz_ArrayHole() { return null });
  22382. AST_Block.DEFMETHOD("to_mozilla_ast", AST_BlockStatement.prototype.to_mozilla_ast);
  22383. AST_Lambda.DEFMETHOD("to_mozilla_ast", AST_Function.prototype.to_mozilla_ast);
  22384. /* -----[ tools ]----- */
  22385. function raw_token(moznode) {
  22386. if (moznode.type == "Literal") {
  22387. return moznode.raw != null ? moznode.raw : moznode.value + "";
  22388. }
  22389. }
  22390. function my_start_token(moznode) {
  22391. var loc = moznode.loc, start = loc && loc.start;
  22392. var range = moznode.range;
  22393. return new AST_Token({
  22394. file : loc && loc.source,
  22395. line : start && start.line,
  22396. col : start && start.column,
  22397. pos : range ? range[0] : moznode.start,
  22398. endline : start && start.line,
  22399. endcol : start && start.column,
  22400. endpos : range ? range[0] : moznode.start,
  22401. raw : raw_token(moznode),
  22402. });
  22403. };
  22404. function my_end_token(moznode) {
  22405. var loc = moznode.loc, end = loc && loc.end;
  22406. var range = moznode.range;
  22407. return new AST_Token({
  22408. file : loc && loc.source,
  22409. line : end && end.line,
  22410. col : end && end.column,
  22411. pos : range ? range[1] : moznode.end,
  22412. endline : end && end.line,
  22413. endcol : end && end.column,
  22414. endpos : range ? range[1] : moznode.end,
  22415. raw : raw_token(moznode),
  22416. });
  22417. };
  22418. function map(moztype, mytype, propmap) {
  22419. var moz_to_me = "function From_Moz_" + moztype + "(M){\n";
  22420. moz_to_me += "return new U2." + mytype.name + "({\n" +
  22421. "start: my_start_token(M),\n" +
  22422. "end: my_end_token(M)";
  22423. var me_to_moz = "function To_Moz_" + moztype + "(M){\n";
  22424. me_to_moz += "return {\n" +
  22425. "type: " + JSON.stringify(moztype);
  22426. if (propmap) propmap.split(/\s*,\s*/).forEach(function(prop){
  22427. var m = /([a-z0-9$_]+)(=|@|>|%)([a-z0-9$_]+)/i.exec(prop);
  22428. if (!m) throw new Error("Can't understand property map: " + prop);
  22429. var moz = m[1], how = m[2], my = m[3];
  22430. moz_to_me += ",\n" + my + ": ";
  22431. me_to_moz += ",\n" + moz + ": ";
  22432. switch (how) {
  22433. case "@":
  22434. moz_to_me += "M." + moz + ".map(from_moz)";
  22435. me_to_moz += "M." + my + ".map(to_moz)";
  22436. break;
  22437. case ">":
  22438. moz_to_me += "from_moz(M." + moz + ")";
  22439. me_to_moz += "to_moz(M." + my + ")";
  22440. break;
  22441. case "=":
  22442. moz_to_me += "M." + moz;
  22443. me_to_moz += "M." + my;
  22444. break;
  22445. case "%":
  22446. moz_to_me += "from_moz(M." + moz + ").body";
  22447. me_to_moz += "to_moz_block(M)";
  22448. break;
  22449. default:
  22450. throw new Error("Can't understand operator in propmap: " + prop);
  22451. }
  22452. });
  22453. moz_to_me += "\n})\n}";
  22454. me_to_moz += "\n}\n}";
  22455. //moz_to_me = parse(moz_to_me).print_to_string({ beautify: true });
  22456. //me_to_moz = parse(me_to_moz).print_to_string({ beautify: true });
  22457. //console.log(moz_to_me);
  22458. moz_to_me = new Function("U2", "my_start_token", "my_end_token", "from_moz", "return(" + moz_to_me + ")")(
  22459. exports, my_start_token, my_end_token, from_moz
  22460. );
  22461. me_to_moz = new Function("to_moz", "to_moz_block", "to_moz_scope", "return(" + me_to_moz + ")")(
  22462. to_moz, to_moz_block, to_moz_scope
  22463. );
  22464. MOZ_TO_ME[moztype] = moz_to_me;
  22465. def_to_moz(mytype, me_to_moz);
  22466. };
  22467. var FROM_MOZ_STACK = null;
  22468. function from_moz(node) {
  22469. FROM_MOZ_STACK.push(node);
  22470. var ret = node != null ? MOZ_TO_ME[node.type](node) : null;
  22471. FROM_MOZ_STACK.pop();
  22472. return ret;
  22473. };
  22474. AST_Node.from_mozilla_ast = function(node){
  22475. var save_stack = FROM_MOZ_STACK;
  22476. FROM_MOZ_STACK = [];
  22477. var ast = from_moz(node);
  22478. FROM_MOZ_STACK = save_stack;
  22479. return ast;
  22480. };
  22481. function set_moz_loc(mynode, moznode, myparent) {
  22482. var start = mynode.start;
  22483. var end = mynode.end;
  22484. if (start.pos != null && end.endpos != null) {
  22485. moznode.range = [start.pos, end.endpos];
  22486. }
  22487. if (start.line) {
  22488. moznode.loc = {
  22489. start: {line: start.line, column: start.col},
  22490. end: end.endline ? {line: end.endline, column: end.endcol} : null
  22491. };
  22492. if (start.file) {
  22493. moznode.loc.source = start.file;
  22494. }
  22495. }
  22496. return moznode;
  22497. };
  22498. function def_to_moz(mytype, handler) {
  22499. mytype.DEFMETHOD("to_mozilla_ast", function() {
  22500. return set_moz_loc(this, handler(this));
  22501. });
  22502. };
  22503. function to_moz(node) {
  22504. return node != null ? node.to_mozilla_ast() : null;
  22505. };
  22506. function to_moz_block(node) {
  22507. return {
  22508. type: "BlockStatement",
  22509. body: node.body.map(to_moz)
  22510. };
  22511. };
  22512. function to_moz_scope(type, node) {
  22513. var body = node.body.map(to_moz);
  22514. if (node.body[0] instanceof AST_SimpleStatement && node.body[0].body instanceof AST_String) {
  22515. body.unshift(to_moz(new AST_EmptyStatement(node.body[0])));
  22516. }
  22517. return {
  22518. type: type,
  22519. body: body
  22520. };
  22521. };
  22522. })();
  22523. /***********************************************************************
  22524. A JavaScript tokenizer / parser / beautifier / compressor.
  22525. https://github.com/mishoo/UglifyJS2
  22526. -------------------------------- (C) ---------------------------------
  22527. Author: Mihai Bazon
  22528. <mihai.bazon@gmail.com>
  22529. http://mihai.bazon.net/blog
  22530. Distributed under the BSD license:
  22531. Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
  22532. Redistribution and use in source and binary forms, with or without
  22533. modification, are permitted provided that the following conditions
  22534. are met:
  22535. * Redistributions of source code must retain the above
  22536. copyright notice, this list of conditions and the following
  22537. disclaimer.
  22538. * Redistributions in binary form must reproduce the above
  22539. copyright notice, this list of conditions and the following
  22540. disclaimer in the documentation and/or other materials
  22541. provided with the distribution.
  22542. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
  22543. EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  22544. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  22545. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
  22546. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
  22547. OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  22548. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  22549. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  22550. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  22551. TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  22552. THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  22553. SUCH DAMAGE.
  22554. ***********************************************************************/
  22555. "use strict";
  22556. function find_builtins() {
  22557. // NaN will be included due to Number.NaN
  22558. var a = [
  22559. "null",
  22560. "true",
  22561. "false",
  22562. "Infinity",
  22563. "-Infinity",
  22564. "undefined",
  22565. ];
  22566. [ Object, Array, Function, Number,
  22567. String, Boolean, Error, Math,
  22568. Date, RegExp
  22569. ].forEach(function(ctor){
  22570. Object.getOwnPropertyNames(ctor).map(add);
  22571. if (ctor.prototype) {
  22572. Object.getOwnPropertyNames(ctor.prototype).map(add);
  22573. }
  22574. });
  22575. function add(name) {
  22576. push_uniq(a, name);
  22577. }
  22578. return a;
  22579. }
  22580. function mangle_properties(ast, options) {
  22581. options = defaults(options, {
  22582. cache: null,
  22583. debug: false,
  22584. ignore_quoted: false,
  22585. only_cache: false,
  22586. regex: null,
  22587. reserved: null,
  22588. });
  22589. var reserved = options.reserved;
  22590. if (reserved == null)
  22591. reserved = find_builtins();
  22592. var cache = options.cache;
  22593. if (cache == null) {
  22594. cache = {
  22595. cname: -1,
  22596. props: new Dictionary()
  22597. };
  22598. }
  22599. var regex = options.regex;
  22600. var ignore_quoted = options.ignore_quoted;
  22601. // note debug is either false (disabled), or a string of the debug suffix to use (enabled).
  22602. // note debug may be enabled as an empty string, which is falsey. Also treat passing 'true'
  22603. // the same as passing an empty string.
  22604. var debug = (options.debug !== false);
  22605. var debug_name_suffix;
  22606. if (debug) {
  22607. debug_name_suffix = (options.debug === true ? "" : options.debug);
  22608. }
  22609. var names_to_mangle = [];
  22610. var unmangleable = [];
  22611. var ignored = {};
  22612. // step 1: find candidates to mangle
  22613. ast.walk(new TreeWalker(function(node){
  22614. if (node instanceof AST_ObjectKeyVal) {
  22615. add(node.key, ignore_quoted && node.quote);
  22616. }
  22617. else if (node instanceof AST_ObjectProperty) {
  22618. // setter or getter, since KeyVal is handled above
  22619. add(node.key.name);
  22620. }
  22621. else if (node instanceof AST_Dot) {
  22622. add(node.property);
  22623. }
  22624. else if (node instanceof AST_Sub) {
  22625. addStrings(node.property, ignore_quoted);
  22626. }
  22627. }));
  22628. // step 2: transform the tree, renaming properties
  22629. return ast.transform(new TreeTransformer(function(node){
  22630. if (node instanceof AST_ObjectKeyVal) {
  22631. if (!(ignore_quoted && node.quote))
  22632. node.key = mangle(node.key);
  22633. }
  22634. else if (node instanceof AST_ObjectProperty) {
  22635. // setter or getter
  22636. node.key.name = mangle(node.key.name);
  22637. }
  22638. else if (node instanceof AST_Dot) {
  22639. node.property = mangle(node.property);
  22640. }
  22641. else if (node instanceof AST_Sub) {
  22642. if (!ignore_quoted)
  22643. node.property = mangleStrings(node.property);
  22644. }
  22645. // else if (node instanceof AST_String) {
  22646. // if (should_mangle(node.value)) {
  22647. // AST_Node.warn(
  22648. // "Found \"{prop}\" property candidate for mangling in an arbitrary string [{file}:{line},{col}]", {
  22649. // file : node.start.file,
  22650. // line : node.start.line,
  22651. // col : node.start.col,
  22652. // prop : node.value
  22653. // }
  22654. // );
  22655. // }
  22656. // }
  22657. }));
  22658. // only function declarations after this line
  22659. function can_mangle(name) {
  22660. if (unmangleable.indexOf(name) >= 0) return false;
  22661. if (reserved.indexOf(name) >= 0) return false;
  22662. if (options.only_cache) {
  22663. return cache.props.has(name);
  22664. }
  22665. if (/^-?[0-9]+(\.[0-9]+)?(e[+-][0-9]+)?$/.test(name)) return false;
  22666. return true;
  22667. }
  22668. function should_mangle(name) {
  22669. if (ignore_quoted && name in ignored) return false;
  22670. if (regex && !regex.test(name)) return false;
  22671. if (reserved.indexOf(name) >= 0) return false;
  22672. return cache.props.has(name)
  22673. || names_to_mangle.indexOf(name) >= 0;
  22674. }
  22675. function add(name, ignore) {
  22676. if (ignore) {
  22677. ignored[name] = true;
  22678. return;
  22679. }
  22680. if (can_mangle(name))
  22681. push_uniq(names_to_mangle, name);
  22682. if (!should_mangle(name)) {
  22683. push_uniq(unmangleable, name);
  22684. }
  22685. }
  22686. function mangle(name) {
  22687. if (!should_mangle(name)) {
  22688. return name;
  22689. }
  22690. var mangled = cache.props.get(name);
  22691. if (!mangled) {
  22692. if (debug) {
  22693. // debug mode: use a prefix and suffix to preserve readability, e.g. o.foo -> o._$foo$NNN_.
  22694. var debug_mangled = "_$" + name + "$" + debug_name_suffix + "_";
  22695. if (can_mangle(debug_mangled) && !(ignore_quoted && debug_mangled in ignored)) {
  22696. mangled = debug_mangled;
  22697. }
  22698. }
  22699. // either debug mode is off, or it is on and we could not use the mangled name
  22700. if (!mangled) {
  22701. // note can_mangle() does not check if the name collides with the 'ignored' set
  22702. // (filled with quoted properties when ignore_quoted set). Make sure we add this
  22703. // check so we don't collide with a quoted name.
  22704. do {
  22705. mangled = base54(++cache.cname);
  22706. } while (!can_mangle(mangled) || (ignore_quoted && mangled in ignored));
  22707. }
  22708. cache.props.set(name, mangled);
  22709. }
  22710. return mangled;
  22711. }
  22712. function addStrings(node, ignore) {
  22713. var out = {};
  22714. try {
  22715. (function walk(node){
  22716. node.walk(new TreeWalker(function(node){
  22717. if (node instanceof AST_Seq) {
  22718. walk(node.cdr);
  22719. return true;
  22720. }
  22721. if (node instanceof AST_String) {
  22722. add(node.value, ignore);
  22723. return true;
  22724. }
  22725. if (node instanceof AST_Conditional) {
  22726. walk(node.consequent);
  22727. walk(node.alternative);
  22728. return true;
  22729. }
  22730. throw out;
  22731. }));
  22732. })(node);
  22733. } catch(ex) {
  22734. if (ex !== out) throw ex;
  22735. }
  22736. }
  22737. function mangleStrings(node) {
  22738. return node.transform(new TreeTransformer(function(node){
  22739. if (node instanceof AST_Seq) {
  22740. node.cdr = mangleStrings(node.cdr);
  22741. }
  22742. else if (node instanceof AST_String) {
  22743. node.value = mangle(node.value);
  22744. }
  22745. else if (node instanceof AST_Conditional) {
  22746. node.consequent = mangleStrings(node.consequent);
  22747. node.alternative = mangleStrings(node.alternative);
  22748. }
  22749. return node;
  22750. }));
  22751. }
  22752. }
  22753. exports["Compressor"] = Compressor;
  22754. exports["DefaultsError"] = DefaultsError;
  22755. exports["Dictionary"] = Dictionary;
  22756. exports["JS_Parse_Error"] = JS_Parse_Error;
  22757. exports["MAP"] = MAP;
  22758. exports["OutputStream"] = OutputStream;
  22759. exports["SourceMap"] = SourceMap;
  22760. exports["TreeTransformer"] = TreeTransformer;
  22761. exports["TreeWalker"] = TreeWalker;
  22762. exports["base54"] = base54;
  22763. exports["defaults"] = defaults;
  22764. exports["mangle_properties"] = mangle_properties;
  22765. exports["merge"] = merge;
  22766. exports["parse"] = parse;
  22767. exports["push_uniq"] = push_uniq;
  22768. exports["string_template"] = string_template;
  22769. exports["tokenizer"] = tokenizer;
  22770. exports["is_identifier"] = is_identifier;
  22771. exports["SymbolDef"] = SymbolDef;
  22772. AST_Node.warn_function = function(txt) { logger.error("uglifyjs WARN: " + txt); };
  22773. // workaround for tty output truncation upon process.exit()
  22774. [process.stdout, process.stderr].forEach(function(stream){
  22775. if (stream._handle && stream._handle.setBlocking)
  22776. stream._handle.setBlocking(true);
  22777. });
  22778. exports.AST_Node.warn_function = function(txt) {
  22779. console.error("WARN: %s", txt);
  22780. };
  22781. function read_source_map(code) {
  22782. var match = /\n\/\/# sourceMappingURL=data:application\/json(;.*?)?;base64,(.*)/.exec(code);
  22783. if (!match) {
  22784. exports.AST_Node.warn("inline source map not found");
  22785. return null;
  22786. }
  22787. return JSON.parse(new Buffer(match[2], "base64"));
  22788. }
  22789. exports.minify = function(files, options, name) {
  22790. options = exports.defaults(options, {
  22791. compress : {},
  22792. fromString : false,
  22793. inSourceMap : null,
  22794. mangle : {},
  22795. mangleProperties : false,
  22796. nameCache : null,
  22797. outFileName : null,
  22798. output : null,
  22799. outSourceMap : null,
  22800. parse : {},
  22801. sourceMapInline : false,
  22802. sourceMapUrl : null,
  22803. sourceRoot : null,
  22804. spidermonkey : false,
  22805. warnings : false,
  22806. });
  22807. exports.base54.reset();
  22808. var inMap = options.inSourceMap;
  22809. if (typeof inMap == "string" && inMap != "inline") {
  22810. inMap = JSON.parse(rjsFile.readFile(inMap, "utf8"));
  22811. }
  22812. // 1. parse
  22813. var toplevel = null,
  22814. sourcesContent = {};
  22815. if (options.spidermonkey) {
  22816. if (inMap == "inline") {
  22817. throw new Error("inline source map only works with built-in parser");
  22818. }
  22819. toplevel = exports.AST_Node.from_mozilla_ast(files);
  22820. } else {
  22821. var addFile = function(file, fileUrl) {
  22822. var code = options.fromString
  22823. ? file
  22824. : rjsFile.readFile(file, "utf8");
  22825. if (inMap == "inline") {
  22826. inMap = read_source_map(code);
  22827. }
  22828. sourcesContent[fileUrl] = code;
  22829. toplevel = exports.parse(code, {
  22830. filename: fileUrl,
  22831. toplevel: toplevel,
  22832. bare_returns: options.parse ? options.parse.bare_returns : undefined
  22833. });
  22834. }
  22835. if (!options.fromString) {
  22836. files = exports.simple_glob(files);
  22837. if (inMap == "inline" && files.length > 1) {
  22838. throw new Error("inline source map only works with singular input");
  22839. }
  22840. }
  22841. [].concat(files).forEach(function (files, i) {
  22842. if (typeof files === 'string') {
  22843. addFile(files, options.fromString ? i : files);
  22844. } else {
  22845. for (var fileUrl in files) {
  22846. addFile(files[fileUrl], fileUrl);
  22847. }
  22848. }
  22849. });
  22850. }
  22851. if (options.wrap) {
  22852. toplevel = toplevel.wrap_commonjs(options.wrap, options.exportAll);
  22853. }
  22854. // 2. compress
  22855. if (options.compress) {
  22856. var compress = { warnings: options.warnings };
  22857. exports.merge(compress, options.compress);
  22858. toplevel.figure_out_scope(options.mangle);
  22859. var sq = exports.Compressor(compress);
  22860. toplevel = sq.compress(toplevel);
  22861. }
  22862. // 3. mangle properties
  22863. if (options.mangleProperties || options.nameCache) {
  22864. options.mangleProperties.cache = exports.readNameCache(options.nameCache, "props");
  22865. toplevel = exports.mangle_properties(toplevel, options.mangleProperties);
  22866. exports.writeNameCache(options.nameCache, "props", options.mangleProperties.cache);
  22867. }
  22868. // 4. mangle
  22869. if (options.mangle) {
  22870. toplevel.figure_out_scope(options.mangle);
  22871. toplevel.compute_char_frequency(options.mangle);
  22872. toplevel.mangle_names(options.mangle);
  22873. }
  22874. // 5. output
  22875. var output = { max_line_len: 32000 };
  22876. if (options.outSourceMap || options.sourceMapInline) {
  22877. output.source_map = exports.SourceMap({
  22878. // prefer outFileName, otherwise use outSourceMap without .map suffix
  22879. file: options.outFileName || (typeof options.outSourceMap === 'string' ? options.outSourceMap.replace(/\.map$/i, '') : null),
  22880. orig: inMap,
  22881. root: options.sourceRoot
  22882. });
  22883. if (options.sourceMapIncludeSources) {
  22884. for (var file in sourcesContent) {
  22885. if (sourcesContent.hasOwnProperty(file)) {
  22886. output.source_map.get().setSourceContent(file, sourcesContent[file]);
  22887. }
  22888. }
  22889. }
  22890. }
  22891. if (options.output) {
  22892. exports.merge(output, options.output);
  22893. }
  22894. var stream = exports.OutputStream(output);
  22895. toplevel.print(stream);
  22896. var source_map = output.source_map;
  22897. if (source_map) {
  22898. source_map = source_map + "";
  22899. }
  22900. var mappingUrlPrefix = "\n//# sourceMappingURL=";
  22901. if (options.sourceMapInline) {
  22902. stream += mappingUrlPrefix + "data:application/json;charset=utf-8;base64," + new Buffer(source_map).toString("base64");
  22903. } else if (options.outSourceMap && typeof options.outSourceMap === "string" && options.sourceMapUrl !== false) {
  22904. stream += mappingUrlPrefix + (typeof options.sourceMapUrl === "string" ? options.sourceMapUrl : options.outSourceMap);
  22905. }
  22906. return {
  22907. code : stream + "",
  22908. map : source_map
  22909. };
  22910. };
  22911. // exports.describe_ast = function() {
  22912. // function doitem(ctor) {
  22913. // var sub = {};
  22914. // ctor.SUBCLASSES.forEach(function(ctor){
  22915. // sub[ctor.TYPE] = doitem(ctor);
  22916. // });
  22917. // var ret = {};
  22918. // if (ctor.SELF_PROPS.length > 0) ret.props = ctor.SELF_PROPS;
  22919. // if (ctor.SUBCLASSES.length > 0) ret.sub = sub;
  22920. // return ret;
  22921. // }
  22922. // return doitem(exports.AST_Node).sub;
  22923. // }
  22924. exports.describe_ast = function() {
  22925. var out = exports.OutputStream({ beautify: true });
  22926. function doitem(ctor) {
  22927. out.print("AST_" + ctor.TYPE);
  22928. var props = ctor.SELF_PROPS.filter(function(prop){
  22929. return !/^\$/.test(prop);
  22930. });
  22931. if (props.length > 0) {
  22932. out.space();
  22933. out.with_parens(function(){
  22934. props.forEach(function(prop, i){
  22935. if (i) out.space();
  22936. out.print(prop);
  22937. });
  22938. });
  22939. }
  22940. if (ctor.documentation) {
  22941. out.space();
  22942. out.print_string(ctor.documentation);
  22943. }
  22944. if (ctor.SUBCLASSES.length > 0) {
  22945. out.space();
  22946. out.with_block(function(){
  22947. ctor.SUBCLASSES.forEach(function(ctor, i){
  22948. out.indent();
  22949. doitem(ctor);
  22950. out.newline();
  22951. });
  22952. });
  22953. }
  22954. };
  22955. doitem(exports.AST_Node);
  22956. return out + "";
  22957. };
  22958. function readReservedFile(filename, reserved) {
  22959. if (!reserved) {
  22960. reserved = { vars: [], props: [] };
  22961. }
  22962. var data = rjsFile.readFile(filename, "utf8");
  22963. data = JSON.parse(data);
  22964. if (data.vars) {
  22965. data.vars.forEach(function(name){
  22966. exports.push_uniq(reserved.vars, name);
  22967. });
  22968. }
  22969. if (data.props) {
  22970. data.props.forEach(function(name){
  22971. exports.push_uniq(reserved.props, name);
  22972. });
  22973. }
  22974. return reserved;
  22975. }
  22976. exports.readReservedFile = readReservedFile;
  22977. exports.readDefaultReservedFile = function(reserved) {
  22978. return readReservedFile(require.resolve("./domprops.json"), reserved);
  22979. };
  22980. exports.readNameCache = function(filename, key) {
  22981. var cache = null;
  22982. if (filename) {
  22983. try {
  22984. var cache = rjsFile.readFile(filename, "utf8");
  22985. cache = JSON.parse(cache)[key];
  22986. if (!cache) throw "init";
  22987. cache.props = exports.Dictionary.fromObject(cache.props);
  22988. } catch(ex) {
  22989. cache = {
  22990. cname: -1,
  22991. props: new exports.Dictionary()
  22992. };
  22993. }
  22994. }
  22995. return cache;
  22996. };
  22997. exports.writeNameCache = function(filename, key, cache) {
  22998. if (filename) {
  22999. var data;
  23000. try {
  23001. data = rjsFile.readFile(filename, "utf8");
  23002. data = JSON.parse(data);
  23003. } catch(ex) {
  23004. data = {};
  23005. }
  23006. data[key] = {
  23007. cname: cache.cname,
  23008. props: cache.props.toObject()
  23009. };
  23010. rjsFile.writeFile(filename, JSON.stringify(data, null, 2), "utf8");
  23011. }
  23012. };
  23013. // A file glob function that only supports "*" and "?" wildcards in the basename.
  23014. // Example: "foo/bar/*baz??.*.js"
  23015. // Argument `glob` may be a string or an array of strings.
  23016. // Returns an array of strings. Garbage in, garbage out.
  23017. exports.simple_glob = function simple_glob(glob) {
  23018. if (Array.isArray(glob)) {
  23019. return [].concat.apply([], glob.map(simple_glob));
  23020. }
  23021. if (glob.match(/\*|\?/)) {
  23022. var dir = path.dirname(glob);
  23023. try {
  23024. var entries = fs.readdirSync(dir);
  23025. } catch (ex) {}
  23026. if (entries) {
  23027. var pattern = "^" + path.basename(glob)
  23028. .replace(/[.+^$[\]\\(){}]/g, "\\$&")
  23029. .replace(/\*/g, "[^/\\\\]*")
  23030. .replace(/\?/g, "[^/\\\\]") + "$";
  23031. var mod = process.platform === "win32" ? "i" : "";
  23032. var rx = new RegExp(pattern, mod);
  23033. var results = entries.filter(function(name) {
  23034. return rx.test(name);
  23035. }).map(function(name) {
  23036. return path.join(dir, name);
  23037. });
  23038. if (results.length) return results;
  23039. }
  23040. }
  23041. return [ glob ];
  23042. };
  23043. });
  23044. /*jslint plusplus: true */
  23045. /*global define: false */
  23046. define('parse', ['./esprimaAdapter', 'lang'], function (esprima, lang) {
  23047. 'use strict';
  23048. function arrayToString(ary) {
  23049. var output = '[';
  23050. if (ary) {
  23051. ary.forEach(function (item, i) {
  23052. output += (i > 0 ? ',' : '') + '"' + lang.jsEscape(item) + '"';
  23053. });
  23054. }
  23055. output += ']';
  23056. return output;
  23057. }
  23058. //This string is saved off because JSLint complains
  23059. //about obj.arguments use, as 'reserved word'
  23060. var argPropName = 'arguments',
  23061. //Default object to use for "scope" checking for UMD identifiers.
  23062. emptyScope = {},
  23063. mixin = lang.mixin,
  23064. hasProp = lang.hasProp;
  23065. //From an esprima example for traversing its ast.
  23066. function traverse(object, visitor) {
  23067. var child;
  23068. if (!object) {
  23069. return;
  23070. }
  23071. if (visitor.call(null, object) === false) {
  23072. return false;
  23073. }
  23074. for (var i = 0, keys = Object.keys(object); i < keys.length; i++) {
  23075. child = object[keys[i]];
  23076. if (typeof child === 'object' && child !== null) {
  23077. if (traverse(child, visitor) === false) {
  23078. return false;
  23079. }
  23080. }
  23081. }
  23082. }
  23083. //Like traverse, but visitor returning false just
  23084. //stops that subtree analysis, not the rest of tree
  23085. //visiting.
  23086. function traverseBroad(object, visitor) {
  23087. var child;
  23088. if (!object) {
  23089. return;
  23090. }
  23091. if (visitor.call(null, object) === false) {
  23092. return false;
  23093. }
  23094. for (var i = 0, keys = Object.keys(object); i < keys.length; i++) {
  23095. child = object[key];
  23096. if (typeof child === 'object' && child !== null) {
  23097. traverseBroad(child, visitor);
  23098. }
  23099. }
  23100. }
  23101. /**
  23102. * Pulls out dependencies from an array literal with just string members.
  23103. * If string literals, will just return those string values in an array,
  23104. * skipping other items in the array.
  23105. *
  23106. * @param {Node} node an AST node.
  23107. *
  23108. * @returns {Array} an array of strings.
  23109. * If null is returned, then it means the input node was not a valid
  23110. * dependency.
  23111. */
  23112. function getValidDeps(node) {
  23113. if (!node || node.type !== 'ArrayExpression' || !node.elements) {
  23114. return;
  23115. }
  23116. var deps = [];
  23117. node.elements.some(function (elem) {
  23118. if (elem.type === 'Literal') {
  23119. deps.push(elem.value);
  23120. }
  23121. });
  23122. return deps.length ? deps : undefined;
  23123. }
  23124. // Detects regular or arrow function expressions as the desired expression
  23125. // type.
  23126. function isFnExpression(node) {
  23127. return (node && (node.type === 'FunctionExpression' ||
  23128. node.type === 'ArrowFunctionExpression'));
  23129. }
  23130. /**
  23131. * Main parse function. Returns a string of any valid require or
  23132. * define/require.def calls as part of one JavaScript source string.
  23133. * @param {String} moduleName the module name that represents this file.
  23134. * It is used to create a default define if there is not one already for the
  23135. * file. This allows properly tracing dependencies for builds. Otherwise, if
  23136. * the file just has a require() call, the file dependencies will not be
  23137. * properly reflected: the file will come before its dependencies.
  23138. * @param {String} moduleName
  23139. * @param {String} fileName
  23140. * @param {String} fileContents
  23141. * @param {Object} options optional options. insertNeedsDefine: true will
  23142. * add calls to require.needsDefine() if appropriate.
  23143. * @returns {String} JS source string or null, if no require or
  23144. * define/require.def calls are found.
  23145. */
  23146. function parse(moduleName, fileName, fileContents, options) {
  23147. options = options || {};
  23148. //Set up source input
  23149. var i, moduleCall, depString,
  23150. moduleDeps = [],
  23151. result = '',
  23152. moduleList = [],
  23153. needsDefine = true,
  23154. astRoot = esprima.parse(fileContents);
  23155. parse.recurse(astRoot, function (callName, config, name, deps, node, factoryIdentifier, fnExpScope) {
  23156. if (!deps) {
  23157. deps = [];
  23158. }
  23159. if (callName === 'define' && (!name || name === moduleName)) {
  23160. needsDefine = false;
  23161. }
  23162. if (!name) {
  23163. //If there is no module name, the dependencies are for
  23164. //this file/default module name.
  23165. moduleDeps = moduleDeps.concat(deps);
  23166. } else {
  23167. moduleList.push({
  23168. name: name,
  23169. deps: deps
  23170. });
  23171. }
  23172. if (callName === 'define' && factoryIdentifier && hasProp(fnExpScope, factoryIdentifier)) {
  23173. return factoryIdentifier;
  23174. }
  23175. //If define was found, no need to dive deeper, unless
  23176. //the config explicitly wants to dig deeper.
  23177. return !!options.findNestedDependencies;
  23178. }, options);
  23179. if (options.insertNeedsDefine && needsDefine) {
  23180. result += 'require.needsDefine("' + moduleName + '");';
  23181. }
  23182. if (moduleDeps.length || moduleList.length) {
  23183. for (i = 0; i < moduleList.length; i++) {
  23184. moduleCall = moduleList[i];
  23185. if (result) {
  23186. result += '\n';
  23187. }
  23188. //If this is the main module for this file, combine any
  23189. //"anonymous" dependencies (could come from a nested require
  23190. //call) with this module.
  23191. if (moduleCall.name === moduleName) {
  23192. moduleCall.deps = moduleCall.deps.concat(moduleDeps);
  23193. moduleDeps = [];
  23194. }
  23195. depString = arrayToString(moduleCall.deps);
  23196. result += 'define("' + moduleCall.name + '",' +
  23197. depString + ');';
  23198. }
  23199. if (moduleDeps.length) {
  23200. if (result) {
  23201. result += '\n';
  23202. }
  23203. depString = arrayToString(moduleDeps);
  23204. result += 'define("' + moduleName + '",' + depString + ');';
  23205. }
  23206. }
  23207. return result || null;
  23208. }
  23209. parse.traverse = traverse;
  23210. parse.traverseBroad = traverseBroad;
  23211. parse.isFnExpression = isFnExpression;
  23212. /**
  23213. * Handles parsing a file recursively for require calls.
  23214. * @param {Array} parentNode the AST node to start with.
  23215. * @param {Function} onMatch function to call on a parse match.
  23216. * @param {Object} [options] This is normally the build config options if
  23217. * it is passed.
  23218. * @param {Object} [fnExpScope] holds list of function expresssion
  23219. * argument identifiers, set up internally, not passed in
  23220. */
  23221. parse.recurse = function (object, onMatch, options, fnExpScope) {
  23222. //Like traverse, but skips if branches that would not be processed
  23223. //after has application that results in tests of true or false boolean
  23224. //literal values.
  23225. var keys, child, result, i, params, param, tempObject,
  23226. hasHas = options && options.has;
  23227. fnExpScope = fnExpScope || emptyScope;
  23228. if (!object) {
  23229. return;
  23230. }
  23231. //If has replacement has resulted in if(true){} or if(false){}, take
  23232. //the appropriate branch and skip the other one.
  23233. if (hasHas && object.type === 'IfStatement' && object.test.type &&
  23234. object.test.type === 'Literal') {
  23235. if (object.test.value) {
  23236. //Take the if branch
  23237. this.recurse(object.consequent, onMatch, options, fnExpScope);
  23238. } else {
  23239. //Take the else branch
  23240. this.recurse(object.alternate, onMatch, options, fnExpScope);
  23241. }
  23242. } else {
  23243. result = this.parseNode(object, onMatch, fnExpScope);
  23244. if (result === false) {
  23245. return;
  23246. } else if (typeof result === 'string') {
  23247. return result;
  23248. }
  23249. //Build up a "scope" object that informs nested recurse calls if
  23250. //the define call references an identifier that is likely a UMD
  23251. //wrapped function expression argument.
  23252. //Catch (function(a) {... wrappers
  23253. if (object.type === 'ExpressionStatement' && object.expression &&
  23254. object.expression.type === 'CallExpression' && object.expression.callee &&
  23255. isFnExpression(object.expression.callee)) {
  23256. tempObject = object.expression.callee;
  23257. }
  23258. // Catch !function(a) {... wrappers
  23259. if (object.type === 'UnaryExpression' && object.argument &&
  23260. object.argument.type === 'CallExpression' && object.argument.callee &&
  23261. isFnExpression(object.argument.callee)) {
  23262. tempObject = object.argument.callee;
  23263. }
  23264. if (tempObject && tempObject.params && tempObject.params.length) {
  23265. params = tempObject.params;
  23266. fnExpScope = mixin({}, fnExpScope, true);
  23267. for (i = 0; i < params.length; i++) {
  23268. param = params[i];
  23269. if (param.type === 'Identifier') {
  23270. fnExpScope[param.name] = true;
  23271. }
  23272. }
  23273. }
  23274. for (i = 0, keys = Object.keys(object); i < keys.length; i++) {
  23275. child = object[keys[i]];
  23276. if (typeof child === 'object' && child !== null) {
  23277. result = this.recurse(child, onMatch, options, fnExpScope);
  23278. if (typeof result === 'string' && hasProp(fnExpScope, result)) {
  23279. //The result was still in fnExpScope so break. Otherwise,
  23280. //was a return from a a tree that had a UMD definition,
  23281. //but now out of that scope so keep siblings.
  23282. break;
  23283. }
  23284. }
  23285. }
  23286. //Check for an identifier for a factory function identifier being
  23287. //passed in as a function expression, indicating a UMD-type of
  23288. //wrapping.
  23289. if (typeof result === 'string') {
  23290. if (hasProp(fnExpScope, result)) {
  23291. //result still in scope, keep jumping out indicating the
  23292. //identifier still in use.
  23293. return result;
  23294. }
  23295. return;
  23296. }
  23297. }
  23298. };
  23299. /**
  23300. * Determines if the file defines the require/define module API.
  23301. * Specifically, it looks for the `define.amd = ` expression.
  23302. * @param {String} fileName
  23303. * @param {String} fileContents
  23304. * @returns {Boolean}
  23305. */
  23306. parse.definesRequire = function (fileName, fileContents) {
  23307. var foundDefine = false,
  23308. foundDefineAmd = false;
  23309. traverse(esprima.parse(fileContents), function (node) {
  23310. // Look for a top level declaration of a define, like
  23311. // var requirejs, require, define, off Program body.
  23312. if (node.type === 'Program' && node.body && node.body.length) {
  23313. foundDefine = node.body.some(function(bodyNode) {
  23314. // var define
  23315. if (bodyNode.type === 'VariableDeclaration') {
  23316. var decls = bodyNode.declarations;
  23317. if (decls) {
  23318. var hasVarDefine = decls.some(function(declNode) {
  23319. return (declNode.type === 'VariableDeclarator' &&
  23320. declNode.id &&
  23321. declNode.id.type === 'Identifier' &&
  23322. declNode.id.name === 'define');
  23323. });
  23324. if (hasVarDefine) {
  23325. return true;
  23326. }
  23327. }
  23328. }
  23329. // function define() {}
  23330. if (bodyNode.type === 'FunctionDeclaration' &&
  23331. bodyNode.id &&
  23332. bodyNode.id.type === 'Identifier' &&
  23333. bodyNode.id.name === 'define') {
  23334. return true;
  23335. }
  23336. });
  23337. }
  23338. // Need define variable found first, before detecting define.amd.
  23339. if (foundDefine && parse.hasDefineAmd(node)) {
  23340. foundDefineAmd = true;
  23341. //Stop traversal
  23342. return false;
  23343. }
  23344. });
  23345. return foundDefine && foundDefineAmd;
  23346. };
  23347. /**
  23348. * Finds require("") calls inside a CommonJS anonymous module wrapped in a
  23349. * define(function(require, exports, module){}) wrapper. These dependencies
  23350. * will be added to a modified define() call that lists the dependencies
  23351. * on the outside of the function.
  23352. * @param {String} fileName
  23353. * @param {String|Object} fileContents: a string of contents, or an already
  23354. * parsed AST tree.
  23355. * @returns {Array} an array of module names that are dependencies. Always
  23356. * returns an array, but could be of length zero.
  23357. */
  23358. parse.getAnonDeps = function (fileName, fileContents) {
  23359. var astRoot = typeof fileContents === 'string' ?
  23360. esprima.parse(fileContents) : fileContents,
  23361. defFunc = this.findAnonDefineFactory(astRoot);
  23362. return parse.getAnonDepsFromNode(defFunc);
  23363. };
  23364. /**
  23365. * Finds require("") calls inside a CommonJS anonymous module wrapped
  23366. * in a define function, given an AST node for the definition function.
  23367. * @param {Node} node the AST node for the definition function.
  23368. * @returns {Array} and array of dependency names. Can be of zero length.
  23369. */
  23370. parse.getAnonDepsFromNode = function (node) {
  23371. var deps = [],
  23372. funcArgLength;
  23373. if (node) {
  23374. this.findRequireDepNames(node, deps);
  23375. //If no deps, still add the standard CommonJS require, exports,
  23376. //module, in that order, to the deps, but only if specified as
  23377. //function args. In particular, if exports is used, it is favored
  23378. //over the return value of the function, so only add it if asked.
  23379. funcArgLength = node.params && node.params.length;
  23380. if (funcArgLength) {
  23381. deps = (funcArgLength > 1 ? ["require", "exports", "module"] :
  23382. ["require"]).concat(deps);
  23383. }
  23384. }
  23385. return deps;
  23386. };
  23387. parse.isDefineNodeWithArgs = function (node) {
  23388. return node && node.type === 'CallExpression' &&
  23389. node.callee && node.callee.type === 'Identifier' &&
  23390. node.callee.name === 'define' && node[argPropName];
  23391. };
  23392. /**
  23393. * Finds the function in define(function (require, exports, module){});
  23394. * @param {Array} node
  23395. * @returns {Boolean}
  23396. */
  23397. parse.findAnonDefineFactory = function (node) {
  23398. var match;
  23399. traverse(node, function (node) {
  23400. var arg0, arg1;
  23401. if (parse.isDefineNodeWithArgs(node)) {
  23402. //Just the factory function passed to define
  23403. arg0 = node[argPropName][0];
  23404. if (isFnExpression(arg0)) {
  23405. match = arg0;
  23406. return false;
  23407. }
  23408. //A string literal module ID followed by the factory function.
  23409. arg1 = node[argPropName][1];
  23410. if (arg0.type === 'Literal' && isFnExpression(arg1)) {
  23411. match = arg1;
  23412. return false;
  23413. }
  23414. }
  23415. });
  23416. return match;
  23417. };
  23418. /**
  23419. * Finds any config that is passed to requirejs. That includes calls to
  23420. * require/requirejs.config(), as well as require({}, ...) and
  23421. * requirejs({}, ...)
  23422. * @param {String} fileContents
  23423. *
  23424. * @returns {Object} a config details object with the following properties:
  23425. * - config: {Object} the config object found. Can be undefined if no
  23426. * config found.
  23427. * - range: {Array} the start index and end index in the contents where
  23428. * the config was found. Can be undefined if no config found.
  23429. * Can throw an error if the config in the file cannot be evaluated in
  23430. * a build context to valid JavaScript.
  23431. */
  23432. parse.findConfig = function (fileContents) {
  23433. /*jslint evil: true */
  23434. var jsConfig, foundConfig, stringData, foundRange, quote, quoteMatch,
  23435. quoteRegExp = /(:\s|\[\s*)(['"])/,
  23436. astRoot = esprima.parse(fileContents, {
  23437. loc: true
  23438. });
  23439. traverse(astRoot, function (node) {
  23440. var arg,
  23441. requireType = parse.hasRequire(node);
  23442. if (requireType && (requireType === 'require' ||
  23443. requireType === 'requirejs' ||
  23444. requireType === 'requireConfig' ||
  23445. requireType === 'requirejsConfig')) {
  23446. arg = node[argPropName] && node[argPropName][0];
  23447. if (arg && arg.type === 'ObjectExpression') {
  23448. stringData = parse.nodeToString(fileContents, arg);
  23449. jsConfig = stringData.value;
  23450. foundRange = stringData.range;
  23451. return false;
  23452. }
  23453. } else {
  23454. arg = parse.getRequireObjectLiteral(node);
  23455. if (arg) {
  23456. stringData = parse.nodeToString(fileContents, arg);
  23457. jsConfig = stringData.value;
  23458. foundRange = stringData.range;
  23459. return false;
  23460. }
  23461. }
  23462. });
  23463. if (jsConfig) {
  23464. // Eval the config
  23465. quoteMatch = quoteRegExp.exec(jsConfig);
  23466. quote = (quoteMatch && quoteMatch[2]) || '"';
  23467. foundConfig = eval('(' + jsConfig + ')');
  23468. }
  23469. return {
  23470. config: foundConfig,
  23471. range: foundRange,
  23472. quote: quote
  23473. };
  23474. };
  23475. /** Returns the node for the object literal assigned to require/requirejs,
  23476. * for holding a declarative config.
  23477. */
  23478. parse.getRequireObjectLiteral = function (node) {
  23479. if (node.id && node.id.type === 'Identifier' &&
  23480. (node.id.name === 'require' || node.id.name === 'requirejs') &&
  23481. node.init && node.init.type === 'ObjectExpression') {
  23482. return node.init;
  23483. }
  23484. };
  23485. /**
  23486. * Renames require/requirejs/define calls to be ns + '.' + require/requirejs/define
  23487. * Does *not* do .config calls though. See pragma.namespace for the complete
  23488. * set of namespace transforms. This function is used because require calls
  23489. * inside a define() call should not be renamed, so a simple regexp is not
  23490. * good enough.
  23491. * @param {String} fileContents the contents to transform.
  23492. * @param {String} ns the namespace, *not* including trailing dot.
  23493. * @return {String} the fileContents with the namespace applied
  23494. */
  23495. parse.renameNamespace = function (fileContents, ns) {
  23496. var lines,
  23497. locs = [],
  23498. astRoot = esprima.parse(fileContents, {
  23499. loc: true
  23500. });
  23501. parse.recurse(astRoot, function (callName, config, name, deps, node) {
  23502. locs.push(node.loc);
  23503. //Do not recurse into define functions, they should be using
  23504. //local defines.
  23505. return callName !== 'define';
  23506. }, {});
  23507. if (locs.length) {
  23508. lines = fileContents.split('\n');
  23509. //Go backwards through the found locs, adding in the namespace name
  23510. //in front.
  23511. locs.reverse();
  23512. locs.forEach(function (loc) {
  23513. var startIndex = loc.start.column,
  23514. //start.line is 1-based, not 0 based.
  23515. lineIndex = loc.start.line - 1,
  23516. line = lines[lineIndex];
  23517. lines[lineIndex] = line.substring(0, startIndex) +
  23518. ns + '.' +
  23519. line.substring(startIndex,
  23520. line.length);
  23521. });
  23522. fileContents = lines.join('\n');
  23523. }
  23524. return fileContents;
  23525. };
  23526. /**
  23527. * Finds all dependencies specified in dependency arrays and inside
  23528. * simplified commonjs wrappers.
  23529. * @param {String} fileName
  23530. * @param {String} fileContents
  23531. *
  23532. * @returns {Array} an array of dependency strings. The dependencies
  23533. * have not been normalized, they may be relative IDs.
  23534. */
  23535. parse.findDependencies = function (fileName, fileContents, options) {
  23536. var dependencies = [],
  23537. astRoot = esprima.parse(fileContents);
  23538. parse.recurse(astRoot, function (callName, config, name, deps) {
  23539. if (deps) {
  23540. dependencies = dependencies.concat(deps);
  23541. }
  23542. }, options);
  23543. return dependencies;
  23544. };
  23545. /**
  23546. * Finds only CJS dependencies, ones that are the form
  23547. * require('stringLiteral')
  23548. */
  23549. parse.findCjsDependencies = function (fileName, fileContents) {
  23550. var dependencies = [];
  23551. traverse(esprima.parse(fileContents), function (node) {
  23552. var arg;
  23553. if (node && node.type === 'CallExpression' && node.callee &&
  23554. node.callee.type === 'Identifier' &&
  23555. node.callee.name === 'require' && node[argPropName] &&
  23556. node[argPropName].length === 1) {
  23557. arg = node[argPropName][0];
  23558. if (arg.type === 'Literal') {
  23559. dependencies.push(arg.value);
  23560. }
  23561. }
  23562. });
  23563. return dependencies;
  23564. };
  23565. //function define() {}
  23566. parse.hasDefDefine = function (node) {
  23567. return node.type === 'FunctionDeclaration' && node.id &&
  23568. node.id.type === 'Identifier' && node.id.name === 'define';
  23569. };
  23570. //define.amd = ...
  23571. parse.hasDefineAmd = function (node) {
  23572. return node && node.type === 'AssignmentExpression' &&
  23573. node.left && node.left.type === 'MemberExpression' &&
  23574. node.left.object && node.left.object.name === 'define' &&
  23575. node.left.property && node.left.property.name === 'amd';
  23576. };
  23577. //define.amd reference, as in: if (define.amd)
  23578. parse.refsDefineAmd = function (node) {
  23579. return node && node.type === 'MemberExpression' &&
  23580. node.object && node.object.name === 'define' &&
  23581. node.object.type === 'Identifier' &&
  23582. node.property && node.property.name === 'amd' &&
  23583. node.property.type === 'Identifier';
  23584. };
  23585. //require(), requirejs(), require.config() and requirejs.config()
  23586. parse.hasRequire = function (node) {
  23587. var callName,
  23588. c = node && node.callee;
  23589. if (node && node.type === 'CallExpression' && c) {
  23590. if (c.type === 'Identifier' &&
  23591. (c.name === 'require' ||
  23592. c.name === 'requirejs')) {
  23593. //A require/requirejs({}, ...) call
  23594. callName = c.name;
  23595. } else if (c.type === 'MemberExpression' &&
  23596. c.object &&
  23597. c.object.type === 'Identifier' &&
  23598. (c.object.name === 'require' ||
  23599. c.object.name === 'requirejs') &&
  23600. c.property && c.property.name === 'config') {
  23601. // require/requirejs.config({}) call
  23602. callName = c.object.name + 'Config';
  23603. }
  23604. }
  23605. return callName;
  23606. };
  23607. //define()
  23608. parse.hasDefine = function (node) {
  23609. return node && node.type === 'CallExpression' && node.callee &&
  23610. node.callee.type === 'Identifier' &&
  23611. node.callee.name === 'define';
  23612. };
  23613. /**
  23614. * If there is a named define in the file, returns the name. Does not
  23615. * scan for mulitple names, just the first one.
  23616. */
  23617. parse.getNamedDefine = function (fileContents) {
  23618. var name;
  23619. traverse(esprima.parse(fileContents), function (node) {
  23620. if (node && node.type === 'CallExpression' && node.callee &&
  23621. node.callee.type === 'Identifier' &&
  23622. node.callee.name === 'define' &&
  23623. node[argPropName] && node[argPropName][0] &&
  23624. node[argPropName][0].type === 'Literal') {
  23625. name = node[argPropName][0].value;
  23626. return false;
  23627. }
  23628. });
  23629. return name;
  23630. };
  23631. /**
  23632. * Finds all the named define module IDs in a file.
  23633. */
  23634. parse.getAllNamedDefines = function (fileContents, excludeMap) {
  23635. var names = [];
  23636. parse.recurse(esprima.parse(fileContents),
  23637. function (callName, config, name, deps, node, factoryIdentifier, fnExpScope) {
  23638. if (callName === 'define' && name) {
  23639. if (!excludeMap.hasOwnProperty(name)) {
  23640. names.push(name);
  23641. }
  23642. }
  23643. //If a UMD definition that points to a factory that is an Identifier,
  23644. //indicate processing should not traverse inside the UMD definition.
  23645. if (callName === 'define' && factoryIdentifier && hasProp(fnExpScope, factoryIdentifier)) {
  23646. return factoryIdentifier;
  23647. }
  23648. //If define was found, no need to dive deeper, unless
  23649. //the config explicitly wants to dig deeper.
  23650. return true;
  23651. }, {});
  23652. return names;
  23653. };
  23654. /**
  23655. * Determines if define(), require({}|[]) or requirejs was called in the
  23656. * file. Also finds out if define() is declared and if define.amd is called.
  23657. */
  23658. parse.usesAmdOrRequireJs = function (fileName, fileContents) {
  23659. var uses;
  23660. traverse(esprima.parse(fileContents), function (node) {
  23661. var type, callName, arg;
  23662. if (parse.hasDefDefine(node)) {
  23663. //function define() {}
  23664. type = 'declaresDefine';
  23665. } else if (parse.hasDefineAmd(node)) {
  23666. type = 'defineAmd';
  23667. } else {
  23668. callName = parse.hasRequire(node);
  23669. if (callName) {
  23670. arg = node[argPropName] && node[argPropName][0];
  23671. if (arg && (arg.type === 'ObjectExpression' ||
  23672. arg.type === 'ArrayExpression')) {
  23673. type = callName;
  23674. }
  23675. } else if (parse.hasDefine(node)) {
  23676. type = 'define';
  23677. }
  23678. }
  23679. if (type) {
  23680. if (!uses) {
  23681. uses = {};
  23682. }
  23683. uses[type] = true;
  23684. }
  23685. });
  23686. return uses;
  23687. };
  23688. /**
  23689. * Determines if require(''), exports.x =, module.exports =,
  23690. * __dirname, __filename are used. So, not strictly traditional CommonJS,
  23691. * also checks for Node variants.
  23692. */
  23693. parse.usesCommonJs = function (fileName, fileContents) {
  23694. var uses = null,
  23695. assignsExports = false;
  23696. traverse(esprima.parse(fileContents), function (node) {
  23697. var type,
  23698. exp = node.expression || node.init;
  23699. if (node.type === 'Identifier' &&
  23700. (node.name === '__dirname' || node.name === '__filename')) {
  23701. type = node.name.substring(2);
  23702. } else if (node.type === 'VariableDeclarator' && node.id &&
  23703. node.id.type === 'Identifier' &&
  23704. node.id.name === 'exports') {
  23705. //Hmm, a variable assignment for exports, so does not use cjs
  23706. //exports.
  23707. type = 'varExports';
  23708. } else if (exp && exp.type === 'AssignmentExpression' && exp.left &&
  23709. exp.left.type === 'MemberExpression' && exp.left.object) {
  23710. if (exp.left.object.name === 'module' && exp.left.property &&
  23711. exp.left.property.name === 'exports') {
  23712. type = 'moduleExports';
  23713. } else if (exp.left.object.name === 'exports' &&
  23714. exp.left.property) {
  23715. type = 'exports';
  23716. } else if (exp.left.object.type === 'MemberExpression' &&
  23717. exp.left.object.object.name === 'module' &&
  23718. exp.left.object.property.name === 'exports' &&
  23719. exp.left.object.property.type === 'Identifier') {
  23720. type = 'moduleExports';
  23721. }
  23722. } else if (node && node.type === 'CallExpression' && node.callee &&
  23723. node.callee.type === 'Identifier' &&
  23724. node.callee.name === 'require' && node[argPropName] &&
  23725. node[argPropName].length === 1 &&
  23726. node[argPropName][0].type === 'Literal') {
  23727. type = 'require';
  23728. }
  23729. if (type) {
  23730. if (type === 'varExports') {
  23731. assignsExports = true;
  23732. } else if (type !== 'exports' || !assignsExports) {
  23733. if (!uses) {
  23734. uses = {};
  23735. }
  23736. uses[type] = true;
  23737. }
  23738. }
  23739. });
  23740. return uses;
  23741. };
  23742. parse.findRequireDepNames = function (node, deps) {
  23743. traverse(node, function (node) {
  23744. var arg;
  23745. if (node && node.type === 'CallExpression' && node.callee &&
  23746. node.callee.type === 'Identifier' &&
  23747. node.callee.name === 'require' &&
  23748. node[argPropName] && node[argPropName].length === 1) {
  23749. arg = node[argPropName][0];
  23750. if (arg.type === 'Literal') {
  23751. deps.push(arg.value);
  23752. }
  23753. }
  23754. });
  23755. };
  23756. /**
  23757. * Determines if a specific node is a valid require or define/require.def
  23758. * call.
  23759. * @param {Array} node
  23760. * @param {Function} onMatch a function to call when a match is found.
  23761. * It is passed the match name, and the config, name, deps possible args.
  23762. * The config, name and deps args are not normalized.
  23763. * @param {Object} fnExpScope an object whose keys are all function
  23764. * expression identifiers that should be in scope. Useful for UMD wrapper
  23765. * detection to avoid parsing more into the wrapped UMD code.
  23766. *
  23767. * @returns {String} a JS source string with the valid require/define call.
  23768. * Otherwise null.
  23769. */
  23770. parse.parseNode = function (node, onMatch, fnExpScope) {
  23771. var name, deps, cjsDeps, arg, factory, exp, refsDefine, bodyNode,
  23772. args = node && node[argPropName],
  23773. callName = parse.hasRequire(node),
  23774. isUmd = false;
  23775. if (callName === 'require' || callName === 'requirejs') {
  23776. //A plain require/requirejs call
  23777. arg = node[argPropName] && node[argPropName][0];
  23778. if (arg && arg.type !== 'ArrayExpression') {
  23779. if (arg.type === 'ObjectExpression') {
  23780. //A config call, try the second arg.
  23781. arg = node[argPropName][1];
  23782. }
  23783. }
  23784. deps = getValidDeps(arg);
  23785. if (!deps) {
  23786. return;
  23787. }
  23788. return onMatch("require", null, null, deps, node);
  23789. } else if (parse.hasDefine(node) && args && args.length) {
  23790. name = args[0];
  23791. deps = args[1];
  23792. factory = args[2];
  23793. if (name.type === 'ArrayExpression') {
  23794. //No name, adjust args
  23795. factory = deps;
  23796. deps = name;
  23797. name = null;
  23798. } else if (isFnExpression(name)) {
  23799. //Just the factory, no name or deps
  23800. factory = name;
  23801. name = deps = null;
  23802. } else if (name.type === 'Identifier' && args.length === 1 &&
  23803. hasProp(fnExpScope, name.name)) {
  23804. //define(e) where e is a UMD identifier for the factory
  23805. //function.
  23806. isUmd = true;
  23807. factory = name;
  23808. name = null;
  23809. } else if (name.type !== 'Literal') {
  23810. //An object literal, just null out
  23811. name = deps = factory = null;
  23812. }
  23813. if (name && name.type === 'Literal' && deps) {
  23814. if (isFnExpression(deps)) {
  23815. //deps is the factory
  23816. factory = deps;
  23817. deps = null;
  23818. } else if (deps.type === 'ObjectExpression') {
  23819. //deps is object literal, null out
  23820. deps = factory = null;
  23821. } else if (deps.type === 'Identifier') {
  23822. if (args.length === 2) {
  23823. //define('id', factory)
  23824. deps = factory = null;
  23825. } else if (args.length === 3 && isFnExpression(factory)) {
  23826. //define('id', depsIdentifier, factory)
  23827. //Since identifier, cannot know the deps, but do not
  23828. //error out, assume they are taken care of outside of
  23829. //static parsing.
  23830. deps = null;
  23831. }
  23832. }
  23833. }
  23834. if (deps && deps.type === 'ArrayExpression') {
  23835. deps = getValidDeps(deps);
  23836. } else if (isFnExpression(factory)) {
  23837. //If no deps and a factory function, could be a commonjs sugar
  23838. //wrapper, scan the function for dependencies.
  23839. cjsDeps = parse.getAnonDepsFromNode(factory);
  23840. if (cjsDeps.length) {
  23841. deps = cjsDeps;
  23842. }
  23843. } else if (deps || (factory && !isUmd)) {
  23844. //Does not match the shape of an AMD call.
  23845. return;
  23846. }
  23847. //Just save off the name as a string instead of an AST object.
  23848. if (name && name.type === 'Literal') {
  23849. name = name.value;
  23850. }
  23851. return onMatch("define", null, name, deps, node,
  23852. (factory && factory.type === 'Identifier' ? factory.name : undefined),
  23853. fnExpScope);
  23854. } else if (node.type === 'CallExpression' && node.callee &&
  23855. isFnExpression(node.callee) &&
  23856. node.callee.body && node.callee.body.body &&
  23857. node.callee.body.body.length === 1 &&
  23858. node.callee.body.body[0].type === 'IfStatement') {
  23859. bodyNode = node.callee.body.body[0];
  23860. //Look for a define(Identifier) case, but only if inside an
  23861. //if that has a define.amd test
  23862. if (bodyNode.consequent && bodyNode.consequent.body) {
  23863. exp = bodyNode.consequent.body[0];
  23864. if (exp.type === 'ExpressionStatement' && exp.expression &&
  23865. parse.hasDefine(exp.expression) &&
  23866. exp.expression.arguments &&
  23867. exp.expression.arguments.length === 1 &&
  23868. exp.expression.arguments[0].type === 'Identifier') {
  23869. //Calls define(Identifier) as first statement in body.
  23870. //Confirm the if test references define.amd
  23871. traverse(bodyNode.test, function (node) {
  23872. if (parse.refsDefineAmd(node)) {
  23873. refsDefine = true;
  23874. return false;
  23875. }
  23876. });
  23877. if (refsDefine) {
  23878. return onMatch("define", null, null, null, exp.expression,
  23879. exp.expression.arguments[0].name, fnExpScope);
  23880. }
  23881. }
  23882. }
  23883. }
  23884. };
  23885. /**
  23886. * Converts an AST node into a JS source string by extracting
  23887. * the node's location from the given contents string. Assumes
  23888. * esprima.parse() with loc was done.
  23889. * @param {String} contents
  23890. * @param {Object} node
  23891. * @returns {String} a JS source string.
  23892. */
  23893. parse.nodeToString = function (contents, node) {
  23894. var extracted,
  23895. loc = node.loc,
  23896. lines = contents.split('\n'),
  23897. firstLine = loc.start.line > 1 ?
  23898. lines.slice(0, loc.start.line - 1).join('\n') + '\n' :
  23899. '',
  23900. preamble = firstLine +
  23901. lines[loc.start.line - 1].substring(0, loc.start.column);
  23902. if (loc.start.line === loc.end.line) {
  23903. extracted = lines[loc.start.line - 1].substring(loc.start.column,
  23904. loc.end.column);
  23905. } else {
  23906. extracted = lines[loc.start.line - 1].substring(loc.start.column) +
  23907. '\n' +
  23908. lines.slice(loc.start.line, loc.end.line - 1).join('\n') +
  23909. '\n' +
  23910. lines[loc.end.line - 1].substring(0, loc.end.column);
  23911. }
  23912. return {
  23913. value: extracted,
  23914. range: [
  23915. preamble.length,
  23916. preamble.length + extracted.length
  23917. ]
  23918. };
  23919. };
  23920. /**
  23921. * Extracts license comments from JS text.
  23922. * @param {String} fileName
  23923. * @param {String} contents
  23924. * @returns {String} a string of license comments.
  23925. */
  23926. parse.getLicenseComments = function (fileName, contents) {
  23927. var commentNode, refNode, subNode, value, i, j,
  23928. //xpconnect's Reflect does not support comment or range, but
  23929. //prefer continued operation vs strict parity of operation,
  23930. //as license comments can be expressed in other ways, like
  23931. //via wrap args, or linked via sourcemaps.
  23932. ast = esprima.parse(contents, {
  23933. comment: true,
  23934. range: true
  23935. }),
  23936. result = '',
  23937. existsMap = {},
  23938. lineEnd = contents.indexOf('\r') === -1 ? '\n' : '\r\n';
  23939. if (ast.comments) {
  23940. for (i = 0; i < ast.comments.length; i++) {
  23941. commentNode = ast.comments[i];
  23942. if (commentNode.type === 'Line') {
  23943. value = '//' + commentNode.value + lineEnd;
  23944. refNode = commentNode;
  23945. if (i + 1 >= ast.comments.length) {
  23946. value += lineEnd;
  23947. } else {
  23948. //Look for immediately adjacent single line comments
  23949. //since it could from a multiple line comment made out
  23950. //of single line comments. Like this comment.
  23951. for (j = i + 1; j < ast.comments.length; j++) {
  23952. subNode = ast.comments[j];
  23953. if (subNode.type === 'Line' &&
  23954. subNode.range[0] === refNode.range[1] + 1) {
  23955. //Adjacent single line comment. Collect it.
  23956. value += '//' + subNode.value + lineEnd;
  23957. refNode = subNode;
  23958. } else {
  23959. //No more single line comment blocks. Break out
  23960. //and continue outer looping.
  23961. break;
  23962. }
  23963. }
  23964. value += lineEnd;
  23965. i = j - 1;
  23966. }
  23967. } else {
  23968. value = '/*' + commentNode.value + '*/' + lineEnd + lineEnd;
  23969. }
  23970. if (!existsMap[value] && (value.indexOf('license') !== -1 ||
  23971. (commentNode.type === 'Block' &&
  23972. value.indexOf('/*!') === 0) ||
  23973. value.indexOf('opyright') !== -1 ||
  23974. value.indexOf('(c)') !== -1)) {
  23975. result += value;
  23976. existsMap[value] = true;
  23977. }
  23978. }
  23979. }
  23980. return result;
  23981. };
  23982. return parse;
  23983. });
  23984. /*global define */
  23985. define('transform', [ './esprimaAdapter', './parse', 'logger', 'lang'],
  23986. function (esprima, parse, logger, lang) {
  23987. 'use strict';
  23988. var transform,
  23989. baseIndentRegExp = /^([ \t]+)/,
  23990. indentRegExp = /\{[\r\n]+([ \t]+)/,
  23991. keyRegExp = /^[_A-Za-z]([A-Za-z\d_]*)$/,
  23992. bulkIndentRegExps = {
  23993. '\n': /\n/g,
  23994. '\r\n': /\r\n/g
  23995. };
  23996. function applyIndent(str, indent, lineReturn) {
  23997. var regExp = bulkIndentRegExps[lineReturn];
  23998. return str.replace(regExp, '$&' + indent);
  23999. }
  24000. transform = {
  24001. toTransport: function (namespace, moduleName, path, contents, onFound, options) {
  24002. options = options || {};
  24003. var astRoot, contentLines, modLine,
  24004. foundAnon,
  24005. scanCount = 0,
  24006. scanReset = false,
  24007. defineInfos = [],
  24008. applySourceUrl = function (contents) {
  24009. if (options.useSourceUrl) {
  24010. contents = 'eval("' + lang.jsEscape(contents) +
  24011. '\\n//# sourceURL=' + (path.indexOf('/') === 0 ? '' : '/') +
  24012. path +
  24013. '");\n';
  24014. }
  24015. return contents;
  24016. };
  24017. try {
  24018. astRoot = esprima.parse(contents, {
  24019. loc: true
  24020. });
  24021. } catch (e) {
  24022. logger.trace('toTransport skipping ' + path + ': ' +
  24023. e.toString());
  24024. return contents;
  24025. }
  24026. //Find the define calls and their position in the files.
  24027. parse.traverse(astRoot, function (node) {
  24028. var args, firstArg, firstArgLoc, factoryNode,
  24029. needsId, depAction, foundId, init,
  24030. sourceUrlData, range,
  24031. namespaceExists = false;
  24032. // If a bundle script with a define declaration, do not
  24033. // parse any further at this level. Likely a built layer
  24034. // by some other tool.
  24035. if (node.type === 'VariableDeclarator' &&
  24036. node.id && node.id.name === 'define' &&
  24037. node.id.type === 'Identifier') {
  24038. init = node.init;
  24039. if (init && init.callee &&
  24040. init.callee.type === 'CallExpression' &&
  24041. init.callee.callee &&
  24042. init.callee.callee.type === 'Identifier' &&
  24043. init.callee.callee.name === 'require' &&
  24044. init.callee.arguments && init.callee.arguments.length === 1 &&
  24045. init.callee.arguments[0].type === 'Literal' &&
  24046. init.callee.arguments[0].value &&
  24047. init.callee.arguments[0].value.indexOf('amdefine') !== -1) {
  24048. // the var define = require('amdefine')(module) case,
  24049. // keep going in that case.
  24050. } else {
  24051. return false;
  24052. }
  24053. }
  24054. namespaceExists = namespace &&
  24055. node.type === 'CallExpression' &&
  24056. node.callee && node.callee.object &&
  24057. node.callee.object.type === 'Identifier' &&
  24058. node.callee.object.name === namespace &&
  24059. node.callee.property.type === 'Identifier' &&
  24060. node.callee.property.name === 'define';
  24061. if (namespaceExists || parse.isDefineNodeWithArgs(node)) {
  24062. //The arguments are where its at.
  24063. args = node.arguments;
  24064. if (!args || !args.length) {
  24065. return;
  24066. }
  24067. firstArg = args[0];
  24068. firstArgLoc = firstArg.loc;
  24069. if (args.length === 1) {
  24070. if (firstArg.type === 'Identifier') {
  24071. //The define(factory) case, but
  24072. //only allow it if one Identifier arg,
  24073. //to limit impact of false positives.
  24074. needsId = true;
  24075. depAction = 'empty';
  24076. } else if (parse.isFnExpression(firstArg)) {
  24077. //define(function(){})
  24078. factoryNode = firstArg;
  24079. needsId = true;
  24080. depAction = 'scan';
  24081. } else if (firstArg.type === 'ObjectExpression') {
  24082. //define({});
  24083. needsId = true;
  24084. depAction = 'skip';
  24085. } else if (firstArg.type === 'Literal' &&
  24086. typeof firstArg.value === 'number') {
  24087. //define('12345');
  24088. needsId = true;
  24089. depAction = 'skip';
  24090. } else if (firstArg.type === 'UnaryExpression' &&
  24091. firstArg.operator === '-' &&
  24092. firstArg.argument &&
  24093. firstArg.argument.type === 'Literal' &&
  24094. typeof firstArg.argument.value === 'number') {
  24095. //define('-12345');
  24096. needsId = true;
  24097. depAction = 'skip';
  24098. } else if (firstArg.type === 'MemberExpression' &&
  24099. firstArg.object &&
  24100. firstArg.property &&
  24101. firstArg.property.type === 'Identifier') {
  24102. //define(this.key);
  24103. needsId = true;
  24104. depAction = 'empty';
  24105. }
  24106. } else if (firstArg.type === 'ArrayExpression') {
  24107. //define([], ...);
  24108. needsId = true;
  24109. depAction = 'skip';
  24110. } else if (firstArg.type === 'Literal' &&
  24111. typeof firstArg.value === 'string') {
  24112. //define('string', ....)
  24113. //Already has an ID.
  24114. needsId = false;
  24115. if (args.length === 2 &&
  24116. parse.isFnExpression(args[1])) {
  24117. //Needs dependency scanning.
  24118. factoryNode = args[1];
  24119. depAction = 'scan';
  24120. } else {
  24121. depAction = 'skip';
  24122. }
  24123. } else {
  24124. //Unknown define entity, keep looking, even
  24125. //in the subtree for this node.
  24126. return;
  24127. }
  24128. range = {
  24129. foundId: foundId,
  24130. needsId: needsId,
  24131. depAction: depAction,
  24132. namespaceExists: namespaceExists,
  24133. node: node,
  24134. defineLoc: node.loc,
  24135. firstArgLoc: firstArgLoc,
  24136. factoryNode: factoryNode,
  24137. sourceUrlData: sourceUrlData
  24138. };
  24139. //Only transform ones that do not have IDs. If it has an
  24140. //ID but no dependency array, assume it is something like
  24141. //a phonegap implementation, that has its own internal
  24142. //define that cannot handle dependency array constructs,
  24143. //and if it is a named module, then it means it has been
  24144. //set for transport form.
  24145. if (range.needsId) {
  24146. if (foundAnon) {
  24147. logger.trace(path + ' has more than one anonymous ' +
  24148. 'define. May be a built file from another ' +
  24149. 'build system like, Ender. Skipping normalization.');
  24150. defineInfos = [];
  24151. return false;
  24152. } else {
  24153. foundAnon = range;
  24154. defineInfos.push(range);
  24155. }
  24156. } else if (depAction === 'scan') {
  24157. scanCount += 1;
  24158. if (scanCount > 1) {
  24159. //Just go back to an array that just has the
  24160. //anon one, since this is an already optimized
  24161. //file like the phonegap one.
  24162. if (!scanReset) {
  24163. defineInfos = foundAnon ? [foundAnon] : [];
  24164. scanReset = true;
  24165. }
  24166. } else {
  24167. defineInfos.push(range);
  24168. }
  24169. }
  24170. }
  24171. });
  24172. if (!defineInfos.length) {
  24173. return applySourceUrl(contents);
  24174. }
  24175. //Reverse the matches, need to start from the bottom of
  24176. //the file to modify it, so that the ranges are still true
  24177. //further up.
  24178. defineInfos.reverse();
  24179. contentLines = contents.split('\n');
  24180. modLine = function (loc, contentInsertion) {
  24181. var startIndex = loc.start.column,
  24182. //start.line is 1-based, not 0 based.
  24183. lineIndex = loc.start.line - 1,
  24184. line = contentLines[lineIndex];
  24185. contentLines[lineIndex] = line.substring(0, startIndex) +
  24186. contentInsertion +
  24187. line.substring(startIndex,
  24188. line.length);
  24189. };
  24190. defineInfos.forEach(function (info) {
  24191. var deps,
  24192. contentInsertion = '',
  24193. depString = '';
  24194. //Do the modifications "backwards", in other words, start with the
  24195. //one that is farthest down and work up, so that the ranges in the
  24196. //defineInfos still apply. So that means deps, id, then namespace.
  24197. if (info.needsId && moduleName) {
  24198. contentInsertion += "'" + moduleName + "',";
  24199. }
  24200. if (info.depAction === 'scan') {
  24201. deps = parse.getAnonDepsFromNode(info.factoryNode);
  24202. if (deps.length) {
  24203. depString = '[' + deps.map(function (dep) {
  24204. return "'" + dep + "'";
  24205. }) + ']';
  24206. } else {
  24207. depString = '[]';
  24208. }
  24209. depString += ',';
  24210. if (info.factoryNode) {
  24211. //Already have a named module, need to insert the
  24212. //dependencies after the name.
  24213. modLine(info.factoryNode.loc, depString);
  24214. } else {
  24215. contentInsertion += depString;
  24216. }
  24217. }
  24218. if (contentInsertion) {
  24219. modLine(info.firstArgLoc, contentInsertion);
  24220. }
  24221. //Do namespace last so that ui does not mess upthe parenRange
  24222. //used above.
  24223. if (namespace && !info.namespaceExists) {
  24224. modLine(info.defineLoc, namespace + '.');
  24225. }
  24226. //Notify any listener for the found info
  24227. if (onFound) {
  24228. onFound(info);
  24229. }
  24230. });
  24231. contents = contentLines.join('\n');
  24232. return applySourceUrl(contents);
  24233. },
  24234. /**
  24235. * Modify the contents of a require.config/requirejs.config call. This
  24236. * call will LOSE any existing comments that are in the config string.
  24237. *
  24238. * @param {String} fileContents String that may contain a config call
  24239. * @param {Function} onConfig Function called when the first config
  24240. * call is found. It will be passed an Object which is the current
  24241. * config, and the onConfig function should return an Object to use
  24242. * as the config.
  24243. * @return {String} the fileContents with the config changes applied.
  24244. */
  24245. modifyConfig: function (fileContents, onConfig) {
  24246. var details = parse.findConfig(fileContents),
  24247. config = details.config;
  24248. if (config) {
  24249. config = onConfig(config);
  24250. if (config) {
  24251. return transform.serializeConfig(config,
  24252. fileContents,
  24253. details.range[0],
  24254. details.range[1],
  24255. {
  24256. quote: details.quote
  24257. });
  24258. }
  24259. }
  24260. return fileContents;
  24261. },
  24262. serializeConfig: function (config, fileContents, start, end, options) {
  24263. //Calculate base level of indent
  24264. var indent, match, configString, outDentRegExp,
  24265. baseIndent = '',
  24266. startString = fileContents.substring(0, start),
  24267. existingConfigString = fileContents.substring(start, end),
  24268. lineReturn = existingConfigString.indexOf('\r') === -1 ? '\n' : '\r\n',
  24269. lastReturnIndex = startString.lastIndexOf('\n');
  24270. //Get the basic amount of indent for the require config call.
  24271. if (lastReturnIndex === -1) {
  24272. lastReturnIndex = 0;
  24273. }
  24274. match = baseIndentRegExp.exec(startString.substring(lastReturnIndex + 1, start));
  24275. if (match && match[1]) {
  24276. baseIndent = match[1];
  24277. }
  24278. //Calculate internal indentation for config
  24279. match = indentRegExp.exec(existingConfigString);
  24280. if (match && match[1]) {
  24281. indent = match[1];
  24282. }
  24283. if (!indent || indent.length < baseIndent) {
  24284. indent = ' ';
  24285. } else {
  24286. indent = indent.substring(baseIndent.length);
  24287. }
  24288. outDentRegExp = new RegExp('(' + lineReturn + ')' + indent, 'g');
  24289. configString = transform.objectToString(config, {
  24290. indent: indent,
  24291. lineReturn: lineReturn,
  24292. outDentRegExp: outDentRegExp,
  24293. quote: options && options.quote
  24294. });
  24295. //Add in the base indenting level.
  24296. configString = applyIndent(configString, baseIndent, lineReturn);
  24297. return startString + configString + fileContents.substring(end);
  24298. },
  24299. /**
  24300. * Tries converting a JS object to a string. This will likely suck, and
  24301. * is tailored to the type of config expected in a loader config call.
  24302. * So, hasOwnProperty fields, strings, numbers, arrays and functions,
  24303. * no weird recursively referenced stuff.
  24304. * @param {Object} obj the object to convert
  24305. * @param {Object} options options object with the following values:
  24306. * {String} indent the indentation to use for each level
  24307. * {String} lineReturn the type of line return to use
  24308. * {outDentRegExp} outDentRegExp the regexp to use to outdent functions
  24309. * {String} quote the quote type to use, ' or ". Optional. Default is "
  24310. * @param {String} totalIndent the total indent to print for this level
  24311. * @return {String} a string representation of the object.
  24312. */
  24313. objectToString: function (obj, options, totalIndent) {
  24314. var startBrace, endBrace, nextIndent,
  24315. first = true,
  24316. value = '',
  24317. lineReturn = options.lineReturn,
  24318. indent = options.indent,
  24319. outDentRegExp = options.outDentRegExp,
  24320. quote = options.quote || '"';
  24321. totalIndent = totalIndent || '';
  24322. nextIndent = totalIndent + indent;
  24323. if (obj === null) {
  24324. value = 'null';
  24325. } else if (obj === undefined) {
  24326. value = 'undefined';
  24327. } else if (typeof obj === 'number' || typeof obj === 'boolean') {
  24328. value = obj;
  24329. } else if (typeof obj === 'string') {
  24330. //Use double quotes in case the config may also work as JSON.
  24331. value = quote + lang.jsEscape(obj) + quote;
  24332. } else if (lang.isArray(obj)) {
  24333. lang.each(obj, function (item, i) {
  24334. value += (i !== 0 ? ',' + lineReturn : '' ) +
  24335. nextIndent +
  24336. transform.objectToString(item,
  24337. options,
  24338. nextIndent);
  24339. });
  24340. startBrace = '[';
  24341. endBrace = ']';
  24342. } else if (lang.isFunction(obj) || lang.isRegExp(obj)) {
  24343. //The outdent regexp just helps pretty up the conversion
  24344. //just in node. Rhino strips comments and does a different
  24345. //indent scheme for Function toString, so not really helpful
  24346. //there.
  24347. value = obj.toString().replace(outDentRegExp, '$1');
  24348. } else {
  24349. //An object
  24350. lang.eachProp(obj, function (v, prop) {
  24351. value += (first ? '': ',' + lineReturn) +
  24352. nextIndent +
  24353. (keyRegExp.test(prop) ? prop : quote + lang.jsEscape(prop) + quote )+
  24354. ': ' +
  24355. transform.objectToString(v,
  24356. options,
  24357. nextIndent);
  24358. first = false;
  24359. });
  24360. startBrace = '{';
  24361. endBrace = '}';
  24362. }
  24363. if (startBrace) {
  24364. value = startBrace +
  24365. lineReturn +
  24366. value +
  24367. lineReturn + totalIndent +
  24368. endBrace;
  24369. }
  24370. return value;
  24371. }
  24372. };
  24373. return transform;
  24374. });
  24375. /*jslint regexp: true, plusplus: true */
  24376. /*global define: false */
  24377. define('pragma', ['parse', 'logger'], function (parse, logger) {
  24378. 'use strict';
  24379. function Temp() {}
  24380. function create(obj, mixin) {
  24381. Temp.prototype = obj;
  24382. var temp = new Temp(), prop;
  24383. //Avoid any extra memory hanging around
  24384. Temp.prototype = null;
  24385. if (mixin) {
  24386. for (prop in mixin) {
  24387. if (mixin.hasOwnProperty(prop) && !temp.hasOwnProperty(prop)) {
  24388. temp[prop] = mixin[prop];
  24389. }
  24390. }
  24391. }
  24392. return temp; // Object
  24393. }
  24394. var pragma = {
  24395. conditionalRegExp: /(exclude|include)Start\s*\(\s*["'](\w+)["']\s*,(.*)\)/,
  24396. useStrictRegExp: /(^|[^{]\r?\n)['"]use strict['"];/g,
  24397. hasRegExp: /has\s*\(\s*['"]([^'"]+)['"]\s*\)/g,
  24398. configRegExp: /(^|[^\.])(requirejs|require)(\.config)\s*\(/g,
  24399. nsWrapRegExp: /\/\*requirejs namespace: true \*\//,
  24400. apiDefRegExp: /var requirejs,\s*require,\s*define;/,
  24401. defineCheckRegExp: /typeof(\s+|\s*\(\s*)define(\s*\))?\s*===?\s*["']function["']\s*&&\s*define\s*\.\s*amd/g,
  24402. defineStringCheckRegExp: /typeof\s+define\s*===?\s*["']function["']\s*&&\s*define\s*\[\s*["']amd["']\s*\]/g,
  24403. defineTypeFirstCheckRegExp: /\s*["']function["']\s*==(=?)\s*typeof\s+define\s*&&\s*define\s*\.\s*amd/g,
  24404. defineJQueryRegExp: /typeof\s+define\s*===?\s*["']function["']\s*&&\s*define\s*\.\s*amd\s*&&\s*define\s*\.\s*amd\s*\.\s*jQuery/g,
  24405. defineHasRegExp: /typeof\s+define\s*==(=)?\s*['"]function['"]\s*&&\s*typeof\s+define\.amd\s*==(=)?\s*['"]object['"]\s*&&\s*define\.amd/g,
  24406. defineTernaryRegExp: /typeof\s+define\s*===?\s*['"]function["']\s*&&\s*define\s*\.\s*amd\s*\?\s*define/,
  24407. defineExistsRegExp: /\s+typeof\s+define\s*!==?\s*['"]undefined["']\s*/,
  24408. defineExistsAndAmdRegExp: /typeof\s+define\s*!==?\s*['"]undefined["']\s*&&\s*define\s*\.\s*amd\s*/,
  24409. amdefineRegExp: /if\s*\(\s*typeof define\s*\!==\s*['"]function['"]\s*\)\s*\{\s*[^\{\}]+amdefine[^\{\}]+\}/g,
  24410. removeStrict: function (contents, config) {
  24411. return config.useStrict ? contents : contents.replace(pragma.useStrictRegExp, '$1');
  24412. },
  24413. namespace: function (fileContents, ns, onLifecycleName) {
  24414. if (ns) {
  24415. //Namespace require/define calls
  24416. fileContents = fileContents.replace(pragma.configRegExp, '$1' + ns + '.$2$3(');
  24417. fileContents = parse.renameNamespace(fileContents, ns);
  24418. //Namespace define ternary use:
  24419. fileContents = fileContents.replace(pragma.defineTernaryRegExp,
  24420. "typeof " + ns + ".define === 'function' && " + ns + ".define.amd ? " + ns + ".define");
  24421. //Namespace define jquery use:
  24422. fileContents = fileContents.replace(pragma.defineJQueryRegExp,
  24423. "typeof " + ns + ".define === 'function' && " + ns + ".define.amd && " + ns + ".define.amd.jQuery");
  24424. //Namespace has.js define use:
  24425. fileContents = fileContents.replace(pragma.defineHasRegExp,
  24426. "typeof " + ns + ".define === 'function' && typeof " + ns + ".define.amd === 'object' && " + ns + ".define.amd");
  24427. //Namespace async.js define use:
  24428. fileContents = fileContents.replace(pragma.defineExistsAndAmdRegExp,
  24429. "typeof " + ns + ".define !== 'undefined' && " + ns + ".define.amd");
  24430. //Namespace define checks.
  24431. //Do these ones last, since they are a subset of the more specific
  24432. //checks above.
  24433. fileContents = fileContents.replace(pragma.defineCheckRegExp,
  24434. "typeof " + ns + ".define === 'function' && " + ns + ".define.amd");
  24435. fileContents = fileContents.replace(pragma.defineStringCheckRegExp,
  24436. "typeof " + ns + ".define === 'function' && " + ns + ".define['amd']");
  24437. fileContents = fileContents.replace(pragma.defineTypeFirstCheckRegExp,
  24438. "'function' === typeof " + ns + ".define && " + ns + ".define.amd");
  24439. fileContents = fileContents.replace(pragma.defineExistsRegExp,
  24440. "typeof " + ns + ".define !== 'undefined'");
  24441. //Check for require.js with the require/define definitions
  24442. if (pragma.apiDefRegExp.test(fileContents) &&
  24443. fileContents.indexOf("if (!" + ns + " || !" + ns + ".requirejs)") === -1) {
  24444. //Wrap the file contents in a typeof check, and a function
  24445. //to contain the API globals.
  24446. fileContents = "var " + ns + ";(function () { if (!" + ns + " || !" + ns + ".requirejs) {\n" +
  24447. "if (!" + ns + ") { " + ns + ' = {}; } else { require = ' + ns + '; }\n' +
  24448. fileContents +
  24449. "\n" +
  24450. ns + ".requirejs = requirejs;" +
  24451. ns + ".require = require;" +
  24452. ns + ".define = define;\n" +
  24453. "}\n}());";
  24454. }
  24455. //Finally, if the file wants a special wrapper because it ties
  24456. //in to the requirejs internals in a way that would not fit
  24457. //the above matches, do that. Look for /*requirejs namespace: true*/
  24458. if (pragma.nsWrapRegExp.test(fileContents)) {
  24459. //Remove the pragma.
  24460. fileContents = fileContents.replace(pragma.nsWrapRegExp, '');
  24461. //Alter the contents.
  24462. fileContents = '(function () {\n' +
  24463. 'var require = ' + ns + '.require,' +
  24464. 'requirejs = ' + ns + '.requirejs,' +
  24465. 'define = ' + ns + '.define;\n' +
  24466. fileContents +
  24467. '\n}());';
  24468. }
  24469. }
  24470. return fileContents;
  24471. },
  24472. /**
  24473. * processes the fileContents for some //>> conditional statements
  24474. */
  24475. process: function (fileName, fileContents, config, onLifecycleName, pluginCollector) {
  24476. /*jslint evil: true */
  24477. var foundIndex = -1, startIndex = 0, lineEndIndex, conditionLine,
  24478. matches, type, marker, condition, isTrue, endRegExp, endMatches,
  24479. endMarkerIndex, shouldInclude, startLength, lifecycleHas, deps,
  24480. i, dep, moduleName, collectorMod,
  24481. lifecyclePragmas, pragmas = config.pragmas, hasConfig = config.has,
  24482. //Legacy arg defined to help in dojo conversion script. Remove later
  24483. //when dojo no longer needs conversion:
  24484. kwArgs = pragmas;
  24485. //Mix in a specific lifecycle scoped object, to allow targeting
  24486. //some pragmas/has tests to only when files are saved, or at different
  24487. //lifecycle events. Do not bother with kwArgs in this section, since
  24488. //the old dojo kwArgs were for all points in the build lifecycle.
  24489. if (onLifecycleName) {
  24490. lifecyclePragmas = config['pragmas' + onLifecycleName];
  24491. lifecycleHas = config['has' + onLifecycleName];
  24492. if (lifecyclePragmas) {
  24493. pragmas = create(pragmas || {}, lifecyclePragmas);
  24494. }
  24495. if (lifecycleHas) {
  24496. hasConfig = create(hasConfig || {}, lifecycleHas);
  24497. }
  24498. }
  24499. //Replace has references if desired
  24500. if (hasConfig) {
  24501. fileContents = fileContents.replace(pragma.hasRegExp, function (match, test) {
  24502. if (hasConfig.hasOwnProperty(test)) {
  24503. return !!hasConfig[test];
  24504. }
  24505. return match;
  24506. });
  24507. }
  24508. if (!config.skipPragmas) {
  24509. while ((foundIndex = fileContents.indexOf("//>>", startIndex)) !== -1) {
  24510. //Found a conditional. Get the conditional line.
  24511. lineEndIndex = fileContents.indexOf("\n", foundIndex);
  24512. if (lineEndIndex === -1) {
  24513. lineEndIndex = fileContents.length - 1;
  24514. }
  24515. //Increment startIndex past the line so the next conditional search can be done.
  24516. startIndex = lineEndIndex + 1;
  24517. //Break apart the conditional.
  24518. conditionLine = fileContents.substring(foundIndex, lineEndIndex + 1);
  24519. matches = conditionLine.match(pragma.conditionalRegExp);
  24520. if (matches) {
  24521. type = matches[1];
  24522. marker = matches[2];
  24523. condition = matches[3];
  24524. isTrue = false;
  24525. //See if the condition is true.
  24526. try {
  24527. isTrue = !!eval("(" + condition + ")");
  24528. } catch (e) {
  24529. throw "Error in file: " +
  24530. fileName +
  24531. ". Conditional comment: " +
  24532. conditionLine +
  24533. " failed with this error: " + e;
  24534. }
  24535. //Find the endpoint marker.
  24536. endRegExp = new RegExp('\\/\\/\\>\\>\\s*' + type + 'End\\(\\s*[\'"]' + marker + '[\'"]\\s*\\)', "g");
  24537. endMatches = endRegExp.exec(fileContents.substring(startIndex, fileContents.length));
  24538. if (endMatches) {
  24539. endMarkerIndex = startIndex + endRegExp.lastIndex - endMatches[0].length;
  24540. //Find the next line return based on the match position.
  24541. lineEndIndex = fileContents.indexOf("\n", endMarkerIndex);
  24542. if (lineEndIndex === -1) {
  24543. lineEndIndex = fileContents.length - 1;
  24544. }
  24545. //Should we include the segment?
  24546. shouldInclude = ((type === "exclude" && !isTrue) || (type === "include" && isTrue));
  24547. //Remove the conditional comments, and optionally remove the content inside
  24548. //the conditional comments.
  24549. startLength = startIndex - foundIndex;
  24550. fileContents = fileContents.substring(0, foundIndex) +
  24551. (shouldInclude ? fileContents.substring(startIndex, endMarkerIndex) : "") +
  24552. fileContents.substring(lineEndIndex + 1, fileContents.length);
  24553. //Move startIndex to foundIndex, since that is the new position in the file
  24554. //where we need to look for more conditionals in the next while loop pass.
  24555. startIndex = foundIndex;
  24556. } else {
  24557. throw "Error in file: " +
  24558. fileName +
  24559. ". Cannot find end marker for conditional comment: " +
  24560. conditionLine;
  24561. }
  24562. }
  24563. }
  24564. }
  24565. //If need to find all plugin resources to optimize, do that now,
  24566. //before namespacing, since the namespacing will change the API
  24567. //names.
  24568. //If there is a plugin collector, scan the file for plugin resources.
  24569. if (config.optimizeAllPluginResources && pluginCollector) {
  24570. try {
  24571. deps = parse.findDependencies(fileName, fileContents);
  24572. if (deps.length) {
  24573. for (i = 0; i < deps.length; i++) {
  24574. dep = deps[i];
  24575. if (dep.indexOf('!') !== -1) {
  24576. moduleName = dep.split('!')[0];
  24577. collectorMod = pluginCollector[moduleName];
  24578. if (!collectorMod) {
  24579. collectorMod = pluginCollector[moduleName] = [];
  24580. }
  24581. collectorMod.push(dep);
  24582. }
  24583. }
  24584. }
  24585. } catch (eDep) {
  24586. logger.error('Parse error looking for plugin resources in ' +
  24587. fileName + ', skipping.');
  24588. }
  24589. }
  24590. //Strip amdefine use for node-shared modules.
  24591. if (!config.keepAmdefine) {
  24592. fileContents = fileContents.replace(pragma.amdefineRegExp, '');
  24593. }
  24594. //Do namespacing
  24595. if (onLifecycleName === 'OnSave' && config.namespace) {
  24596. fileContents = pragma.namespace(fileContents, config.namespace, onLifecycleName);
  24597. }
  24598. return pragma.removeStrict(fileContents, config);
  24599. }
  24600. };
  24601. return pragma;
  24602. });
  24603. if(env === 'browser') {
  24604. /*jslint strict: false */
  24605. /*global define: false */
  24606. define('browser/optimize', {});
  24607. }
  24608. if(env === 'node') {
  24609. /*jslint strict: false */
  24610. /*global define: false */
  24611. define('node/optimize', {});
  24612. }
  24613. if(env === 'rhino') {
  24614. /*jslint sloppy: true, plusplus: true */
  24615. /*global define, java, Packages, com */
  24616. define('rhino/optimize', ['logger', 'env!env/file'], function (logger, file) {
  24617. //Add .reduce to Rhino so UglifyJS can run in Rhino,
  24618. //inspired by https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/reduce
  24619. //but rewritten for brevity, and to be good enough for use by UglifyJS.
  24620. if (!Array.prototype.reduce) {
  24621. Array.prototype.reduce = function (fn /*, initialValue */) {
  24622. var i = 0,
  24623. length = this.length,
  24624. accumulator;
  24625. if (arguments.length >= 2) {
  24626. accumulator = arguments[1];
  24627. } else {
  24628. if (length) {
  24629. while (!(i in this)) {
  24630. i++;
  24631. }
  24632. accumulator = this[i++];
  24633. }
  24634. }
  24635. for (; i < length; i++) {
  24636. if (i in this) {
  24637. accumulator = fn.call(undefined, accumulator, this[i], i, this);
  24638. }
  24639. }
  24640. return accumulator;
  24641. };
  24642. }
  24643. var JSSourceFilefromCode, optimize,
  24644. mapRegExp = /"file":"[^"]+"/;
  24645. //Bind to Closure compiler, but if it is not available, do not sweat it.
  24646. try {
  24647. // Try older closure compiler that worked on Java 6
  24648. JSSourceFilefromCode = java.lang.Class.forName('com.google.javascript.jscomp.JSSourceFile').getMethod('fromCode', [java.lang.String, java.lang.String]);
  24649. } catch (e) {
  24650. try {
  24651. // Try for newer closure compiler that needs Java 7+
  24652. JSSourceFilefromCode = java.lang.Class.forName('com.google.javascript.jscomp.SourceFile').getMethod('fromCode', [java.lang.String, java.lang.String]);
  24653. } catch (e) {
  24654. try {
  24655. // Try Nashorn style
  24656. var stringClass = Java.type("java.lang.String").class;
  24657. JSSourceFilefromCode = Java.type("com.google.javascript.jscomp.SourceFile").class.getMethod("fromCode", [stringClass, stringClass]);
  24658. } catch (e) {}
  24659. }
  24660. }
  24661. //Helper for closure compiler, because of weird Java-JavaScript interactions.
  24662. function closurefromCode(filename, content) {
  24663. return JSSourceFilefromCode.invoke(null, [filename, content]);
  24664. }
  24665. function getFileWriter(fileName, encoding) {
  24666. var outFile = new java.io.File(fileName), outWriter, parentDir;
  24667. parentDir = outFile.getAbsoluteFile().getParentFile();
  24668. if (!parentDir.exists()) {
  24669. if (!parentDir.mkdirs()) {
  24670. throw "Could not create directory: " + parentDir.getAbsolutePath();
  24671. }
  24672. }
  24673. if (encoding) {
  24674. outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile), encoding);
  24675. } else {
  24676. outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile));
  24677. }
  24678. return new java.io.BufferedWriter(outWriter);
  24679. }
  24680. optimize = {
  24681. closure: function (fileName, fileContents, outFileName, keepLines, config) {
  24682. config = config || {};
  24683. var result, mappings, optimized, compressed, baseName, writer,
  24684. outBaseName, outFileNameMap, outFileNameMapContent,
  24685. srcOutFileName, concatNameMap,
  24686. jscomp = Packages.com.google.javascript.jscomp,
  24687. flags = Packages.com.google.common.flags,
  24688. //Set up source input
  24689. jsSourceFile = closurefromCode(String(fileName), String(fileContents)),
  24690. sourceListArray = new java.util.ArrayList(),
  24691. externList = new java.util.ArrayList(),
  24692. options, option, FLAG_compilation_level, compiler, externExportsPath,
  24693. Compiler = Packages.com.google.javascript.jscomp.Compiler,
  24694. CommandLineRunner = Packages.com.google.javascript.jscomp.CommandLineRunner;
  24695. logger.trace("Minifying file: " + fileName);
  24696. baseName = (new java.io.File(fileName)).getName();
  24697. //Set up options
  24698. options = new jscomp.CompilerOptions();
  24699. for (option in config.CompilerOptions) {
  24700. // options are false by default and jslint wanted an if statement in this for loop
  24701. if (config.CompilerOptions[option]) {
  24702. options[option] = config.CompilerOptions[option];
  24703. }
  24704. }
  24705. options.prettyPrint = keepLines || options.prettyPrint;
  24706. FLAG_compilation_level = jscomp.CompilationLevel[config.CompilationLevel || 'SIMPLE_OPTIMIZATIONS'];
  24707. FLAG_compilation_level.setOptionsForCompilationLevel(options);
  24708. if (config.generateSourceMaps) {
  24709. mappings = new java.util.ArrayList();
  24710. mappings.add(new com.google.javascript.jscomp.SourceMap.LocationMapping(fileName, baseName + ".src.js"));
  24711. options.setSourceMapLocationMappings(mappings);
  24712. options.setSourceMapOutputPath(fileName + ".map");
  24713. }
  24714. //If we need to pass an externs file to Closure so that it does not create aliases
  24715. //for certain symbols, do so here.
  24716. externList.addAll(CommandLineRunner.getDefaultExterns());
  24717. if (config.externExportsPath) {
  24718. externExportsPath = config.externExportsPath;
  24719. externList.add(jscomp.SourceFile.fromFile(externExportsPath));
  24720. }
  24721. //Trigger the compiler
  24722. Compiler.setLoggingLevel(Packages.java.util.logging.Level[config.loggingLevel || 'WARNING']);
  24723. compiler = new Compiler();
  24724. //fill the sourceArrrayList; we need the ArrayList because the only overload of compile
  24725. //accepting the getDefaultExterns return value (a List) also wants the sources as a List
  24726. sourceListArray.add(jsSourceFile);
  24727. result = compiler.compile(externList, sourceListArray, options);
  24728. if (result.success) {
  24729. optimized = String(compiler.toSource());
  24730. if (config.generateSourceMaps && result.sourceMap && outFileName) {
  24731. outBaseName = (new java.io.File(outFileName)).getName();
  24732. srcOutFileName = outFileName + ".src.js";
  24733. outFileNameMap = outFileName + ".map";
  24734. //If previous .map file exists, move it to the ".src.js"
  24735. //location. Need to update the sourceMappingURL part in the
  24736. //src.js file too.
  24737. if (file.exists(outFileNameMap)) {
  24738. concatNameMap = outFileNameMap.replace(/\.map$/, '.src.js.map');
  24739. file.saveFile(concatNameMap, file.readFile(outFileNameMap));
  24740. file.saveFile(srcOutFileName,
  24741. fileContents.replace(/\/\# sourceMappingURL=(.+).map/,
  24742. '/# sourceMappingURL=$1.src.js.map'));
  24743. } else {
  24744. file.saveUtf8File(srcOutFileName, fileContents);
  24745. }
  24746. writer = getFileWriter(outFileNameMap, "utf-8");
  24747. result.sourceMap.appendTo(writer, outFileName);
  24748. writer.close();
  24749. //Not sure how better to do this, but right now the .map file
  24750. //leaks the full OS path in the "file" property. Manually
  24751. //modify it to not do that.
  24752. file.saveFile(outFileNameMap,
  24753. file.readFile(outFileNameMap).replace(mapRegExp, '"file":"' + baseName + '"'));
  24754. fileContents = optimized + "\n//# sourceMappingURL=" + outBaseName + ".map";
  24755. } else {
  24756. fileContents = optimized;
  24757. }
  24758. return fileContents;
  24759. } else {
  24760. throw new Error('Cannot closure compile file: ' + fileName + '. Skipping it.');
  24761. }
  24762. return fileContents;
  24763. }
  24764. };
  24765. return optimize;
  24766. });
  24767. }
  24768. if(env === 'xpconnect') {
  24769. define('xpconnect/optimize', {});
  24770. }
  24771. /*jslint plusplus: true, nomen: true, regexp: true */
  24772. /*global define: false */
  24773. define('optimize', [ 'lang', 'logger', 'env!env/optimize', 'env!env/file', 'parse',
  24774. 'pragma', 'uglifyjs',
  24775. 'source-map'],
  24776. function (lang, logger, envOptimize, file, parse,
  24777. pragma, uglify,
  24778. sourceMap) {
  24779. 'use strict';
  24780. var optimize,
  24781. cssImportRegExp = /\@import\s+(url\()?\s*([^);]+)\s*(\))?([\w, ]*)(;)?/ig,
  24782. cssCommentImportRegExp = /\/\*[^\*]*@import[^\*]*\*\//g,
  24783. cssUrlRegExp = /\url\(\s*([^\)]+)\s*\)?/g,
  24784. protocolRegExp = /^\w+:/,
  24785. SourceMapGenerator = sourceMap.SourceMapGenerator,
  24786. SourceMapConsumer = sourceMap.SourceMapConsumer,
  24787. es5PlusGuidance = 'If the source uses ES2015 or later syntax, please pass "optimize: \'none\'" to r.js and use an ES2015+ compatible minifier after running r.js. The included UglifyJS only understands ES5 or earlier syntax.';
  24788. /**
  24789. * If an URL from a CSS url value contains start/end quotes, remove them.
  24790. * This is not done in the regexp, since my regexp fu is not that strong,
  24791. * and the CSS spec allows for ' and " in the URL if they are backslash escaped.
  24792. * @param {String} url
  24793. */
  24794. function cleanCssUrlQuotes(url) {
  24795. //Make sure we are not ending in whitespace.
  24796. //Not very confident of the css regexps above that there will not be ending
  24797. //whitespace.
  24798. url = url.replace(/\s+$/, "");
  24799. if (url.charAt(0) === "'" || url.charAt(0) === "\"") {
  24800. url = url.substring(1, url.length - 1);
  24801. }
  24802. return url;
  24803. }
  24804. function fixCssUrlPaths(fileName, path, contents, cssPrefix) {
  24805. return contents.replace(cssUrlRegExp, function (fullMatch, urlMatch) {
  24806. var firstChar, hasProtocol, parts, i,
  24807. fixedUrlMatch = cleanCssUrlQuotes(urlMatch);
  24808. fixedUrlMatch = fixedUrlMatch.replace(lang.backSlashRegExp, "/");
  24809. //Only do the work for relative URLs. Skip things that start with / or #, or have
  24810. //a protocol.
  24811. firstChar = fixedUrlMatch.charAt(0);
  24812. hasProtocol = protocolRegExp.test(fixedUrlMatch);
  24813. if (firstChar !== "/" && firstChar !== "#" && !hasProtocol) {
  24814. //It is a relative URL, tack on the cssPrefix and path prefix
  24815. urlMatch = cssPrefix + path + fixedUrlMatch;
  24816. } else if (!hasProtocol) {
  24817. logger.trace(fileName + "\n URL not a relative URL, skipping: " + urlMatch);
  24818. }
  24819. //Collapse .. and .
  24820. parts = urlMatch.split("/");
  24821. for (i = parts.length - 1; i > 0; i--) {
  24822. if (parts[i] === ".") {
  24823. parts.splice(i, 1);
  24824. } else if (parts[i] === "..") {
  24825. if (i !== 0 && parts[i - 1] !== "..") {
  24826. parts.splice(i - 1, 2);
  24827. i -= 1;
  24828. }
  24829. }
  24830. }
  24831. return "url(" + parts.join("/") + ")";
  24832. });
  24833. }
  24834. /**
  24835. * Inlines nested stylesheets that have @import calls in them.
  24836. * @param {String} fileName the file name
  24837. * @param {String} fileContents the file contents
  24838. * @param {String} cssImportIgnore comma delimited string of files to ignore
  24839. * @param {String} cssPrefix string to be prefixed before relative URLs
  24840. * @param {Object} included an object used to track the files already imported
  24841. */
  24842. function flattenCss(fileName, fileContents, cssImportIgnore, cssPrefix, included, topLevel) {
  24843. //Find the last slash in the name.
  24844. fileName = fileName.replace(lang.backSlashRegExp, "/");
  24845. var endIndex = fileName.lastIndexOf("/"),
  24846. //Make a file path based on the last slash.
  24847. //If no slash, so must be just a file name. Use empty string then.
  24848. filePath = (endIndex !== -1) ? fileName.substring(0, endIndex + 1) : "",
  24849. //store a list of merged files
  24850. importList = [],
  24851. skippedList = [];
  24852. //First make a pass by removing any commented out @import calls.
  24853. fileContents = fileContents.replace(cssCommentImportRegExp, '');
  24854. //Make sure we have a delimited ignore list to make matching faster
  24855. if (cssImportIgnore && cssImportIgnore.charAt(cssImportIgnore.length - 1) !== ",") {
  24856. cssImportIgnore += ",";
  24857. }
  24858. fileContents = fileContents.replace(cssImportRegExp, function (fullMatch, urlStart, importFileName, urlEnd, mediaTypes) {
  24859. //Only process media type "all" or empty media type rules.
  24860. if (mediaTypes && ((mediaTypes.replace(/^\s\s*/, '').replace(/\s\s*$/, '')) !== "all")) {
  24861. skippedList.push(fileName);
  24862. return fullMatch;
  24863. }
  24864. importFileName = cleanCssUrlQuotes(importFileName);
  24865. //Ignore the file import if it is part of an ignore list.
  24866. if (cssImportIgnore && cssImportIgnore.indexOf(importFileName + ",") !== -1) {
  24867. return fullMatch;
  24868. }
  24869. //Make sure we have a unix path for the rest of the operation.
  24870. importFileName = importFileName.replace(lang.backSlashRegExp, "/");
  24871. try {
  24872. //if a relative path, then tack on the filePath.
  24873. //If it is not a relative path, then the readFile below will fail,
  24874. //and we will just skip that import.
  24875. var fullImportFileName = importFileName.charAt(0) === "/" ? importFileName : filePath + importFileName,
  24876. importContents = file.readFile(fullImportFileName),
  24877. importEndIndex, importPath, flat;
  24878. //Skip the file if it has already been included.
  24879. if (included[fullImportFileName]) {
  24880. return '';
  24881. }
  24882. included[fullImportFileName] = true;
  24883. //Make sure to flatten any nested imports.
  24884. flat = flattenCss(fullImportFileName, importContents, cssImportIgnore, cssPrefix, included);
  24885. importContents = flat.fileContents;
  24886. if (flat.importList.length) {
  24887. importList.push.apply(importList, flat.importList);
  24888. }
  24889. if (flat.skippedList.length) {
  24890. skippedList.push.apply(skippedList, flat.skippedList);
  24891. }
  24892. //Make the full import path
  24893. importEndIndex = importFileName.lastIndexOf("/");
  24894. //Make a file path based on the last slash.
  24895. //If no slash, so must be just a file name. Use empty string then.
  24896. importPath = (importEndIndex !== -1) ? importFileName.substring(0, importEndIndex + 1) : "";
  24897. //fix url() on relative import (#5)
  24898. importPath = importPath.replace(/^\.\//, '');
  24899. //Modify URL paths to match the path represented by this file.
  24900. importContents = fixCssUrlPaths(importFileName, importPath, importContents, cssPrefix);
  24901. importList.push(fullImportFileName);
  24902. return importContents;
  24903. } catch (e) {
  24904. logger.warn(fileName + "\n Cannot inline css import, skipping: " + importFileName);
  24905. return fullMatch;
  24906. }
  24907. });
  24908. if (cssPrefix && topLevel) {
  24909. //Modify URL paths to match the path represented by this file.
  24910. fileContents = fixCssUrlPaths(fileName, '', fileContents, cssPrefix);
  24911. }
  24912. return {
  24913. importList : importList,
  24914. skippedList: skippedList,
  24915. fileContents : fileContents
  24916. };
  24917. }
  24918. optimize = {
  24919. /**
  24920. * Optimizes a file that contains JavaScript content. Optionally collects
  24921. * plugin resources mentioned in a file, and then passes the content
  24922. * through an minifier if one is specified via config.optimize.
  24923. *
  24924. * @param {String} fileName the name of the file to optimize
  24925. * @param {String} fileContents the contents to optimize. If this is
  24926. * a null value, then fileName will be used to read the fileContents.
  24927. * @param {String} outFileName the name of the file to use for the
  24928. * saved optimized content.
  24929. * @param {Object} config the build config object.
  24930. * @param {Array} [pluginCollector] storage for any plugin resources
  24931. * found.
  24932. */
  24933. jsFile: function (fileName, fileContents, outFileName, config, pluginCollector) {
  24934. if (!fileContents) {
  24935. fileContents = file.readFile(fileName);
  24936. }
  24937. fileContents = optimize.js(fileName, fileContents, outFileName, config, pluginCollector);
  24938. file.saveUtf8File(outFileName, fileContents);
  24939. },
  24940. /**
  24941. * Optimizes a file that contains JavaScript content. Optionally collects
  24942. * plugin resources mentioned in a file, and then passes the content
  24943. * through an minifier if one is specified via config.optimize.
  24944. *
  24945. * @param {String} fileName the name of the file that matches the
  24946. * fileContents.
  24947. * @param {String} fileContents the string of JS to optimize.
  24948. * @param {Object} [config] the build config object.
  24949. * @param {Array} [pluginCollector] storage for any plugin resources
  24950. * found.
  24951. */
  24952. js: function (fileName, fileContents, outFileName, config, pluginCollector) {
  24953. var optFunc, optConfig,
  24954. parts = (String(config.optimize)).split('.'),
  24955. optimizerName = parts[0],
  24956. keepLines = parts[1] === 'keepLines',
  24957. licenseContents = '';
  24958. config = config || {};
  24959. //Apply pragmas/namespace renaming
  24960. fileContents = pragma.process(fileName, fileContents, config, 'OnSave', pluginCollector);
  24961. //Optimize the JS files if asked.
  24962. if (optimizerName && optimizerName !== 'none') {
  24963. optFunc = envOptimize[optimizerName] || optimize.optimizers[optimizerName];
  24964. if (!optFunc) {
  24965. throw new Error('optimizer with name of "' +
  24966. optimizerName +
  24967. '" not found for this environment');
  24968. }
  24969. optConfig = config[optimizerName] || {};
  24970. if (config.generateSourceMaps) {
  24971. optConfig.generateSourceMaps = !!config.generateSourceMaps;
  24972. optConfig._buildSourceMap = config._buildSourceMap;
  24973. }
  24974. try {
  24975. if (config.preserveLicenseComments) {
  24976. //Pull out any license comments for prepending after optimization.
  24977. try {
  24978. licenseContents = parse.getLicenseComments(fileName, fileContents);
  24979. } catch (e) {
  24980. throw new Error('Cannot parse file: ' + fileName + ' for comments. Skipping it. Error is:\n' + e.toString());
  24981. }
  24982. }
  24983. if (config.generateSourceMaps && licenseContents) {
  24984. optConfig.preamble = licenseContents;
  24985. licenseContents = '';
  24986. }
  24987. fileContents = licenseContents + optFunc(fileName,
  24988. fileContents,
  24989. outFileName,
  24990. keepLines,
  24991. optConfig);
  24992. if (optConfig._buildSourceMap && optConfig._buildSourceMap !== config._buildSourceMap) {
  24993. config._buildSourceMap = optConfig._buildSourceMap;
  24994. }
  24995. } catch (e) {
  24996. if (config.throwWhen && config.throwWhen.optimize) {
  24997. throw e;
  24998. } else {
  24999. logger.error(e);
  25000. }
  25001. }
  25002. } else {
  25003. if (config._buildSourceMap) {
  25004. config._buildSourceMap = null;
  25005. }
  25006. }
  25007. return fileContents;
  25008. },
  25009. /**
  25010. * Optimizes one CSS file, inlining @import calls, stripping comments, and
  25011. * optionally removes line returns.
  25012. * @param {String} fileName the path to the CSS file to optimize
  25013. * @param {String} outFileName the path to save the optimized file.
  25014. * @param {Object} config the config object with the optimizeCss and
  25015. * cssImportIgnore options.
  25016. */
  25017. cssFile: function (fileName, outFileName, config) {
  25018. //Read in the file. Make sure we have a JS string.
  25019. var originalFileContents = file.readFile(fileName),
  25020. flat = flattenCss(fileName, originalFileContents, config.cssImportIgnore, config.cssPrefix, {}, true),
  25021. //Do not use the flattened CSS if there was one that was skipped.
  25022. fileContents = flat.skippedList.length ? originalFileContents : flat.fileContents,
  25023. startIndex, endIndex, buildText, comment;
  25024. if (flat.skippedList.length) {
  25025. logger.warn('Cannot inline @imports for ' + fileName +
  25026. ',\nthe following files had media queries in them:\n' +
  25027. flat.skippedList.join('\n'));
  25028. }
  25029. //Do comment removal.
  25030. try {
  25031. if (config.optimizeCss.indexOf(".keepComments") === -1) {
  25032. startIndex = 0;
  25033. //Get rid of comments.
  25034. while ((startIndex = fileContents.indexOf("/*", startIndex)) !== -1) {
  25035. endIndex = fileContents.indexOf("*/", startIndex + 2);
  25036. if (endIndex === -1) {
  25037. throw "Improper comment in CSS file: " + fileName;
  25038. }
  25039. comment = fileContents.substring(startIndex, endIndex);
  25040. if (config.preserveLicenseComments &&
  25041. (comment.indexOf('license') !== -1 ||
  25042. comment.indexOf('opyright') !== -1 ||
  25043. comment.indexOf('(c)') !== -1)) {
  25044. //Keep the comment, just increment the startIndex
  25045. startIndex = endIndex;
  25046. } else {
  25047. fileContents = fileContents.substring(0, startIndex) + fileContents.substring(endIndex + 2, fileContents.length);
  25048. startIndex = 0;
  25049. }
  25050. }
  25051. }
  25052. //Get rid of newlines.
  25053. if (config.optimizeCss.indexOf(".keepLines") === -1) {
  25054. fileContents = fileContents.replace(/[\r\n]/g, " ");
  25055. fileContents = fileContents.replace(/\s+/g, " ");
  25056. fileContents = fileContents.replace(/\{\s/g, "{");
  25057. fileContents = fileContents.replace(/\s\}/g, "}");
  25058. } else {
  25059. //Remove multiple empty lines.
  25060. fileContents = fileContents.replace(/(\r\n)+/g, "\r\n");
  25061. fileContents = fileContents.replace(/(\n)+/g, "\n");
  25062. }
  25063. //Remove unnecessary whitespace
  25064. if (config.optimizeCss.indexOf(".keepWhitespace") === -1) {
  25065. //Remove leading and trailing whitespace from lines
  25066. fileContents = fileContents.replace(/^[ \t]+/gm, "");
  25067. fileContents = fileContents.replace(/[ \t]+$/gm, "");
  25068. //Remove whitespace after semicolon, colon, curly brackets and commas
  25069. fileContents = fileContents.replace(/(;|:|\{|}|,)[ \t]+/g, "$1");
  25070. //Remove whitespace before opening curly brackets
  25071. fileContents = fileContents.replace(/[ \t]+(\{)/g, "$1");
  25072. //Truncate double whitespace
  25073. fileContents = fileContents.replace(/([ \t])+/g, "$1");
  25074. //Remove empty lines
  25075. fileContents = fileContents.replace(/^[ \t]*[\r\n]/gm,'');
  25076. }
  25077. } catch (e) {
  25078. fileContents = originalFileContents;
  25079. logger.error("Could not optimized CSS file: " + fileName + ", error: " + e);
  25080. }
  25081. file.saveUtf8File(outFileName, fileContents);
  25082. //text output to stdout and/or written to build.txt file
  25083. buildText = "\n"+ outFileName.replace(config.dir, "") +"\n----------------\n";
  25084. flat.importList.push(fileName);
  25085. buildText += flat.importList.map(function(path){
  25086. return path.replace(config.dir, "");
  25087. }).join("\n");
  25088. return {
  25089. importList: flat.importList,
  25090. buildText: buildText +"\n"
  25091. };
  25092. },
  25093. /**
  25094. * Optimizes CSS files, inlining @import calls, stripping comments, and
  25095. * optionally removes line returns.
  25096. * @param {String} startDir the path to the top level directory
  25097. * @param {Object} config the config object with the optimizeCss and
  25098. * cssImportIgnore options.
  25099. */
  25100. css: function (startDir, config) {
  25101. var buildText = "",
  25102. importList = [],
  25103. shouldRemove = config.dir && config.removeCombined,
  25104. i, fileName, result, fileList;
  25105. if (config.optimizeCss.indexOf("standard") !== -1) {
  25106. fileList = file.getFilteredFileList(startDir, /\.css$/, true);
  25107. if (fileList) {
  25108. for (i = 0; i < fileList.length; i++) {
  25109. fileName = fileList[i];
  25110. logger.trace("Optimizing (" + config.optimizeCss + ") CSS file: " + fileName);
  25111. result = optimize.cssFile(fileName, fileName, config);
  25112. buildText += result.buildText;
  25113. if (shouldRemove) {
  25114. result.importList.pop();
  25115. importList = importList.concat(result.importList);
  25116. }
  25117. }
  25118. }
  25119. if (shouldRemove) {
  25120. importList.forEach(function (path) {
  25121. if (file.exists(path)) {
  25122. file.deleteFile(path);
  25123. }
  25124. });
  25125. }
  25126. }
  25127. return buildText;
  25128. },
  25129. optimizers: {
  25130. uglify: function (fileName, fileContents, outFileName, keepLines, config) {
  25131. var result, existingMap, resultMap, finalMap, sourceIndex,
  25132. uconfig = {},
  25133. existingMapPath = outFileName + '.map',
  25134. baseName = fileName && fileName.split('/').pop();
  25135. config = config || {};
  25136. lang.mixin(uconfig, config, true);
  25137. uconfig.fromString = true;
  25138. if (config.preamble) {
  25139. uconfig.output = {preamble: config.preamble};
  25140. }
  25141. if (config.generateSourceMaps && (outFileName || config._buildSourceMap)) {
  25142. uconfig.outSourceMap = baseName + '.map';
  25143. if (config._buildSourceMap) {
  25144. existingMap = JSON.parse(config._buildSourceMap);
  25145. uconfig.inSourceMap = existingMap;
  25146. } else if (file.exists(existingMapPath)) {
  25147. uconfig.inSourceMap = existingMapPath;
  25148. existingMap = JSON.parse(file.readFile(existingMapPath));
  25149. }
  25150. }
  25151. logger.trace("Uglify file: " + fileName);
  25152. try {
  25153. //var tempContents = fileContents.replace(/\/\/\# sourceMappingURL=.*$/, '');
  25154. result = uglify.minify(fileContents, uconfig, baseName + '.src.js');
  25155. if (uconfig.outSourceMap && result.map) {
  25156. resultMap = result.map;
  25157. if (!existingMap && !config._buildSourceMap) {
  25158. file.saveFile(outFileName + '.src.js', fileContents);
  25159. }
  25160. fileContents = result.code;
  25161. if (config._buildSourceMap) {
  25162. config._buildSourceMap = resultMap;
  25163. } else {
  25164. file.saveFile(outFileName + '.map', resultMap);
  25165. }
  25166. } else {
  25167. fileContents = result.code;
  25168. }
  25169. } catch (e) {
  25170. var errorString = e.toString();
  25171. var isSyntaxError = /SyntaxError/.test(errorString);
  25172. throw new Error('Cannot uglify file: ' + fileName +
  25173. '. Skipping it. Error is:\n' + errorString +
  25174. (isSyntaxError ? '\n\n' + es5PlusGuidance : ''));
  25175. }
  25176. return fileContents;
  25177. }
  25178. }
  25179. };
  25180. return optimize;
  25181. });
  25182. /*
  25183. * This file patches require.js to communicate with the build system.
  25184. */
  25185. //Using sloppy since this uses eval for some code like plugins,
  25186. //which may not be strict mode compliant. So if use strict is used
  25187. //below they will have strict rules applied and may cause an error.
  25188. /*jslint sloppy: true, nomen: true, plusplus: true, regexp: true */
  25189. /*global require, define: true */
  25190. //NOT asking for require as a dependency since the goal is to modify the
  25191. //global require below
  25192. define('requirePatch', [ 'env!env/file', 'pragma', 'parse', 'lang', 'logger', 'commonJs', 'prim'], function (
  25193. file,
  25194. pragma,
  25195. parse,
  25196. lang,
  25197. logger,
  25198. commonJs,
  25199. prim
  25200. ) {
  25201. var allowRun = true,
  25202. hasProp = lang.hasProp,
  25203. falseProp = lang.falseProp,
  25204. getOwn = lang.getOwn,
  25205. // Used to strip out use strict from toString()'d functions for the
  25206. // shim config since they will explicitly want to not be bound by strict,
  25207. // but some envs, explicitly xpcshell, adds a use strict.
  25208. useStrictRegExp = /['"]use strict['"];/g,
  25209. //Absolute path if starts with /, \, or x:
  25210. absoluteUrlRegExp = /^[\/\\]|^\w:/;
  25211. //Turn off throwing on resolution conflict, that was just an older prim
  25212. //idea about finding errors early, but does not comply with how promises
  25213. //should operate.
  25214. prim.hideResolutionConflict = true;
  25215. //This method should be called when the patches to require should take hold.
  25216. return function () {
  25217. if (!allowRun) {
  25218. return;
  25219. }
  25220. allowRun = false;
  25221. var layer,
  25222. pluginBuilderRegExp = /(["']?)pluginBuilder(["']?)\s*[=\:]\s*["']([^'"\s]+)["']/,
  25223. oldNewContext = require.s.newContext,
  25224. oldDef,
  25225. //create local undefined values for module and exports,
  25226. //so that when files are evaled in this function they do not
  25227. //see the node values used for r.js
  25228. exports,
  25229. module;
  25230. /**
  25231. * Reset "global" build caches that are kept around between
  25232. * build layer builds. Useful to do when there are multiple
  25233. * top level requirejs.optimize() calls.
  25234. */
  25235. require._cacheReset = function () {
  25236. //Stored raw text caches, used by browser use.
  25237. require._cachedRawText = {};
  25238. //Stored cached file contents for reuse in other layers.
  25239. require._cachedFileContents = {};
  25240. //Store which cached files contain a require definition.
  25241. require._cachedDefinesRequireUrls = {};
  25242. };
  25243. require._cacheReset();
  25244. /**
  25245. * Makes sure the URL is something that can be supported by the
  25246. * optimization tool.
  25247. * @param {String} url
  25248. * @returns {Boolean}
  25249. */
  25250. require._isSupportedBuildUrl = function (url) {
  25251. //Ignore URLs with protocols, hosts or question marks, means either network
  25252. //access is needed to fetch it or it is too dynamic. Note that
  25253. //on Windows, full paths are used for some urls, which include
  25254. //the drive, like c:/something, so need to test for something other
  25255. //than just a colon.
  25256. if (url.indexOf("://") === -1 && url.indexOf("?") === -1 &&
  25257. url.indexOf('empty:') !== 0 && url.indexOf('//') !== 0) {
  25258. return true;
  25259. } else {
  25260. if (!layer.ignoredUrls[url]) {
  25261. if (url.indexOf('empty:') === -1) {
  25262. logger.info('Cannot optimize network URL, skipping: ' + url);
  25263. }
  25264. layer.ignoredUrls[url] = true;
  25265. }
  25266. return false;
  25267. }
  25268. };
  25269. function normalizeUrlWithBase(context, moduleName, url) {
  25270. //Adjust the URL if it was not transformed to use baseUrl, but only
  25271. //if the URL is not already an absolute path.
  25272. if (require.jsExtRegExp.test(moduleName) &&
  25273. !absoluteUrlRegExp.test(url)) {
  25274. url = (context.config.dir || context.config.dirBaseUrl) + url;
  25275. }
  25276. return url;
  25277. }
  25278. //Overrides the new context call to add existing tracking features.
  25279. require.s.newContext = function (name) {
  25280. var context = oldNewContext(name),
  25281. oldEnable = context.enable,
  25282. moduleProto = context.Module.prototype,
  25283. oldInit = moduleProto.init,
  25284. oldCallPlugin = moduleProto.callPlugin;
  25285. //Only do this for the context used for building.
  25286. if (name === '_') {
  25287. //For build contexts, do everything sync
  25288. context.nextTick = function (fn) {
  25289. fn();
  25290. };
  25291. context.needFullExec = {};
  25292. context.fullExec = {};
  25293. context.plugins = {};
  25294. context.buildShimExports = {};
  25295. //Override the shim exports function generator to just
  25296. //spit out strings that can be used in the stringified
  25297. //build output.
  25298. context.makeShimExports = function (value) {
  25299. var fn;
  25300. if (context.config.wrapShim) {
  25301. fn = function () {
  25302. var str = 'return ';
  25303. // If specifies an export that is just a global
  25304. // name, no dot for a `this.` and such, then also
  25305. // attach to the global, for `var a = {}` files
  25306. // where the function closure would hide that from
  25307. // the global object.
  25308. if (value.exports && value.exports.indexOf('.') === -1) {
  25309. str += 'root.' + value.exports + ' = ';
  25310. }
  25311. if (value.init) {
  25312. str += '(' + value.init.toString()
  25313. .replace(useStrictRegExp, '') + '.apply(this, arguments))';
  25314. }
  25315. if (value.init && value.exports) {
  25316. str += ' || ';
  25317. }
  25318. if (value.exports) {
  25319. str += value.exports;
  25320. }
  25321. str += ';';
  25322. return str;
  25323. };
  25324. } else {
  25325. fn = function () {
  25326. return '(function (global) {\n' +
  25327. ' return function () {\n' +
  25328. ' var ret, fn;\n' +
  25329. (value.init ?
  25330. (' fn = ' + value.init.toString()
  25331. .replace(useStrictRegExp, '') + ';\n' +
  25332. ' ret = fn.apply(global, arguments);\n') : '') +
  25333. (value.exports ?
  25334. ' return ret || global.' + value.exports + ';\n' :
  25335. ' return ret;\n') +
  25336. ' };\n' +
  25337. '}(this))';
  25338. };
  25339. }
  25340. return fn;
  25341. };
  25342. context.enable = function (depMap, parent) {
  25343. var id = depMap.id,
  25344. parentId = parent && parent.map.id,
  25345. needFullExec = context.needFullExec,
  25346. fullExec = context.fullExec,
  25347. mod = getOwn(context.registry, id);
  25348. if (mod && !mod.defined) {
  25349. if (parentId && getOwn(needFullExec, parentId)) {
  25350. needFullExec[id] = depMap;
  25351. }
  25352. } else if ((getOwn(needFullExec, id) && falseProp(fullExec, id)) ||
  25353. (parentId && getOwn(needFullExec, parentId) &&
  25354. falseProp(fullExec, id))) {
  25355. context.require.undef(id);
  25356. }
  25357. return oldEnable.apply(context, arguments);
  25358. };
  25359. //Override load so that the file paths can be collected.
  25360. context.load = function (moduleName, url) {
  25361. /*jslint evil: true */
  25362. var contents, pluginBuilderMatch, builderName,
  25363. shim, shimExports;
  25364. //Do not mark the url as fetched if it is
  25365. //not an empty: URL, used by the optimizer.
  25366. //In that case we need to be sure to call
  25367. //load() for each module that is mapped to
  25368. //empty: so that dependencies are satisfied
  25369. //correctly.
  25370. if (url.indexOf('empty:') === 0) {
  25371. delete context.urlFetched[url];
  25372. }
  25373. //Only handle urls that can be inlined, so that means avoiding some
  25374. //URLs like ones that require network access or may be too dynamic,
  25375. //like JSONP
  25376. if (require._isSupportedBuildUrl(url)) {
  25377. //Adjust the URL if it was not transformed to use baseUrl.
  25378. url = normalizeUrlWithBase(context, moduleName, url);
  25379. //Save the module name to path and path to module name mappings.
  25380. layer.buildPathMap[moduleName] = url;
  25381. layer.buildFileToModule[url] = moduleName;
  25382. if (hasProp(context.plugins, moduleName)) {
  25383. //plugins need to have their source evaled as-is.
  25384. context.needFullExec[moduleName] = true;
  25385. }
  25386. prim().start(function () {
  25387. if (hasProp(require._cachedFileContents, url) &&
  25388. (falseProp(context.needFullExec, moduleName) ||
  25389. getOwn(context.fullExec, moduleName))) {
  25390. contents = require._cachedFileContents[url];
  25391. //If it defines require, mark it so it can be hoisted.
  25392. //Done here and in the else below, before the
  25393. //else block removes code from the contents.
  25394. //Related to #263
  25395. if (!layer.existingRequireUrl && require._cachedDefinesRequireUrls[url]) {
  25396. layer.existingRequireUrl = url;
  25397. }
  25398. } else {
  25399. //Load the file contents, process for conditionals, then
  25400. //evaluate it.
  25401. return require._cacheReadAsync(url).then(function (text) {
  25402. contents = text;
  25403. if (context.config.cjsTranslate &&
  25404. (!context.config.shim || !lang.hasProp(context.config.shim, moduleName))) {
  25405. contents = commonJs.convert(url, contents);
  25406. }
  25407. //If there is a read filter, run it now.
  25408. if (context.config.onBuildRead) {
  25409. contents = context.config.onBuildRead(moduleName, url, contents);
  25410. }
  25411. contents = pragma.process(url, contents, context.config, 'OnExecute');
  25412. //Find out if the file contains a require() definition. Need to know
  25413. //this so we can inject plugins right after it, but before they are needed,
  25414. //and to make sure this file is first, so that define calls work.
  25415. try {
  25416. if (!layer.existingRequireUrl && parse.definesRequire(url, contents)) {
  25417. layer.existingRequireUrl = url;
  25418. require._cachedDefinesRequireUrls[url] = true;
  25419. }
  25420. } catch (e1) {
  25421. throw new Error('Parse error using esprima ' +
  25422. 'for file: ' + url + '\n' + e1);
  25423. }
  25424. }).then(function () {
  25425. if (hasProp(context.plugins, moduleName)) {
  25426. //This is a loader plugin, check to see if it has a build extension,
  25427. //otherwise the plugin will act as the plugin builder too.
  25428. pluginBuilderMatch = pluginBuilderRegExp.exec(contents);
  25429. if (pluginBuilderMatch) {
  25430. //Load the plugin builder for the plugin contents.
  25431. builderName = context.makeModuleMap(pluginBuilderMatch[3],
  25432. context.makeModuleMap(moduleName),
  25433. null,
  25434. true).id;
  25435. return require._cacheReadAsync(context.nameToUrl(builderName));
  25436. }
  25437. }
  25438. return contents;
  25439. }).then(function (text) {
  25440. contents = text;
  25441. //Parse out the require and define calls.
  25442. //Do this even for plugins in case they have their own
  25443. //dependencies that may be separate to how the pluginBuilder works.
  25444. try {
  25445. if (falseProp(context.needFullExec, moduleName)) {
  25446. contents = parse(moduleName, url, contents, {
  25447. insertNeedsDefine: true,
  25448. has: context.config.has,
  25449. findNestedDependencies: context.config.findNestedDependencies
  25450. });
  25451. }
  25452. } catch (e2) {
  25453. throw new Error('Parse error using esprima ' +
  25454. 'for file: ' + url + '\n' + e2);
  25455. }
  25456. require._cachedFileContents[url] = contents;
  25457. });
  25458. }
  25459. }).then(function () {
  25460. if (contents) {
  25461. eval(contents);
  25462. }
  25463. try {
  25464. //If have a string shim config, and this is
  25465. //a fully executed module, try to see if
  25466. //it created a variable in this eval scope
  25467. if (getOwn(context.needFullExec, moduleName)) {
  25468. shim = getOwn(context.config.shim, moduleName);
  25469. if (shim && shim.exports) {
  25470. shimExports = eval(shim.exports);
  25471. if (typeof shimExports !== 'undefined') {
  25472. context.buildShimExports[moduleName] = shimExports;
  25473. }
  25474. }
  25475. }
  25476. //Need to close out completion of this module
  25477. //so that listeners will get notified that it is available.
  25478. context.completeLoad(moduleName);
  25479. } catch (e) {
  25480. //Track which module could not complete loading.
  25481. if (!e.moduleTree) {
  25482. e.moduleTree = [];
  25483. }
  25484. e.moduleTree.push(moduleName);
  25485. throw e;
  25486. }
  25487. }).then(null, function (eOuter) {
  25488. if (!eOuter.fileName) {
  25489. eOuter.fileName = url;
  25490. }
  25491. throw eOuter;
  25492. }).end();
  25493. } else {
  25494. //With unsupported URLs still need to call completeLoad to
  25495. //finish loading.
  25496. context.completeLoad(moduleName);
  25497. }
  25498. };
  25499. //Marks module has having a name, and optionally executes the
  25500. //callback, but only if it meets certain criteria.
  25501. context.execCb = function (name, cb, args, exports) {
  25502. var buildShimExports = getOwn(layer.context.buildShimExports, name);
  25503. if (buildShimExports) {
  25504. return buildShimExports;
  25505. } else if (cb.__requireJsBuild || getOwn(layer.context.needFullExec, name)) {
  25506. return cb.apply(exports, args);
  25507. }
  25508. return undefined;
  25509. };
  25510. moduleProto.init = function (depMaps) {
  25511. if (context.needFullExec[this.map.id]) {
  25512. lang.each(depMaps, lang.bind(this, function (depMap) {
  25513. if (typeof depMap === 'string') {
  25514. depMap = context.makeModuleMap(depMap,
  25515. (this.map.isDefine ? this.map : this.map.parentMap),
  25516. false, true);
  25517. }
  25518. if (!context.fullExec[depMap.id]) {
  25519. context.require.undef(depMap.id);
  25520. }
  25521. }));
  25522. }
  25523. return oldInit.apply(this, arguments);
  25524. };
  25525. moduleProto.callPlugin = function () {
  25526. var map = this.map,
  25527. pluginMap = context.makeModuleMap(map.prefix),
  25528. pluginId = pluginMap.id,
  25529. pluginMod = getOwn(context.registry, pluginId);
  25530. context.plugins[pluginId] = true;
  25531. context.needFullExec[pluginId] = map;
  25532. //If the module is not waiting to finish being defined,
  25533. //undef it and start over, to get full execution.
  25534. if (falseProp(context.fullExec, pluginId) && (!pluginMod || pluginMod.defined)) {
  25535. context.require.undef(pluginMap.id);
  25536. }
  25537. return oldCallPlugin.apply(this, arguments);
  25538. };
  25539. }
  25540. return context;
  25541. };
  25542. //Clear up the existing context so that the newContext modifications
  25543. //above will be active.
  25544. delete require.s.contexts._;
  25545. /** Reset state for each build layer pass. */
  25546. require._buildReset = function () {
  25547. var oldContext = require.s.contexts._;
  25548. //Clear up the existing context.
  25549. delete require.s.contexts._;
  25550. //Set up new context, so the layer object can hold onto it.
  25551. require({});
  25552. layer = require._layer = {
  25553. buildPathMap: {},
  25554. buildFileToModule: {},
  25555. buildFilePaths: [],
  25556. pathAdded: {},
  25557. modulesWithNames: {},
  25558. needsDefine: {},
  25559. existingRequireUrl: "",
  25560. ignoredUrls: {},
  25561. context: require.s.contexts._
  25562. };
  25563. //Return the previous context in case it is needed, like for
  25564. //the basic config object.
  25565. return oldContext;
  25566. };
  25567. require._buildReset();
  25568. //Override define() to catch modules that just define an object, so that
  25569. //a dummy define call is not put in the build file for them. They do
  25570. //not end up getting defined via context.execCb, so we need to catch them
  25571. //at the define call.
  25572. oldDef = define;
  25573. //This function signature does not have to be exact, just match what we
  25574. //are looking for.
  25575. define = function (name) {
  25576. if (typeof name === "string" && falseProp(layer.needsDefine, name)) {
  25577. layer.modulesWithNames[name] = true;
  25578. }
  25579. return oldDef.apply(require, arguments);
  25580. };
  25581. define.amd = oldDef.amd;
  25582. //Add some utilities for plugins
  25583. require._readFile = file.readFile;
  25584. require._fileExists = function (path) {
  25585. return file.exists(path);
  25586. };
  25587. //Called when execManager runs for a dependency. Used to figure out
  25588. //what order of execution.
  25589. require.onResourceLoad = function (context, map) {
  25590. var id = map.id,
  25591. url;
  25592. // Fix up any maps that need to be normalized as part of the fullExec
  25593. // plumbing for plugins to participate in the build.
  25594. if (context.plugins && lang.hasProp(context.plugins, id)) {
  25595. lang.eachProp(context.needFullExec, function(value, prop) {
  25596. // For plugin entries themselves, they do not have a map
  25597. // value in needFullExec, just a "true" entry.
  25598. if (value !== true && value.prefix === id && value.unnormalized) {
  25599. var map = context.makeModuleMap(value.originalName, value.parentMap);
  25600. context.needFullExec[map.id] = map;
  25601. }
  25602. });
  25603. }
  25604. //If build needed a full execution, indicate it
  25605. //has been done now. But only do it if the context is tracking
  25606. //that. Only valid for the context used in a build, not for
  25607. //other contexts being run, like for useLib, plain requirejs
  25608. //use in node/rhino.
  25609. if (context.needFullExec && getOwn(context.needFullExec, id)) {
  25610. context.fullExec[id] = map;
  25611. }
  25612. //A plugin.
  25613. if (map.prefix) {
  25614. if (falseProp(layer.pathAdded, id)) {
  25615. layer.buildFilePaths.push(id);
  25616. //For plugins the real path is not knowable, use the name
  25617. //for both module to file and file to module mappings.
  25618. layer.buildPathMap[id] = id;
  25619. layer.buildFileToModule[id] = id;
  25620. layer.modulesWithNames[id] = true;
  25621. layer.pathAdded[id] = true;
  25622. }
  25623. } else if (map.url && require._isSupportedBuildUrl(map.url)) {
  25624. //If the url has not been added to the layer yet, and it
  25625. //is from an actual file that was loaded, add it now.
  25626. url = normalizeUrlWithBase(context, id, map.url);
  25627. if (!layer.pathAdded[url] && getOwn(layer.buildPathMap, id)) {
  25628. //Remember the list of dependencies for this layer.
  25629. layer.buildFilePaths.push(url);
  25630. layer.pathAdded[url] = true;
  25631. }
  25632. }
  25633. };
  25634. //Called by output of the parse() function, when a file does not
  25635. //explicitly call define, probably just require, but the parse()
  25636. //function normalizes on define() for dependency mapping and file
  25637. //ordering works correctly.
  25638. require.needsDefine = function (moduleName) {
  25639. layer.needsDefine[moduleName] = true;
  25640. };
  25641. };
  25642. });
  25643. /*jslint */
  25644. /*global define: false, console: false */
  25645. define('commonJs', ['env!env/file', 'parse'], function (file, parse) {
  25646. 'use strict';
  25647. var commonJs = {
  25648. //Set to false if you do not want this file to log. Useful in environments
  25649. //like node where you want the work to happen without noise.
  25650. useLog: true,
  25651. convertDir: function (commonJsPath, savePath) {
  25652. var fileList, i,
  25653. jsFileRegExp = /\.js$/,
  25654. fileName, convertedFileName, fileContents;
  25655. //Get list of files to convert.
  25656. fileList = file.getFilteredFileList(commonJsPath, /\w/, true);
  25657. //Normalize on front slashes and make sure the paths do not end in a slash.
  25658. commonJsPath = commonJsPath.replace(/\\/g, "/");
  25659. savePath = savePath.replace(/\\/g, "/");
  25660. if (commonJsPath.charAt(commonJsPath.length - 1) === "/") {
  25661. commonJsPath = commonJsPath.substring(0, commonJsPath.length - 1);
  25662. }
  25663. if (savePath.charAt(savePath.length - 1) === "/") {
  25664. savePath = savePath.substring(0, savePath.length - 1);
  25665. }
  25666. //Cycle through all the JS files and convert them.
  25667. if (!fileList || !fileList.length) {
  25668. if (commonJs.useLog) {
  25669. if (commonJsPath === "convert") {
  25670. //A request just to convert one file.
  25671. console.log('\n\n' + commonJs.convert(savePath, file.readFile(savePath)));
  25672. } else {
  25673. console.log("No files to convert in directory: " + commonJsPath);
  25674. }
  25675. }
  25676. } else {
  25677. for (i = 0; i < fileList.length; i++) {
  25678. fileName = fileList[i];
  25679. convertedFileName = fileName.replace(commonJsPath, savePath);
  25680. //Handle JS files.
  25681. if (jsFileRegExp.test(fileName)) {
  25682. fileContents = file.readFile(fileName);
  25683. fileContents = commonJs.convert(fileName, fileContents);
  25684. file.saveUtf8File(convertedFileName, fileContents);
  25685. } else {
  25686. //Just copy the file over.
  25687. file.copyFile(fileName, convertedFileName, true);
  25688. }
  25689. }
  25690. }
  25691. },
  25692. /**
  25693. * Does the actual file conversion.
  25694. *
  25695. * @param {String} fileName the name of the file.
  25696. *
  25697. * @param {String} fileContents the contents of a file :)
  25698. *
  25699. * @returns {String} the converted contents
  25700. */
  25701. convert: function (fileName, fileContents) {
  25702. //Strip out comments.
  25703. try {
  25704. var preamble = '',
  25705. commonJsProps = parse.usesCommonJs(fileName, fileContents);
  25706. //First see if the module is not already RequireJS-formatted.
  25707. if (parse.usesAmdOrRequireJs(fileName, fileContents) || !commonJsProps) {
  25708. return fileContents;
  25709. }
  25710. if (commonJsProps.dirname || commonJsProps.filename) {
  25711. preamble = 'var __filename = module.uri || "", ' +
  25712. '__dirname = __filename.substring(0, __filename.lastIndexOf("/") + 1); ';
  25713. }
  25714. //Construct the wrapper boilerplate.
  25715. fileContents = 'define(function (require, exports, module) {' +
  25716. preamble +
  25717. fileContents +
  25718. '\n});\n';
  25719. } catch (e) {
  25720. console.log("commonJs.convert: COULD NOT CONVERT: " + fileName + ", so skipping it. Error was: " + e);
  25721. return fileContents;
  25722. }
  25723. return fileContents;
  25724. }
  25725. };
  25726. return commonJs;
  25727. });
  25728. /*jslint plusplus: true, nomen: true, regexp: true */
  25729. /*global define, requirejs, java, process, console */
  25730. define('build', function (require) {
  25731. 'use strict';
  25732. var build,
  25733. lang = require('lang'),
  25734. prim = require('prim'),
  25735. logger = require('logger'),
  25736. file = require('env!env/file'),
  25737. parse = require('parse'),
  25738. optimize = require('optimize'),
  25739. pragma = require('pragma'),
  25740. transform = require('transform'),
  25741. requirePatch = require('requirePatch'),
  25742. env = require('env'),
  25743. commonJs = require('commonJs'),
  25744. SourceMapGenerator = require('source-map').SourceMapGenerator,
  25745. hasProp = lang.hasProp,
  25746. getOwn = lang.getOwn,
  25747. falseProp = lang.falseProp,
  25748. endsWithSemiColonRegExp = /;\s*$/,
  25749. endsWithSlashRegExp = /[\/\\]$/,
  25750. resourceIsModuleIdRegExp = /^[\w\/\\\.]+$/,
  25751. deepCopyProps = {
  25752. layer: true
  25753. };
  25754. //Deep copy a config object, but do not copy over the "layer" property,
  25755. //as it can be a deeply nested structure with a full requirejs context.
  25756. function copyConfig(obj) {
  25757. return lang.deeplikeCopy(obj, deepCopyProps);
  25758. }
  25759. prim.nextTick = function (fn) {
  25760. fn();
  25761. };
  25762. //Now map require to the outermost requirejs, now that we have
  25763. //local dependencies for this module. The rest of the require use is
  25764. //manipulating the requirejs loader.
  25765. require = requirejs;
  25766. //Caching function for performance. Attached to
  25767. //require so it can be reused in requirePatch.js. _cachedRawText
  25768. //set up by requirePatch.js
  25769. require._cacheReadAsync = function (path, encoding) {
  25770. var d;
  25771. if (lang.hasProp(require._cachedRawText, path)) {
  25772. d = prim();
  25773. d.resolve(require._cachedRawText[path]);
  25774. return d.promise;
  25775. } else {
  25776. return file.readFileAsync(path, encoding).then(function (text) {
  25777. require._cachedRawText[path] = text;
  25778. return text;
  25779. });
  25780. }
  25781. };
  25782. function makeBuildBaseConfig() {
  25783. return {
  25784. appDir: "",
  25785. pragmas: {},
  25786. paths: {},
  25787. optimize: "uglify",
  25788. optimizeCss: "standard.keepLines.keepWhitespace",
  25789. inlineText: true,
  25790. isBuild: true,
  25791. optimizeAllPluginResources: false,
  25792. findNestedDependencies: false,
  25793. preserveLicenseComments: true,
  25794. writeBuildTxt: true,
  25795. //Some builds can take a while, up the default limit.
  25796. waitSeconds: 30,
  25797. //By default, all files/directories are copied, unless
  25798. //they match this regexp, by default just excludes .folders
  25799. dirExclusionRegExp: file.dirExclusionRegExp,
  25800. _buildPathToModuleIndex: {}
  25801. };
  25802. }
  25803. /**
  25804. * Some JS may not be valid if concatenated with other JS, in particular
  25805. * the style of omitting semicolons and rely on ASI. Add a semicolon in
  25806. * those cases.
  25807. */
  25808. function addSemiColon(text, config) {
  25809. if (config.skipSemiColonInsertion || endsWithSemiColonRegExp.test(text)) {
  25810. return text;
  25811. } else {
  25812. return text + ";";
  25813. }
  25814. }
  25815. function endsWithSlash(dirName) {
  25816. if (dirName.charAt(dirName.length - 1) !== "/") {
  25817. dirName += "/";
  25818. }
  25819. return dirName;
  25820. }
  25821. function endsWithNewLine(text) {
  25822. if (text.charAt(text.length - 1) !== "\n") {
  25823. text += "\n";
  25824. }
  25825. return text;
  25826. }
  25827. //Method used by plugin writeFile calls, defined up here to avoid
  25828. //jslint warning about "making a function in a loop".
  25829. function makeWriteFile(namespace, layer) {
  25830. function writeFile(name, contents) {
  25831. logger.trace('Saving plugin-optimized file: ' + name);
  25832. file.saveUtf8File(name, contents);
  25833. }
  25834. writeFile.asModule = function (moduleName, fileName, contents) {
  25835. writeFile(fileName,
  25836. build.toTransport(namespace, moduleName, fileName, contents, layer));
  25837. };
  25838. return writeFile;
  25839. }
  25840. /**
  25841. * Appends singleContents to fileContents and returns the result. If a sourceMapGenerator
  25842. * is provided, adds singleContents to the source map.
  25843. *
  25844. * @param {string} fileContents - The file contents to which to append singleContents
  25845. * @param {string} singleContents - The additional contents to append to fileContents
  25846. * @param {string} path - An absolute path of a file whose name to use in the source map.
  25847. * The file need not actually exist if the code in singleContents is generated.
  25848. * @param {{out: ?string, baseUrl: ?string}} config - The build configuration object.
  25849. * @param {?{_buildPath: ?string}} module - An object with module information.
  25850. * @param {?SourceMapGenerator} sourceMapGenerator - An instance of Mozilla's SourceMapGenerator,
  25851. * or null if no source map is being generated.
  25852. * @returns {string} fileContents with singleContents appended
  25853. */
  25854. function appendToFileContents(fileContents, singleContents, path, config, module, sourceMapGenerator) {
  25855. var refPath, sourceMapPath, resourcePath, pluginId, sourceMapLineNumber, lineCount, parts, i;
  25856. if (sourceMapGenerator) {
  25857. if (config.out) {
  25858. refPath = config.baseUrl;
  25859. } else if (module && module._buildPath) {
  25860. refPath = module._buildPath;
  25861. } else {
  25862. refPath = "";
  25863. }
  25864. parts = path.split('!');
  25865. if (parts.length === 1) {
  25866. //Not a plugin resource, fix the path
  25867. sourceMapPath = build.makeRelativeFilePath(refPath, path);
  25868. } else {
  25869. //Plugin resource. If it looks like just a plugin
  25870. //followed by a module ID, pull off the plugin
  25871. //and put it at the end of the name, otherwise
  25872. //just leave it alone.
  25873. pluginId = parts.shift();
  25874. resourcePath = parts.join('!');
  25875. if (resourceIsModuleIdRegExp.test(resourcePath)) {
  25876. sourceMapPath = build.makeRelativeFilePath(refPath, require.toUrl(resourcePath)) +
  25877. '!' + pluginId;
  25878. } else {
  25879. sourceMapPath = path;
  25880. }
  25881. }
  25882. sourceMapLineNumber = fileContents.split('\n').length - 1;
  25883. lineCount = singleContents.split('\n').length;
  25884. for (i = 1; i <= lineCount; i += 1) {
  25885. sourceMapGenerator.addMapping({
  25886. generated: {
  25887. line: sourceMapLineNumber + i,
  25888. column: 0
  25889. },
  25890. original: {
  25891. line: i,
  25892. column: 0
  25893. },
  25894. source: sourceMapPath
  25895. });
  25896. }
  25897. //Store the content of the original in the source
  25898. //map since other transforms later like minification
  25899. //can mess up translating back to the original
  25900. //source.
  25901. sourceMapGenerator.setSourceContent(sourceMapPath, singleContents);
  25902. }
  25903. fileContents += singleContents;
  25904. return fileContents;
  25905. }
  25906. /**
  25907. * Main API entry point into the build. The args argument can either be
  25908. * an array of arguments (like the onese passed on a command-line),
  25909. * or it can be a JavaScript object that has the format of a build profile
  25910. * file.
  25911. *
  25912. * If it is an object, then in addition to the normal properties allowed in
  25913. * a build profile file, the object should contain one other property:
  25914. *
  25915. * The object could also contain a "buildFile" property, which is a string
  25916. * that is the file path to a build profile that contains the rest
  25917. * of the build profile directives.
  25918. *
  25919. * This function does not return a status, it should throw an error if
  25920. * there is a problem completing the build.
  25921. */
  25922. build = function (args) {
  25923. var buildFile, cmdConfig, errorMsg, errorStack, stackMatch, errorTree,
  25924. i, j, errorMod,
  25925. stackRegExp = /( {4}at[^\n]+)\n/,
  25926. standardIndent = ' ';
  25927. return prim().start(function () {
  25928. if (!args || lang.isArray(args)) {
  25929. if (!args || args.length < 1) {
  25930. logger.error("build.js buildProfile.js\n" +
  25931. "where buildProfile.js is the name of the build file (see example.build.js for hints on how to make a build file).");
  25932. return undefined;
  25933. }
  25934. //Next args can include a build file path as well as other build args.
  25935. //build file path comes first. If it does not contain an = then it is
  25936. //a build file path. Otherwise, just all build args.
  25937. if (args[0].indexOf("=") === -1) {
  25938. buildFile = args[0];
  25939. args.splice(0, 1);
  25940. }
  25941. //Remaining args are options to the build
  25942. cmdConfig = build.convertArrayToObject(args);
  25943. cmdConfig.buildFile = buildFile;
  25944. } else {
  25945. cmdConfig = args;
  25946. }
  25947. return build._run(cmdConfig);
  25948. }).then(null, function (e) {
  25949. var err;
  25950. errorMsg = e.toString();
  25951. errorTree = e.moduleTree;
  25952. stackMatch = stackRegExp.exec(errorMsg);
  25953. if (stackMatch) {
  25954. errorMsg += errorMsg.substring(0, stackMatch.index + stackMatch[0].length + 1);
  25955. }
  25956. //If a module tree that shows what module triggered the error,
  25957. //print it out.
  25958. if (errorTree && errorTree.length > 0) {
  25959. errorMsg += '\nIn module tree:\n';
  25960. for (i = errorTree.length - 1; i > -1; i--) {
  25961. errorMod = errorTree[i];
  25962. if (errorMod) {
  25963. for (j = errorTree.length - i; j > -1; j--) {
  25964. errorMsg += standardIndent;
  25965. }
  25966. errorMsg += errorMod + '\n';
  25967. }
  25968. }
  25969. logger.error(errorMsg);
  25970. }
  25971. errorStack = e.stack;
  25972. if (typeof args === 'string' && args.indexOf('stacktrace=true') !== -1) {
  25973. errorMsg += '\n' + errorStack;
  25974. } else {
  25975. if (!stackMatch && errorStack) {
  25976. //Just trim out the first "at" in the stack.
  25977. stackMatch = stackRegExp.exec(errorStack);
  25978. if (stackMatch) {
  25979. errorMsg += '\n' + stackMatch[0] || '';
  25980. }
  25981. }
  25982. }
  25983. err = new Error(errorMsg);
  25984. err.originalError = e;
  25985. throw err;
  25986. });
  25987. };
  25988. build._run = function (cmdConfig) {
  25989. var buildPaths, fileName, fileNames,
  25990. paths, i,
  25991. baseConfig, config,
  25992. modules, srcPath, buildContext,
  25993. destPath, moduleMap, parentModuleMap, context,
  25994. resources, resource, plugin, fileContents,
  25995. pluginProcessed = {},
  25996. buildFileContents = "",
  25997. pluginCollector = {};
  25998. return prim().start(function () {
  25999. var prop;
  26000. //Can now run the patches to require.js to allow it to be used for
  26001. //build generation. Do it here instead of at the top of the module
  26002. //because we want normal require behavior to load the build tool
  26003. //then want to switch to build mode.
  26004. requirePatch();
  26005. config = build.createConfig(cmdConfig);
  26006. paths = config.paths;
  26007. //Remove the previous build dir, in case it contains source transforms,
  26008. //like the ones done with onBuildRead and onBuildWrite.
  26009. if (config.dir && !config.keepBuildDir && file.exists(config.dir)) {
  26010. file.deleteFile(config.dir);
  26011. }
  26012. if (!config.out && !config.cssIn) {
  26013. //This is not just a one-off file build but a full build profile, with
  26014. //lots of files to process.
  26015. //First copy all the baseUrl content
  26016. file.copyDir((config.appDir || config.baseUrl), config.dir, /\w/, true);
  26017. //Adjust baseUrl if config.appDir is in play, and set up build output paths.
  26018. buildPaths = {};
  26019. if (config.appDir) {
  26020. //All the paths should be inside the appDir, so just adjust
  26021. //the paths to use the dirBaseUrl
  26022. for (prop in paths) {
  26023. if (hasProp(paths, prop)) {
  26024. buildPaths[prop] = paths[prop].replace(config.appDir, config.dir);
  26025. }
  26026. }
  26027. } else {
  26028. //If no appDir, then make sure to copy the other paths to this directory.
  26029. for (prop in paths) {
  26030. if (hasProp(paths, prop)) {
  26031. //Set up build path for each path prefix, but only do so
  26032. //if the path falls out of the current baseUrl
  26033. if (paths[prop].indexOf(config.baseUrl) === 0) {
  26034. buildPaths[prop] = paths[prop].replace(config.baseUrl, config.dirBaseUrl);
  26035. } else {
  26036. buildPaths[prop] = paths[prop] === 'empty:' ? 'empty:' : prop;
  26037. //Make sure source path is fully formed with baseUrl,
  26038. //if it is a relative URL.
  26039. srcPath = paths[prop];
  26040. if (srcPath.indexOf('/') !== 0 && srcPath.indexOf(':') === -1) {
  26041. srcPath = config.baseUrl + srcPath;
  26042. }
  26043. destPath = config.dirBaseUrl + buildPaths[prop];
  26044. //Skip empty: paths
  26045. if (srcPath !== 'empty:') {
  26046. //If the srcPath is a directory, copy the whole directory.
  26047. if (file.exists(srcPath) && file.isDirectory(srcPath)) {
  26048. //Copy files to build area. Copy all files (the /\w/ regexp)
  26049. file.copyDir(srcPath, destPath, /\w/, true);
  26050. } else {
  26051. //Try a .js extension
  26052. srcPath += '.js';
  26053. destPath += '.js';
  26054. file.copyFile(srcPath, destPath);
  26055. }
  26056. }
  26057. }
  26058. }
  26059. }
  26060. }
  26061. }
  26062. //Figure out source file location for each module layer. Do this by seeding require
  26063. //with source area configuration. This is needed so that later the module layers
  26064. //can be manually copied over to the source area, since the build may be
  26065. //require multiple times and the above copyDir call only copies newer files.
  26066. require({
  26067. baseUrl: config.baseUrl,
  26068. paths: paths,
  26069. packagePaths: config.packagePaths,
  26070. packages: config.packages
  26071. });
  26072. buildContext = require.s.contexts._;
  26073. modules = config.modules;
  26074. if (modules) {
  26075. modules.forEach(function (module) {
  26076. if (module.name) {
  26077. module._sourcePath = buildContext.nameToUrl(module.name);
  26078. //If the module does not exist, and this is not a "new" module layer,
  26079. //as indicated by a true "create" property on the module, and
  26080. //it is not a plugin-loaded resource, and there is no
  26081. //'rawText' containing the module's source then throw an error.
  26082. if (!file.exists(module._sourcePath) && !module.create &&
  26083. module.name.indexOf('!') === -1 &&
  26084. (!config.rawText || !lang.hasProp(config.rawText, module.name))) {
  26085. throw new Error("ERROR: module path does not exist: " +
  26086. module._sourcePath + " for module named: " + module.name +
  26087. ". Path is relative to: " + file.absPath('.'));
  26088. }
  26089. }
  26090. });
  26091. }
  26092. if (config.out) {
  26093. //Just set up the _buildPath for the module layer.
  26094. require(config);
  26095. if (!config.cssIn) {
  26096. config.modules[0]._buildPath = typeof config.out === 'function' ?
  26097. 'FUNCTION' : config.out;
  26098. }
  26099. } else if (!config.cssIn) {
  26100. //Now set up the config for require to use the build area, and calculate the
  26101. //build file locations. Pass along any config info too.
  26102. baseConfig = {
  26103. baseUrl: config.dirBaseUrl,
  26104. paths: buildPaths
  26105. };
  26106. lang.mixin(baseConfig, config);
  26107. require(baseConfig);
  26108. if (modules) {
  26109. modules.forEach(function (module) {
  26110. if (module.name) {
  26111. module._buildPath = buildContext.nameToUrl(module.name, null);
  26112. //If buildPath and sourcePath are the same, throw since this
  26113. //would result in modifying source. This condition can happen
  26114. //with some more tricky paths: config and appDir/baseUrl
  26115. //setting, which is a sign of incorrect config.
  26116. if (module._buildPath === module._sourcePath &&
  26117. !config.allowSourceOverwrites) {
  26118. throw new Error('Module ID \'' + module.name +
  26119. '\' has a source path that is same as output path: ' +
  26120. module._sourcePath +
  26121. '. Stopping, config is malformed.');
  26122. }
  26123. // Copy the file, but only if it is not provided in rawText.
  26124. if (!module.create && (!config.rawText || !lang.hasProp(config.rawText, module.name))) {
  26125. file.copyFile(module._sourcePath, module._buildPath);
  26126. }
  26127. }
  26128. });
  26129. }
  26130. }
  26131. //Run CSS optimizations before doing JS module tracing, to allow
  26132. //things like text loader plugins loading CSS to get the optimized
  26133. //CSS.
  26134. if (config.optimizeCss && config.optimizeCss !== "none" && config.dir) {
  26135. buildFileContents += optimize.css(config.dir, config);
  26136. }
  26137. }).then(function() {
  26138. baseConfig = copyConfig(require.s.contexts._.config);
  26139. }).then(function () {
  26140. var actions = [];
  26141. if (modules) {
  26142. actions = modules.map(function (module, i) {
  26143. return function () {
  26144. //Save off buildPath to module index in a hash for quicker
  26145. //lookup later.
  26146. config._buildPathToModuleIndex[file.normalize(module._buildPath)] = i;
  26147. //Call require to calculate dependencies.
  26148. return build.traceDependencies(module, config, baseConfig)
  26149. .then(function (layer) {
  26150. module.layer = layer;
  26151. });
  26152. };
  26153. });
  26154. return prim.serial(actions);
  26155. }
  26156. }).then(function () {
  26157. var actions;
  26158. if (modules) {
  26159. //Now build up shadow layers for anything that should be excluded.
  26160. //Do this after tracing dependencies for each module, in case one
  26161. //of those modules end up being one of the excluded values.
  26162. actions = modules.map(function (module) {
  26163. return function () {
  26164. if (module.exclude) {
  26165. module.excludeLayers = [];
  26166. return prim.serial(module.exclude.map(function (exclude, i) {
  26167. return function () {
  26168. //See if it is already in the list of modules.
  26169. //If not trace dependencies for it.
  26170. var found = build.findBuildModule(exclude, modules);
  26171. if (found) {
  26172. module.excludeLayers[i] = found;
  26173. } else {
  26174. return build.traceDependencies({name: exclude}, config, baseConfig)
  26175. .then(function (layer) {
  26176. module.excludeLayers[i] = { layer: layer };
  26177. });
  26178. }
  26179. };
  26180. }));
  26181. }
  26182. };
  26183. });
  26184. return prim.serial(actions);
  26185. }
  26186. }).then(function () {
  26187. if (modules) {
  26188. return prim.serial(modules.map(function (module) {
  26189. return function () {
  26190. if (module.exclude) {
  26191. //module.exclude is an array of module names. For each one,
  26192. //get the nested dependencies for it via a matching entry
  26193. //in the module.excludeLayers array.
  26194. module.exclude.forEach(function (excludeModule, i) {
  26195. var excludeLayer = module.excludeLayers[i].layer,
  26196. map = excludeLayer.buildFileToModule;
  26197. excludeLayer.buildFilePaths.forEach(function(filePath){
  26198. build.removeModulePath(map[filePath], filePath, module.layer);
  26199. });
  26200. });
  26201. }
  26202. if (module.excludeShallow) {
  26203. //module.excludeShallow is an array of module names.
  26204. //shallow exclusions are just that module itself, and not
  26205. //its nested dependencies.
  26206. module.excludeShallow.forEach(function (excludeShallowModule) {
  26207. var path = getOwn(module.layer.buildPathMap, excludeShallowModule);
  26208. if (path) {
  26209. build.removeModulePath(excludeShallowModule, path, module.layer);
  26210. }
  26211. });
  26212. }
  26213. //Flatten them and collect the build output for each module.
  26214. return build.flattenModule(module, module.layer, config).then(function (builtModule) {
  26215. var finalText, baseName;
  26216. //Save it to a temp file for now, in case there are other layers that
  26217. //contain optimized content that should not be included in later
  26218. //layer optimizations. See issue #56.
  26219. if (module._buildPath === 'FUNCTION') {
  26220. module._buildText = builtModule.text;
  26221. module._buildSourceMap = builtModule.sourceMap;
  26222. } else {
  26223. finalText = builtModule.text;
  26224. if (builtModule.sourceMap) {
  26225. baseName = module._buildPath.split('/');
  26226. baseName = baseName.pop();
  26227. finalText += '\n//# sourceMappingURL=' + baseName + '.map';
  26228. file.saveUtf8File(module._buildPath + '.map', builtModule.sourceMap);
  26229. }
  26230. file.saveUtf8File(module._buildPath + '-temp', finalText);
  26231. }
  26232. buildFileContents += builtModule.buildText;
  26233. });
  26234. };
  26235. }));
  26236. }
  26237. }).then(function () {
  26238. var moduleName, outOrigSourceMap,
  26239. bundlesConfig = {},
  26240. bundlesConfigOutFile = config.bundlesConfigOutFile;
  26241. if (modules) {
  26242. //Now move the build layers to their final position.
  26243. modules.forEach(function (module) {
  26244. var entryConfig,
  26245. finalPath = module._buildPath;
  26246. if (finalPath !== 'FUNCTION') {
  26247. if (file.exists(finalPath)) {
  26248. file.deleteFile(finalPath);
  26249. }
  26250. file.renameFile(finalPath + '-temp', finalPath);
  26251. //If bundles config should be written out, scan the
  26252. //built file for module IDs. Favor doing this reparse
  26253. //since tracking the IDs as the file is built has some
  26254. //edge cases around files that had more than one ID in
  26255. //them already, and likely loader plugin-written contents.
  26256. if (bundlesConfigOutFile) {
  26257. entryConfig = bundlesConfig[module.name] = [];
  26258. var bundleContents = file.readFile(finalPath);
  26259. var excludeMap = {};
  26260. excludeMap[module.name] = true;
  26261. var parsedIds = parse.getAllNamedDefines(bundleContents, excludeMap);
  26262. entryConfig.push.apply(entryConfig, parsedIds);
  26263. }
  26264. //And finally, if removeCombined is specified, remove
  26265. //any of the files that were used in this layer.
  26266. //Be sure not to remove other build layers.
  26267. if (config.removeCombined && !config.out) {
  26268. module.layer.buildFilePaths.forEach(function (path) {
  26269. var isLayer = modules.some(function (mod) {
  26270. return mod._buildPath === path;
  26271. }),
  26272. relPath = build.makeRelativeFilePath(config.dir, path);
  26273. if (file.exists(path) &&
  26274. // not a build layer target
  26275. !isLayer &&
  26276. // not outside the build directory
  26277. relPath.indexOf('..') !== 0) {
  26278. file.deleteFile(path);
  26279. }
  26280. });
  26281. }
  26282. }
  26283. //Signal layer is done
  26284. if (config.onModuleBundleComplete) {
  26285. config.onModuleBundleComplete(module.onCompleteData);
  26286. }
  26287. });
  26288. //Write out bundles config, if it is wanted.
  26289. if (bundlesConfigOutFile) {
  26290. var text = file.readFile(bundlesConfigOutFile);
  26291. text = transform.modifyConfig(text, function (config) {
  26292. if (!config.bundles) {
  26293. config.bundles = {};
  26294. }
  26295. lang.eachProp(bundlesConfig, function (value, prop) {
  26296. config.bundles[prop] = value;
  26297. });
  26298. return config;
  26299. });
  26300. file.saveUtf8File(bundlesConfigOutFile, text);
  26301. }
  26302. }
  26303. //If removeCombined in play, remove any empty directories that
  26304. //may now exist because of its use
  26305. if (config.removeCombined && !config.out && config.dir) {
  26306. file.deleteEmptyDirs(config.dir);
  26307. }
  26308. //Do other optimizations.
  26309. if (config.out && !config.cssIn) {
  26310. //Just need to worry about one JS file.
  26311. fileName = config.modules[0]._buildPath;
  26312. if (fileName === 'FUNCTION') {
  26313. outOrigSourceMap = config.modules[0]._buildSourceMap;
  26314. config._buildSourceMap = outOrigSourceMap;
  26315. config.modules[0]._buildText = optimize.js((config.modules[0].name ||
  26316. config.modules[0].include[0] ||
  26317. fileName) + '.build.js',
  26318. config.modules[0]._buildText,
  26319. null,
  26320. config);
  26321. if (config._buildSourceMap && config._buildSourceMap !== outOrigSourceMap) {
  26322. config.modules[0]._buildSourceMap = config._buildSourceMap;
  26323. config._buildSourceMap = null;
  26324. }
  26325. } else {
  26326. optimize.jsFile(fileName, null, fileName, config);
  26327. }
  26328. } else if (!config.cssIn) {
  26329. //Normal optimizations across modules.
  26330. //JS optimizations.
  26331. fileNames = file.getFilteredFileList(config.dir, /\.js$/, true);
  26332. fileNames.forEach(function (fileName) {
  26333. var cfg, override, moduleIndex;
  26334. //Generate the module name from the config.dir root.
  26335. moduleName = fileName.replace(config.dir, '');
  26336. //Get rid of the extension
  26337. moduleName = moduleName.substring(0, moduleName.length - 3);
  26338. //If there is an override for a specific layer build module,
  26339. //and this file is that module, mix in the override for use
  26340. //by optimize.jsFile.
  26341. moduleIndex = getOwn(config._buildPathToModuleIndex, fileName);
  26342. //Normalize, since getOwn could have returned undefined
  26343. moduleIndex = moduleIndex === 0 || moduleIndex > 0 ? moduleIndex : -1;
  26344. //Try to avoid extra work if the other files do not need to
  26345. //be read. Build layers should be processed at the very
  26346. //least for optimization.
  26347. if (moduleIndex > -1 || !config.skipDirOptimize ||
  26348. config.normalizeDirDefines === "all" ||
  26349. config.cjsTranslate) {
  26350. //Convert the file to transport format, but without a name
  26351. //inserted (by passing null for moduleName) since the files are
  26352. //standalone, one module per file.
  26353. fileContents = file.readFile(fileName);
  26354. //For builds, if wanting cjs translation, do it now, so that
  26355. //the individual modules can be loaded cross domain via
  26356. //plain script tags.
  26357. if (config.cjsTranslate &&
  26358. (!config.shim || !lang.hasProp(config.shim, moduleName))) {
  26359. fileContents = commonJs.convert(fileName, fileContents);
  26360. }
  26361. if (moduleIndex === -1) {
  26362. if (config.onBuildRead) {
  26363. fileContents = config.onBuildRead(moduleName,
  26364. fileName,
  26365. fileContents);
  26366. }
  26367. //Only do transport normalization if this is not a build
  26368. //layer (since it was already normalized) and if
  26369. //normalizeDirDefines indicated all should be done.
  26370. if (config.normalizeDirDefines === "all") {
  26371. fileContents = build.toTransport(config.namespace,
  26372. null,
  26373. fileName,
  26374. fileContents);
  26375. }
  26376. if (config.onBuildWrite) {
  26377. fileContents = config.onBuildWrite(moduleName,
  26378. fileName,
  26379. fileContents);
  26380. }
  26381. }
  26382. override = moduleIndex > -1 ?
  26383. config.modules[moduleIndex].override : null;
  26384. if (override) {
  26385. cfg = build.createOverrideConfig(config, override);
  26386. } else {
  26387. cfg = config;
  26388. }
  26389. if (moduleIndex > -1 || !config.skipDirOptimize) {
  26390. optimize.jsFile(fileName, fileContents, fileName, cfg, pluginCollector);
  26391. }
  26392. }
  26393. });
  26394. //Normalize all the plugin resources.
  26395. context = require.s.contexts._;
  26396. for (moduleName in pluginCollector) {
  26397. if (hasProp(pluginCollector, moduleName)) {
  26398. parentModuleMap = context.makeModuleMap(moduleName);
  26399. resources = pluginCollector[moduleName];
  26400. for (i = 0; i < resources.length; i++) {
  26401. resource = resources[i];
  26402. moduleMap = context.makeModuleMap(resource, parentModuleMap);
  26403. if (falseProp(context.plugins, moduleMap.prefix)) {
  26404. //Set the value in context.plugins so it
  26405. //will be evaluated as a full plugin.
  26406. context.plugins[moduleMap.prefix] = true;
  26407. //Do not bother if the plugin is not available.
  26408. if (!file.exists(require.toUrl(moduleMap.prefix + '.js'))) {
  26409. continue;
  26410. }
  26411. //Rely on the require in the build environment
  26412. //to be synchronous
  26413. context.require([moduleMap.prefix]);
  26414. //Now that the plugin is loaded, redo the moduleMap
  26415. //since the plugin will need to normalize part of the path.
  26416. moduleMap = context.makeModuleMap(resource, parentModuleMap);
  26417. }
  26418. //Only bother with plugin resources that can be handled
  26419. //processed by the plugin, via support of the writeFile
  26420. //method.
  26421. if (falseProp(pluginProcessed, moduleMap.id)) {
  26422. //Only do the work if the plugin was really loaded.
  26423. //Using an internal access because the file may
  26424. //not really be loaded.
  26425. plugin = getOwn(context.defined, moduleMap.prefix);
  26426. if (plugin && plugin.writeFile) {
  26427. plugin.writeFile(
  26428. moduleMap.prefix,
  26429. moduleMap.name,
  26430. require,
  26431. makeWriteFile(
  26432. config.namespace
  26433. ),
  26434. context.config
  26435. );
  26436. }
  26437. pluginProcessed[moduleMap.id] = true;
  26438. }
  26439. }
  26440. }
  26441. }
  26442. //console.log('PLUGIN COLLECTOR: ' + JSON.stringify(pluginCollector, null, " "));
  26443. //All module layers are done, write out the build.txt file.
  26444. if (config.writeBuildTxt) {
  26445. file.saveUtf8File(config.dir + "build.txt", buildFileContents);
  26446. }
  26447. }
  26448. //If just have one CSS file to optimize, do that here.
  26449. if (config.cssIn) {
  26450. buildFileContents += optimize.cssFile(config.cssIn, config.out, config).buildText;
  26451. }
  26452. if (typeof config.out === 'function') {
  26453. config.out(config.modules[0]._buildText, config.modules[0]._buildSourceMap);
  26454. }
  26455. //Print out what was built into which layers.
  26456. if (buildFileContents) {
  26457. logger.info(buildFileContents);
  26458. return buildFileContents;
  26459. }
  26460. return '';
  26461. });
  26462. };
  26463. /**
  26464. * Converts command line args like "paths.foo=../some/path"
  26465. * result.paths = { foo: '../some/path' } where prop = paths,
  26466. * name = paths.foo and value = ../some/path, so it assumes the
  26467. * name=value splitting has already happened.
  26468. */
  26469. function stringDotToObj(result, name, value) {
  26470. var parts = name.split('.');
  26471. parts.forEach(function (prop, i) {
  26472. if (i === parts.length - 1) {
  26473. result[prop] = value;
  26474. } else {
  26475. if (falseProp(result, prop)) {
  26476. result[prop] = {};
  26477. }
  26478. result = result[prop];
  26479. }
  26480. });
  26481. }
  26482. build.objProps = {
  26483. paths: true,
  26484. wrap: true,
  26485. pragmas: true,
  26486. pragmasOnSave: true,
  26487. has: true,
  26488. hasOnSave: true,
  26489. uglify: true,
  26490. uglify2: true,
  26491. closure: true,
  26492. map: true,
  26493. throwWhen: true
  26494. };
  26495. build.hasDotPropMatch = function (prop) {
  26496. var dotProp,
  26497. index = prop.indexOf('.');
  26498. if (index !== -1) {
  26499. dotProp = prop.substring(0, index);
  26500. return hasProp(build.objProps, dotProp);
  26501. }
  26502. return false;
  26503. };
  26504. /**
  26505. * Converts an array that has String members of "name=value"
  26506. * into an object, where the properties on the object are the names in the array.
  26507. * Also converts the strings "true" and "false" to booleans for the values.
  26508. * member name/value pairs, and converts some comma-separated lists into
  26509. * arrays.
  26510. * @param {Array} ary
  26511. */
  26512. build.convertArrayToObject = function (ary) {
  26513. var result = {}, i, separatorIndex, prop, value,
  26514. needArray = {
  26515. "include": true,
  26516. "exclude": true,
  26517. "excludeShallow": true,
  26518. "insertRequire": true,
  26519. "stubModules": true,
  26520. "deps": true,
  26521. "mainConfigFile": true,
  26522. "wrap.startFile": true,
  26523. "wrap.endFile": true
  26524. };
  26525. for (i = 0; i < ary.length; i++) {
  26526. separatorIndex = ary[i].indexOf("=");
  26527. if (separatorIndex === -1) {
  26528. throw "Malformed name/value pair: [" + ary[i] + "]. Format should be name=value";
  26529. }
  26530. value = ary[i].substring(separatorIndex + 1, ary[i].length);
  26531. if (value === "true") {
  26532. value = true;
  26533. } else if (value === "false") {
  26534. value = false;
  26535. }
  26536. prop = ary[i].substring(0, separatorIndex);
  26537. //Convert to array if necessary
  26538. if (getOwn(needArray, prop)) {
  26539. value = value.split(",");
  26540. }
  26541. if (build.hasDotPropMatch(prop)) {
  26542. stringDotToObj(result, prop, value);
  26543. } else {
  26544. result[prop] = value;
  26545. }
  26546. }
  26547. return result; //Object
  26548. };
  26549. build.makeAbsPath = function (path, absFilePath) {
  26550. if (!absFilePath) {
  26551. return path;
  26552. }
  26553. //Add abspath if necessary. If path starts with a slash or has a colon,
  26554. //then already is an abolute path.
  26555. if (path.indexOf('/') !== 0 && path.indexOf(':') === -1) {
  26556. path = absFilePath +
  26557. (absFilePath.charAt(absFilePath.length - 1) === '/' ? '' : '/') +
  26558. path;
  26559. path = file.normalize(path);
  26560. }
  26561. return path.replace(lang.backSlashRegExp, '/');
  26562. };
  26563. build.makeAbsObject = function (props, obj, absFilePath) {
  26564. var i, prop;
  26565. if (obj) {
  26566. for (i = 0; i < props.length; i++) {
  26567. prop = props[i];
  26568. if (hasProp(obj, prop) && typeof obj[prop] === 'string') {
  26569. obj[prop] = build.makeAbsPath(obj[prop], absFilePath);
  26570. }
  26571. }
  26572. }
  26573. };
  26574. /**
  26575. * For any path in a possible config, make it absolute relative
  26576. * to the absFilePath passed in.
  26577. */
  26578. build.makeAbsConfig = function (config, absFilePath) {
  26579. var props, prop, i;
  26580. props = ["appDir", "dir", "baseUrl"];
  26581. for (i = 0; i < props.length; i++) {
  26582. prop = props[i];
  26583. if (getOwn(config, prop)) {
  26584. //Add abspath if necessary, make sure these paths end in
  26585. //slashes
  26586. if (prop === "baseUrl") {
  26587. config.originalBaseUrl = config.baseUrl;
  26588. if (config.appDir) {
  26589. //If baseUrl with an appDir, the baseUrl is relative to
  26590. //the appDir, *not* the absFilePath. appDir and dir are
  26591. //made absolute before baseUrl, so this will work.
  26592. config.baseUrl = build.makeAbsPath(config.originalBaseUrl, config.appDir);
  26593. } else {
  26594. //The dir output baseUrl is same as regular baseUrl, both
  26595. //relative to the absFilePath.
  26596. config.baseUrl = build.makeAbsPath(config[prop], absFilePath);
  26597. }
  26598. } else {
  26599. config[prop] = build.makeAbsPath(config[prop], absFilePath);
  26600. }
  26601. config[prop] = endsWithSlash(config[prop]);
  26602. }
  26603. }
  26604. build.makeAbsObject((config.out === "stdout" ? ["cssIn"] : ["out", "cssIn"]),
  26605. config, absFilePath);
  26606. build.makeAbsObject(["startFile", "endFile"], config.wrap, absFilePath);
  26607. build.makeAbsObject(["externExportsPath"], config.closure, absFilePath);
  26608. };
  26609. /**
  26610. * Creates a relative path to targetPath from refPath.
  26611. * Only deals with file paths, not folders. If folders,
  26612. * make sure paths end in a trailing '/'.
  26613. */
  26614. build.makeRelativeFilePath = function (refPath, targetPath) {
  26615. var i, dotLength, finalParts, length, targetParts, targetName,
  26616. refParts = refPath.split('/'),
  26617. hasEndSlash = endsWithSlashRegExp.test(targetPath),
  26618. dotParts = [];
  26619. targetPath = file.normalize(targetPath);
  26620. if (hasEndSlash && !endsWithSlashRegExp.test(targetPath)) {
  26621. targetPath += '/';
  26622. }
  26623. targetParts = targetPath.split('/');
  26624. //Pull off file name
  26625. targetName = targetParts.pop();
  26626. //Also pop off the ref file name to make the matches against
  26627. //targetParts equivalent.
  26628. refParts.pop();
  26629. length = refParts.length;
  26630. for (i = 0; i < length; i += 1) {
  26631. if (refParts[i] !== targetParts[i]) {
  26632. break;
  26633. }
  26634. }
  26635. //Now i is the index in which they diverge.
  26636. finalParts = targetParts.slice(i);
  26637. dotLength = length - i;
  26638. for (i = 0; i > -1 && i < dotLength; i += 1) {
  26639. dotParts.push('..');
  26640. }
  26641. return dotParts.join('/') + (dotParts.length ? '/' : '') +
  26642. finalParts.join('/') + (finalParts.length ? '/' : '') +
  26643. targetName;
  26644. };
  26645. build.nestedMix = {
  26646. paths: true,
  26647. has: true,
  26648. hasOnSave: true,
  26649. pragmas: true,
  26650. pragmasOnSave: true
  26651. };
  26652. /**
  26653. * Mixes additional source config into target config, and merges some
  26654. * nested config, like paths, correctly.
  26655. */
  26656. function mixConfig(target, source, skipArrays) {
  26657. var prop, value, isArray, targetValue;
  26658. for (prop in source) {
  26659. if (hasProp(source, prop)) {
  26660. //If the value of the property is a plain object, then
  26661. //allow a one-level-deep mixing of it.
  26662. value = source[prop];
  26663. isArray = lang.isArray(value);
  26664. if (typeof value === 'object' && value &&
  26665. !isArray && !lang.isFunction(value) &&
  26666. !lang.isRegExp(value)) {
  26667. // TODO: need to generalize this work, maybe also reuse
  26668. // the work done in requirejs configure, perhaps move to
  26669. // just a deep copy/merge overall. However, given the
  26670. // amount of observable change, wait for a dot release.
  26671. // This change is in relation to #645
  26672. if (prop === 'map') {
  26673. if (!target.map) {
  26674. target.map = {};
  26675. }
  26676. lang.deepMix(target.map, source.map);
  26677. } else {
  26678. target[prop] = lang.mixin({}, target[prop], value, true);
  26679. }
  26680. } else if (isArray) {
  26681. if (!skipArrays) {
  26682. // Some config, like packages, are arrays. For those,
  26683. // just merge the results.
  26684. targetValue = target[prop];
  26685. if (lang.isArray(targetValue)) {
  26686. target[prop] = targetValue.concat(value);
  26687. } else {
  26688. target[prop] = value;
  26689. }
  26690. }
  26691. } else {
  26692. target[prop] = value;
  26693. }
  26694. }
  26695. }
  26696. //Set up log level since it can affect if errors are thrown
  26697. //or caught and passed to errbacks while doing config setup.
  26698. if (lang.hasProp(target, 'logLevel')) {
  26699. logger.logLevel(target.logLevel);
  26700. }
  26701. }
  26702. /**
  26703. * Converts a wrap.startFile or endFile to be start/end as a string.
  26704. * the startFile/endFile values can be arrays.
  26705. */
  26706. function flattenWrapFile(config, keyName, absFilePath) {
  26707. var wrap = config.wrap,
  26708. keyFileName = keyName + 'File',
  26709. keyMapName = '__' + keyName + 'Map';
  26710. if (typeof wrap[keyName] !== 'string' && wrap[keyFileName]) {
  26711. wrap[keyName] = '';
  26712. if (typeof wrap[keyFileName] === 'string') {
  26713. wrap[keyFileName] = [wrap[keyFileName]];
  26714. }
  26715. wrap[keyMapName] = [];
  26716. wrap[keyFileName].forEach(function (fileName) {
  26717. var absPath = build.makeAbsPath(fileName, absFilePath),
  26718. fileText = endsWithNewLine(file.readFile(absPath));
  26719. wrap[keyMapName].push(function (fileContents, cfg, sourceMapGenerator) {
  26720. return appendToFileContents(fileContents, fileText, absPath, cfg, null, sourceMapGenerator);
  26721. });
  26722. wrap[keyName] += fileText;
  26723. });
  26724. } else if (wrap[keyName] === null || wrap[keyName] === undefined) {
  26725. //Allow missing one, just set to empty string.
  26726. wrap[keyName] = '';
  26727. } else if (typeof wrap[keyName] === 'string') {
  26728. wrap[keyName] = endsWithNewLine(wrap[keyName]);
  26729. wrap[keyMapName] = [
  26730. function (fileContents, cfg, sourceMapGenerator) {
  26731. var absPath = build.makeAbsPath("config-wrap-" + keyName + "-default.js", absFilePath);
  26732. return appendToFileContents(fileContents, wrap[keyName], absPath, cfg, null, sourceMapGenerator);
  26733. }
  26734. ];
  26735. } else {
  26736. throw new Error('wrap.' + keyName + ' or wrap.' + keyFileName + ' malformed');
  26737. }
  26738. }
  26739. function normalizeWrapConfig(config, absFilePath) {
  26740. //Get any wrap text.
  26741. try {
  26742. if (config.wrap) {
  26743. if (config.wrap === true) {
  26744. //Use default values.
  26745. config.wrap = {
  26746. start: '(function () {\n',
  26747. end: '}());',
  26748. __startMap: [
  26749. function (fileContents, cfg, sourceMapGenerator) {
  26750. return appendToFileContents(fileContents, "(function () {\n",
  26751. build.makeAbsPath("config-wrap-start-default.js",
  26752. absFilePath), cfg, null,
  26753. sourceMapGenerator);
  26754. }
  26755. ],
  26756. __endMap: [
  26757. function (fileContents, cfg, sourceMapGenerator) {
  26758. return appendToFileContents(fileContents, "}());",
  26759. build.makeAbsPath("config-wrap-end-default.js", absFilePath),
  26760. cfg, null, sourceMapGenerator);
  26761. }
  26762. ]
  26763. };
  26764. } else {
  26765. flattenWrapFile(config, 'start', absFilePath);
  26766. flattenWrapFile(config, 'end', absFilePath);
  26767. }
  26768. }
  26769. } catch (wrapError) {
  26770. throw new Error('Malformed wrap config: ' + wrapError.toString());
  26771. }
  26772. }
  26773. /**
  26774. * Creates a config object for an optimization build.
  26775. * It will also read the build profile if it is available, to create
  26776. * the configuration.
  26777. *
  26778. * @param {Object} cfg config options that take priority
  26779. * over defaults and ones in the build file. These options could
  26780. * be from a command line, for instance.
  26781. *
  26782. * @param {Object} the created config object.
  26783. */
  26784. build.createConfig = function (cfg) {
  26785. /*jslint evil: true */
  26786. var buildFileContents, buildFileConfig, mainConfig,
  26787. mainConfigFile, mainConfigPath, buildFile, absFilePath,
  26788. config = {},
  26789. buildBaseConfig = makeBuildBaseConfig();
  26790. //Make sure all paths are relative to current directory.
  26791. absFilePath = file.absPath('.');
  26792. build.makeAbsConfig(cfg, absFilePath);
  26793. build.makeAbsConfig(buildBaseConfig, absFilePath);
  26794. lang.mixin(config, buildBaseConfig);
  26795. lang.mixin(config, cfg, true);
  26796. //Set up log level early since it can affect if errors are thrown
  26797. //or caught and passed to errbacks, even while constructing config.
  26798. if (lang.hasProp(config, 'logLevel')) {
  26799. logger.logLevel(config.logLevel);
  26800. }
  26801. if (config.buildFile) {
  26802. //A build file exists, load it to get more config.
  26803. buildFile = file.absPath(config.buildFile);
  26804. //Find the build file, and make sure it exists, if this is a build
  26805. //that has a build profile, and not just command line args with an in=path
  26806. if (!file.exists(buildFile)) {
  26807. throw new Error("ERROR: build file does not exist: " + buildFile);
  26808. }
  26809. absFilePath = config.baseUrl = file.absPath(file.parent(buildFile));
  26810. //Load build file options.
  26811. buildFileContents = file.readFile(buildFile);
  26812. try {
  26813. //Be a bit lenient in the file ending in a ; or ending with
  26814. //a //# sourceMappingUrl comment, mostly for compiled languages
  26815. //that create a config, like typescript.
  26816. buildFileContents = buildFileContents
  26817. .replace(/\/\/\#[^\n\r]+[\n\r]*$/, '')
  26818. .trim()
  26819. .replace(/;$/, '');
  26820. buildFileConfig = eval("(" + buildFileContents + ")");
  26821. build.makeAbsConfig(buildFileConfig, absFilePath);
  26822. //Mix in the config now so that items in mainConfigFile can
  26823. //be resolved relative to them if necessary, like if appDir
  26824. //is set here, but the baseUrl is in mainConfigFile. Will
  26825. //re-mix in the same build config later after mainConfigFile
  26826. //is processed, since build config should take priority.
  26827. mixConfig(config, buildFileConfig);
  26828. } catch (e) {
  26829. throw new Error("Build file " + buildFile + " is malformed: " + e);
  26830. }
  26831. }
  26832. mainConfigFile = config.mainConfigFile || (buildFileConfig && buildFileConfig.mainConfigFile);
  26833. if (mainConfigFile) {
  26834. if (typeof mainConfigFile === 'string') {
  26835. mainConfigFile = [mainConfigFile];
  26836. }
  26837. mainConfigFile.forEach(function (configFile) {
  26838. configFile = build.makeAbsPath(configFile, absFilePath);
  26839. if (!file.exists(configFile)) {
  26840. throw new Error(configFile + ' does not exist.');
  26841. }
  26842. try {
  26843. mainConfig = parse.findConfig(file.readFile(configFile)).config;
  26844. } catch (configError) {
  26845. throw new Error('The config in mainConfigFile ' +
  26846. configFile +
  26847. ' cannot be used because it cannot be evaluated' +
  26848. ' correctly while running in the optimizer. Try only' +
  26849. ' using a config that is also valid JSON, or do not use' +
  26850. ' mainConfigFile and instead copy the config values needed' +
  26851. ' into a build file or command line arguments given to the optimizer.\n' +
  26852. 'Source error from parsing: ' + configFile + ': ' + configError);
  26853. }
  26854. if (mainConfig) {
  26855. mainConfigPath = configFile.substring(0, configFile.lastIndexOf('/'));
  26856. //Add in some existing config, like appDir, since they can be
  26857. //used inside the configFile -- paths and baseUrl are
  26858. //relative to them.
  26859. if (config.appDir && !mainConfig.appDir) {
  26860. mainConfig.appDir = config.appDir;
  26861. }
  26862. //If no baseUrl, then use the directory holding the main config.
  26863. if (!mainConfig.baseUrl) {
  26864. mainConfig.baseUrl = mainConfigPath;
  26865. }
  26866. build.makeAbsConfig(mainConfig, mainConfigPath);
  26867. mixConfig(config, mainConfig);
  26868. }
  26869. });
  26870. }
  26871. //Mix in build file config, but only after mainConfig has been mixed in.
  26872. //Since this is a re-application, skip array merging.
  26873. if (buildFileConfig) {
  26874. mixConfig(config, buildFileConfig, true);
  26875. }
  26876. //Re-apply the override config values. Command line
  26877. //args should take precedence over build file values.
  26878. //Since this is a re-application, skip array merging.
  26879. mixConfig(config, cfg, true);
  26880. //Fix paths to full paths so that they can be adjusted consistently
  26881. //lately to be in the output area.
  26882. lang.eachProp(config.paths, function (value, prop) {
  26883. if (lang.isArray(value)) {
  26884. throw new Error('paths fallback not supported in optimizer. ' +
  26885. 'Please provide a build config path override ' +
  26886. 'for ' + prop);
  26887. }
  26888. config.paths[prop] = build.makeAbsPath(value, config.baseUrl);
  26889. });
  26890. //Set final output dir
  26891. if (hasProp(config, "baseUrl")) {
  26892. if (config.appDir) {
  26893. if (!config.originalBaseUrl) {
  26894. throw new Error('Please set a baseUrl in the build config');
  26895. }
  26896. config.dirBaseUrl = build.makeAbsPath(config.originalBaseUrl, config.dir);
  26897. } else {
  26898. config.dirBaseUrl = config.dir || config.baseUrl;
  26899. }
  26900. //Make sure dirBaseUrl ends in a slash, since it is
  26901. //concatenated with other strings.
  26902. config.dirBaseUrl = endsWithSlash(config.dirBaseUrl);
  26903. }
  26904. if (config.bundlesConfigOutFile) {
  26905. if (!config.dir) {
  26906. throw new Error('bundlesConfigOutFile can only be used with optimizations ' +
  26907. 'that use "dir".');
  26908. }
  26909. config.bundlesConfigOutFile = build.makeAbsPath(config.bundlesConfigOutFile, config.dir);
  26910. }
  26911. //If out=stdout, write output to STDOUT instead of a file.
  26912. if (config.out && config.out === 'stdout') {
  26913. config.out = function (content) {
  26914. var e = env.get();
  26915. if (e === 'rhino') {
  26916. var out = new java.io.PrintStream(java.lang.System.out, true, 'UTF-8');
  26917. out.println(content);
  26918. } else if (e === 'node') {
  26919. process.stdout.write(content, 'utf8');
  26920. } else {
  26921. console.log(content);
  26922. }
  26923. };
  26924. }
  26925. //Check for errors in config
  26926. if (config.main) {
  26927. throw new Error('"main" passed as an option, but the ' +
  26928. 'supported option is called "name".');
  26929. }
  26930. if (config.out && !config.name && !config.modules && !config.include &&
  26931. !config.cssIn) {
  26932. throw new Error('Missing either a "name", "include" or "modules" ' +
  26933. 'option');
  26934. }
  26935. if (config.cssIn) {
  26936. if (config.dir || config.appDir) {
  26937. throw new Error('cssIn is only for the output of single file ' +
  26938. 'CSS optimizations and is not compatible with "dir" or "appDir" configuration.');
  26939. }
  26940. if (!config.out) {
  26941. throw new Error('"out" option missing.');
  26942. }
  26943. }
  26944. if (!config.cssIn && !config.baseUrl) {
  26945. //Just use the current directory as the baseUrl
  26946. config.baseUrl = './';
  26947. }
  26948. if (!config.out && !config.dir) {
  26949. throw new Error('Missing either an "out" or "dir" config value. ' +
  26950. 'If using "appDir" for a full project optimization, ' +
  26951. 'use "dir". If you want to optimize to one file, ' +
  26952. 'use "out".');
  26953. }
  26954. if (config.appDir && config.out) {
  26955. throw new Error('"appDir" is not compatible with "out". Use "dir" ' +
  26956. 'instead. appDir is used to copy whole projects, ' +
  26957. 'where "out" with "baseUrl" is used to just ' +
  26958. 'optimize to one file.');
  26959. }
  26960. if (config.out && config.dir) {
  26961. throw new Error('The "out" and "dir" options are incompatible.' +
  26962. ' Use "out" if you are targeting a single file' +
  26963. ' for optimization, and "dir" if you want the appDir' +
  26964. ' or baseUrl directories optimized.');
  26965. }
  26966. if (config.dir) {
  26967. // Make sure the output dir is not set to a parent of the
  26968. // source dir or the same dir, as it will result in source
  26969. // code deletion.
  26970. if (!config.allowSourceOverwrites && (config.dir === config.baseUrl ||
  26971. config.dir === config.appDir ||
  26972. (config.baseUrl && build.makeRelativeFilePath(config.dir,
  26973. config.baseUrl).indexOf('..') !== 0) ||
  26974. (config.appDir &&
  26975. build.makeRelativeFilePath(config.dir, config.appDir).indexOf('..') !== 0))) {
  26976. throw new Error('"dir" is set to a parent or same directory as' +
  26977. ' "appDir" or "baseUrl". This can result in' +
  26978. ' the deletion of source code. Stopping. If' +
  26979. ' you want to allow possible overwriting of' +
  26980. ' source code, set "allowSourceOverwrites"' +
  26981. ' to true in the build config, but do so at' +
  26982. ' your own risk. In that case, you may want' +
  26983. ' to also set "keepBuildDir" to true.');
  26984. }
  26985. }
  26986. if (config.insertRequire && !lang.isArray(config.insertRequire)) {
  26987. throw new Error('insertRequire should be a list of module IDs' +
  26988. ' to insert in to a require([]) call.');
  26989. }
  26990. //Support older configs with uglify2 settings, but now that uglify1 has
  26991. //been removed, just translate it to 'uglify' settings.
  26992. if (config.optimize === 'uglify2') {
  26993. config.optimize = 'uglify';
  26994. }
  26995. if (config.uglify2) {
  26996. config.uglify = config.uglify2;
  26997. delete config.uglify2;
  26998. }
  26999. if (config.generateSourceMaps) {
  27000. if (config.preserveLicenseComments && !(config.optimize === 'none' || config.optimize === 'uglify')) {
  27001. throw new Error('Cannot use preserveLicenseComments and ' +
  27002. 'generateSourceMaps together, unless optimize is set ' +
  27003. 'to \'uglify\'. Either explicitly set preserveLicenseComments ' +
  27004. 'to false (default is true) or turn off generateSourceMaps. ' +
  27005. 'If you want source maps with license comments, see: ' +
  27006. 'http://requirejs.org/docs/errors.html#sourcemapcomments');
  27007. } else if (config.optimize !== 'none' &&
  27008. config.optimize !== 'closure' &&
  27009. config.optimize !== 'uglify') {
  27010. //Allow optimize: none to pass, since it is useful when toggling
  27011. //minification on and off to debug something, and it implicitly
  27012. //works, since it does not need a source map.
  27013. throw new Error('optimize: "' + config.optimize +
  27014. '" does not support generateSourceMaps.');
  27015. }
  27016. }
  27017. if ((config.name || config.include) && !config.modules) {
  27018. //Just need to build one file, but may be part of a whole appDir/
  27019. //baseUrl copy, but specified on the command line, so cannot do
  27020. //the modules array setup. So create a modules section in that
  27021. //case.
  27022. config.modules = [
  27023. {
  27024. name: config.name,
  27025. out: config.out,
  27026. create: config.create,
  27027. include: config.include,
  27028. exclude: config.exclude,
  27029. excludeShallow: config.excludeShallow,
  27030. insertRequire: config.insertRequire,
  27031. stubModules: config.stubModules
  27032. }
  27033. ];
  27034. delete config.stubModules;
  27035. } else if (config.modules && config.out) {
  27036. throw new Error('If the "modules" option is used, then there ' +
  27037. 'should be a "dir" option set and "out" should ' +
  27038. 'not be used since "out" is only for single file ' +
  27039. 'optimization output.');
  27040. } else if (config.modules && config.name) {
  27041. throw new Error('"name" and "modules" options are incompatible. ' +
  27042. 'Either use "name" if doing a single file ' +
  27043. 'optimization, or "modules" if you want to target ' +
  27044. 'more than one file for optimization.');
  27045. }
  27046. if (config.out && !config.cssIn) {
  27047. //Just one file to optimize.
  27048. //Does not have a build file, so set up some defaults.
  27049. //Optimizing CSS should not be allowed, unless explicitly
  27050. //asked for on command line. In that case the only task is
  27051. //to optimize a CSS file.
  27052. if (!cfg.optimizeCss) {
  27053. config.optimizeCss = "none";
  27054. }
  27055. }
  27056. //Normalize cssPrefix
  27057. if (config.cssPrefix) {
  27058. //Make sure cssPrefix ends in a slash
  27059. config.cssPrefix = endsWithSlash(config.cssPrefix);
  27060. } else {
  27061. config.cssPrefix = '';
  27062. }
  27063. //Cycle through modules and normalize
  27064. if (config.modules && config.modules.length) {
  27065. config.modules.forEach(function (mod) {
  27066. if (lang.isArray(mod) || typeof mod === 'string' || !mod) {
  27067. throw new Error('modules config item is malformed: it should' +
  27068. ' be an object with a \'name\' property.');
  27069. }
  27070. //Combine any local stubModules with global values.
  27071. if (config.stubModules) {
  27072. mod.stubModules = config.stubModules.concat(mod.stubModules || []);
  27073. }
  27074. //Create a hash lookup for the stubModules config to make lookup
  27075. //cheaper later.
  27076. if (mod.stubModules) {
  27077. mod.stubModules._byName = {};
  27078. mod.stubModules.forEach(function (id) {
  27079. mod.stubModules._byName[id] = true;
  27080. });
  27081. }
  27082. // Legacy command support, which allowed a single string ID
  27083. // for include.
  27084. if (typeof mod.include === 'string') {
  27085. mod.include = [mod.include];
  27086. }
  27087. //Allow wrap config in overrides, but normalize it.
  27088. if (mod.override) {
  27089. normalizeWrapConfig(mod.override, absFilePath);
  27090. }
  27091. });
  27092. }
  27093. normalizeWrapConfig(config, absFilePath);
  27094. //Do final input verification
  27095. if (config.context) {
  27096. throw new Error('The build argument "context" is not supported' +
  27097. ' in a build. It should only be used in web' +
  27098. ' pages.');
  27099. }
  27100. //Set up normalizeDirDefines. If not explicitly set, if optimize "none",
  27101. //set to "skip" otherwise set to "all".
  27102. if (!hasProp(config, 'normalizeDirDefines')) {
  27103. if (config.optimize === 'none' || config.skipDirOptimize) {
  27104. config.normalizeDirDefines = 'skip';
  27105. } else {
  27106. config.normalizeDirDefines = 'all';
  27107. }
  27108. }
  27109. //Set file.fileExclusionRegExp if desired
  27110. if (hasProp(config, 'fileExclusionRegExp')) {
  27111. if (typeof config.fileExclusionRegExp === "string") {
  27112. file.exclusionRegExp = new RegExp(config.fileExclusionRegExp);
  27113. } else {
  27114. file.exclusionRegExp = config.fileExclusionRegExp;
  27115. }
  27116. } else if (hasProp(config, 'dirExclusionRegExp')) {
  27117. //Set file.dirExclusionRegExp if desired, this is the old
  27118. //name for fileExclusionRegExp before 1.0.2. Support for backwards
  27119. //compatibility
  27120. file.exclusionRegExp = config.dirExclusionRegExp;
  27121. }
  27122. //Track the deps, but in a different key, so that they are not loaded
  27123. //as part of config seeding before all config is in play (#648). Was
  27124. //going to merge this in with "include", but include is added after
  27125. //the "name" target. To preserve what r.js has done previously, make
  27126. //sure "deps" comes before the "name".
  27127. if (config.deps) {
  27128. config._depsInclude = config.deps;
  27129. }
  27130. //Remove things that may cause problems in the build.
  27131. //deps already merged above
  27132. delete config.deps;
  27133. delete config.jQuery;
  27134. delete config.enforceDefine;
  27135. delete config.urlArgs;
  27136. return config;
  27137. };
  27138. /**
  27139. * finds the module being built/optimized with the given moduleName,
  27140. * or returns null.
  27141. * @param {String} moduleName
  27142. * @param {Array} modules
  27143. * @returns {Object} the module object from the build profile, or null.
  27144. */
  27145. build.findBuildModule = function (moduleName, modules) {
  27146. var i, module;
  27147. for (i = 0; i < modules.length; i++) {
  27148. module = modules[i];
  27149. if (module.name === moduleName) {
  27150. return module;
  27151. }
  27152. }
  27153. return null;
  27154. };
  27155. /**
  27156. * Removes a module name and path from a layer, if it is supposed to be
  27157. * excluded from the layer.
  27158. * @param {String} moduleName the name of the module
  27159. * @param {String} path the file path for the module
  27160. * @param {Object} layer the layer to remove the module/path from
  27161. */
  27162. build.removeModulePath = function (module, path, layer) {
  27163. var index = layer.buildFilePaths.indexOf(path);
  27164. if (index !== -1) {
  27165. layer.buildFilePaths.splice(index, 1);
  27166. }
  27167. };
  27168. /**
  27169. * Uses the module build config object to trace the dependencies for the
  27170. * given module.
  27171. *
  27172. * @param {Object} module the module object from the build config info.
  27173. * @param {Object} config the build config object.
  27174. * @param {Object} [baseLoaderConfig] the base loader config to use for env resets.
  27175. *
  27176. * @returns {Object} layer information about what paths and modules should
  27177. * be in the flattened module.
  27178. */
  27179. build.traceDependencies = function (module, config, baseLoaderConfig) {
  27180. var include, override, layer, context, oldContext,
  27181. rawTextByIds,
  27182. syncChecks = {
  27183. rhino: true,
  27184. node: true,
  27185. xpconnect: true
  27186. },
  27187. deferred = prim();
  27188. //Reset some state set up in requirePatch.js, and clean up require's
  27189. //current context.
  27190. oldContext = require._buildReset();
  27191. //Grab the reset layer and context after the reset, but keep the
  27192. //old config to reuse in the new context.
  27193. layer = require._layer;
  27194. context = layer.context;
  27195. //Put back basic config, use a fresh object for it.
  27196. if (baseLoaderConfig) {
  27197. require(copyConfig(baseLoaderConfig));
  27198. }
  27199. logger.trace("\nTracing dependencies for: " + (module.name ||
  27200. (typeof module.out === 'function' ? 'FUNCTION' : module.out)));
  27201. include = config._depsInclude || [];
  27202. include = include.concat(module.name && !module.create ? [module.name] : []);
  27203. if (module.include) {
  27204. include = include.concat(module.include);
  27205. }
  27206. //If there are overrides to basic config, set that up now.;
  27207. if (module.override) {
  27208. if (baseLoaderConfig) {
  27209. override = build.createOverrideConfig(baseLoaderConfig, module.override);
  27210. } else {
  27211. override = copyConfig(module.override);
  27212. }
  27213. require(override);
  27214. }
  27215. //Now, populate the rawText cache with any values explicitly passed in
  27216. //via config.
  27217. rawTextByIds = require.s.contexts._.config.rawText;
  27218. if (rawTextByIds) {
  27219. lang.eachProp(rawTextByIds, function (contents, id) {
  27220. var url = require.toUrl(id) + '.js';
  27221. require._cachedRawText[url] = contents;
  27222. });
  27223. }
  27224. //Configure the callbacks to be called.
  27225. deferred.reject.__requireJsBuild = true;
  27226. //Use a wrapping function so can check for errors.
  27227. function includeFinished(value) {
  27228. //If a sync build environment, check for errors here, instead of
  27229. //in the then callback below, since some errors, like two IDs pointed
  27230. //to same URL but only one anon ID will leave the loader in an
  27231. //unresolved state since a setTimeout cannot be used to check for
  27232. //timeout.
  27233. var hasError = false;
  27234. if (syncChecks[env.get()]) {
  27235. try {
  27236. build.checkForErrors(context, layer);
  27237. } catch (e) {
  27238. hasError = true;
  27239. deferred.reject(e);
  27240. }
  27241. }
  27242. if (!hasError) {
  27243. deferred.resolve(value);
  27244. }
  27245. }
  27246. includeFinished.__requireJsBuild = true;
  27247. //Figure out module layer dependencies by calling require to do the work.
  27248. require(include, includeFinished, deferred.reject);
  27249. // If a sync env, then with the "two IDs to same anon module path"
  27250. // issue, the require never completes, need to check for errors
  27251. // here.
  27252. if (syncChecks[env.get()]) {
  27253. build.checkForErrors(context, layer);
  27254. }
  27255. return deferred.promise.then(function () {
  27256. //Reset config
  27257. if (module.override && baseLoaderConfig) {
  27258. require(copyConfig(baseLoaderConfig));
  27259. }
  27260. build.checkForErrors(context, layer);
  27261. return layer;
  27262. });
  27263. };
  27264. build.checkForErrors = function (context, layer) {
  27265. //Check to see if it all loaded. If not, then throw, and give
  27266. //a message on what is left.
  27267. var id, prop, mod, idParts, pluginId, pluginResources,
  27268. errMessage = '',
  27269. failedPluginMap = {},
  27270. failedPluginIds = [],
  27271. errIds = [],
  27272. errUrlMap = {},
  27273. errUrlConflicts = {},
  27274. hasErrUrl = false,
  27275. hasUndefined = false,
  27276. defined = context.defined,
  27277. registry = context.registry;
  27278. function populateErrUrlMap(id, errUrl, skipNew) {
  27279. // Loader plugins do not have an errUrl, so skip them.
  27280. if (!errUrl) {
  27281. return;
  27282. }
  27283. if (!skipNew) {
  27284. errIds.push(id);
  27285. }
  27286. if (errUrlMap[errUrl]) {
  27287. hasErrUrl = true;
  27288. //This error module has the same URL as another
  27289. //error module, could be misconfiguration.
  27290. if (!errUrlConflicts[errUrl]) {
  27291. errUrlConflicts[errUrl] = [];
  27292. //Store the original module that had the same URL.
  27293. errUrlConflicts[errUrl].push(errUrlMap[errUrl]);
  27294. }
  27295. errUrlConflicts[errUrl].push(id);
  27296. } else if (!skipNew) {
  27297. errUrlMap[errUrl] = id;
  27298. }
  27299. }
  27300. for (id in registry) {
  27301. if (hasProp(registry, id) && id.indexOf('_@r') !== 0) {
  27302. hasUndefined = true;
  27303. mod = getOwn(registry, id);
  27304. idParts = id.split('!');
  27305. pluginId = idParts[0];
  27306. if (id.indexOf('_unnormalized') === -1 && mod && mod.enabled) {
  27307. populateErrUrlMap(id, mod.map.url);
  27308. }
  27309. //Look for plugins that did not call load()
  27310. //But skip plugin IDs that were already inlined and called
  27311. //define() with a name.
  27312. if (!hasProp(layer.modulesWithNames, id) && idParts.length > 1) {
  27313. if (falseProp(failedPluginMap, pluginId)) {
  27314. failedPluginIds.push(pluginId);
  27315. }
  27316. pluginResources = failedPluginMap[pluginId];
  27317. if (!pluginResources) {
  27318. pluginResources = failedPluginMap[pluginId] = [];
  27319. }
  27320. pluginResources.push(id + (mod.error ? ': ' + mod.error : ''));
  27321. }
  27322. }
  27323. }
  27324. // If have some modules that are not defined/stuck in the registry,
  27325. // then check defined modules for URL overlap.
  27326. if (hasUndefined) {
  27327. for (id in defined) {
  27328. if (hasProp(defined, id) && id.indexOf('!') === -1) {
  27329. populateErrUrlMap(id, require.toUrl(id) + '.js', true);
  27330. }
  27331. }
  27332. }
  27333. if (errIds.length || failedPluginIds.length) {
  27334. if (failedPluginIds.length) {
  27335. errMessage += 'Loader plugin' +
  27336. (failedPluginIds.length === 1 ? '' : 's') +
  27337. ' did not call ' +
  27338. 'the load callback in the build:\n' +
  27339. failedPluginIds.map(function (pluginId) {
  27340. var pluginResources = failedPluginMap[pluginId];
  27341. return pluginId + ':\n ' + pluginResources.join('\n ');
  27342. }).join('\n') + '\n';
  27343. }
  27344. errMessage += 'Module loading did not complete for: ' + errIds.join(', ');
  27345. if (hasErrUrl) {
  27346. errMessage += '\nThe following modules share the same URL. This ' +
  27347. 'could be a misconfiguration if that URL only has ' +
  27348. 'one anonymous module in it:';
  27349. for (prop in errUrlConflicts) {
  27350. if (hasProp(errUrlConflicts, prop)) {
  27351. errMessage += '\n' + prop + ': ' +
  27352. errUrlConflicts[prop].join(', ');
  27353. }
  27354. }
  27355. }
  27356. throw new Error(errMessage);
  27357. }
  27358. };
  27359. build.createOverrideConfig = function (config, override) {
  27360. var cfg = copyConfig(config),
  27361. oride = copyConfig(override);
  27362. lang.eachProp(oride, function (value, prop) {
  27363. if (hasProp(build.objProps, prop)) {
  27364. //An object property, merge keys. Start a new object
  27365. //so that source object in config does not get modified.
  27366. cfg[prop] = {};
  27367. lang.mixin(cfg[prop], config[prop], true);
  27368. lang.mixin(cfg[prop], override[prop], true);
  27369. } else {
  27370. cfg[prop] = override[prop];
  27371. }
  27372. });
  27373. return cfg;
  27374. };
  27375. /**
  27376. * Uses the module build config object to create an flattened version
  27377. * of the module, with deep dependencies included.
  27378. *
  27379. * @param {Object} module the module object from the build config info.
  27380. *
  27381. * @param {Object} layer the layer object returned from build.traceDependencies.
  27382. *
  27383. * @param {Object} the build config object.
  27384. *
  27385. * @returns {Object} with two properties: "text", the text of the flattened
  27386. * module, and "buildText", a string of text representing which files were
  27387. * included in the flattened module text.
  27388. */
  27389. build.flattenModule = function (module, layer, config) {
  27390. var fileContents, sourceMapGenerator,
  27391. sourceMapBase,
  27392. buildFileContents = '';
  27393. return prim().start(function () {
  27394. var reqIndex, currContents, fileForSourceMap,
  27395. moduleName, shim, packageName,
  27396. parts, builder, writeApi,
  27397. namespace, namespaceWithDot, stubModulesByName,
  27398. context = layer.context,
  27399. onLayerEnds = [],
  27400. onLayerEndAdded = {},
  27401. pkgsMainMap = {};
  27402. //Use override settings, particularly for pragmas
  27403. //Do this before the var readings since it reads config values.
  27404. if (module.override) {
  27405. config = build.createOverrideConfig(config, module.override);
  27406. }
  27407. namespace = config.namespace || '';
  27408. namespaceWithDot = namespace ? namespace + '.' : '';
  27409. stubModulesByName = (module.stubModules && module.stubModules._byName) || {};
  27410. //Start build output for the module.
  27411. module.onCompleteData = {
  27412. name: module.name,
  27413. path: (config.dir ? module._buildPath.replace(config.dir, "") : module._buildPath),
  27414. included: []
  27415. };
  27416. buildFileContents += "\n" +
  27417. module.onCompleteData.path +
  27418. "\n----------------\n";
  27419. //If there was an existing file with require in it, hoist to the top.
  27420. if (layer.existingRequireUrl) {
  27421. reqIndex = layer.buildFilePaths.indexOf(layer.existingRequireUrl);
  27422. if (reqIndex !== -1) {
  27423. layer.buildFilePaths.splice(reqIndex, 1);
  27424. layer.buildFilePaths.unshift(layer.existingRequireUrl);
  27425. }
  27426. }
  27427. if (config.generateSourceMaps) {
  27428. sourceMapBase = config.dir || config.baseUrl;
  27429. if (module._buildPath === 'FUNCTION') {
  27430. fileForSourceMap = (module.name || module.include[0] || 'FUNCTION') + '.build.js';
  27431. } else if (config.out) {
  27432. fileForSourceMap = module._buildPath.split('/').pop();
  27433. } else {
  27434. fileForSourceMap = module._buildPath.replace(sourceMapBase, '');
  27435. }
  27436. sourceMapGenerator = new SourceMapGenerator({
  27437. file: fileForSourceMap
  27438. });
  27439. }
  27440. //Create a reverse lookup for packages main module IDs to their package
  27441. //names, useful for knowing when to write out define() package main ID
  27442. //adapters.
  27443. lang.eachProp(layer.context.config.pkgs, function(value, prop) {
  27444. pkgsMainMap[value] = prop;
  27445. });
  27446. //Write the built module to disk, and build up the build output.
  27447. fileContents = "";
  27448. if (config.wrap && config.wrap.__startMap) {
  27449. config.wrap.__startMap.forEach(function (wrapFunction) {
  27450. fileContents = wrapFunction(fileContents, config, sourceMapGenerator);
  27451. });
  27452. }
  27453. return prim.serial(layer.buildFilePaths.map(function (path) {
  27454. return function () {
  27455. var singleContents = '';
  27456. moduleName = layer.buildFileToModule[path];
  27457. //If the moduleName is a package main, then hold on to the
  27458. //packageName in case an adapter needs to be written.
  27459. packageName = getOwn(pkgsMainMap, moduleName);
  27460. return prim().start(function () {
  27461. //Figure out if the module is a result of a build plugin, and if so,
  27462. //then delegate to that plugin.
  27463. parts = context.makeModuleMap(moduleName);
  27464. builder = parts.prefix && getOwn(context.defined, parts.prefix);
  27465. if (builder) {
  27466. if (builder.onLayerEnd && falseProp(onLayerEndAdded, parts.prefix)) {
  27467. onLayerEnds.push(builder);
  27468. onLayerEndAdded[parts.prefix] = true;
  27469. }
  27470. if (builder.write) {
  27471. writeApi = function (input) {
  27472. singleContents += "\n" + addSemiColon(input, config);
  27473. if (config.onBuildWrite) {
  27474. singleContents = config.onBuildWrite(moduleName, path, singleContents);
  27475. }
  27476. };
  27477. writeApi.asModule = function (moduleName, input) {
  27478. singleContents += "\n" +
  27479. addSemiColon(build.toTransport(namespace, moduleName, path, input, layer, {
  27480. useSourceUrl: layer.context.config.useSourceUrl
  27481. }), config);
  27482. if (config.onBuildWrite) {
  27483. singleContents = config.onBuildWrite(moduleName, path, singleContents);
  27484. }
  27485. };
  27486. builder.write(parts.prefix, parts.name, writeApi);
  27487. }
  27488. return;
  27489. } else {
  27490. return prim().start(function () {
  27491. if (hasProp(stubModulesByName, moduleName)) {
  27492. //Just want to insert a simple module definition instead
  27493. //of the source module. Useful for plugins that inline
  27494. //all their resources.
  27495. if (hasProp(layer.context.plugins, moduleName)) {
  27496. //Slightly different content for plugins, to indicate
  27497. //that dynamic loading will not work.
  27498. return 'define({load: function(id){throw new Error("Dynamic load not allowed: " + id);}});';
  27499. } else {
  27500. return 'define({});';
  27501. }
  27502. } else {
  27503. return require._cacheReadAsync(path);
  27504. }
  27505. }).then(function (text) {
  27506. var hasPackageName;
  27507. currContents = text;
  27508. if (config.cjsTranslate &&
  27509. (!config.shim || !lang.hasProp(config.shim, moduleName))) {
  27510. currContents = commonJs.convert(path, currContents);
  27511. }
  27512. if (config.onBuildRead) {
  27513. currContents = config.onBuildRead(moduleName, path, currContents);
  27514. }
  27515. if (packageName) {
  27516. hasPackageName = (packageName === parse.getNamedDefine(currContents));
  27517. }
  27518. if (namespace) {
  27519. currContents = pragma.namespace(currContents, namespace);
  27520. }
  27521. currContents = build.toTransport(namespace, moduleName, path, currContents, layer, {
  27522. useSourceUrl: config.useSourceUrl
  27523. });
  27524. if (packageName && !hasPackageName) {
  27525. currContents = addSemiColon(currContents, config) + '\n';
  27526. currContents += namespaceWithDot + "define('" +
  27527. packageName + "', ['" + moduleName +
  27528. "'], function (main) { return main; });\n";
  27529. }
  27530. if (config.onBuildWrite) {
  27531. currContents = config.onBuildWrite(moduleName, path, currContents);
  27532. }
  27533. //Semicolon is for files that are not well formed when
  27534. //concatenated with other content.
  27535. singleContents += addSemiColon(currContents, config);
  27536. });
  27537. }
  27538. }).then(function () {
  27539. var shimDeps, shortPath = path.replace(config.dir, "");
  27540. module.onCompleteData.included.push(shortPath);
  27541. buildFileContents += shortPath + "\n";
  27542. //Some files may not have declared a require module, and if so,
  27543. //put in a placeholder call so the require does not try to load them
  27544. //after the module is processed.
  27545. //If we have a name, but no defined module, then add in the placeholder.
  27546. if (moduleName && falseProp(layer.modulesWithNames, moduleName) && !config.skipModuleInsertion) {
  27547. shim = config.shim && (getOwn(config.shim, moduleName) || (packageName && getOwn(config.shim, packageName)));
  27548. if (shim) {
  27549. shimDeps = lang.isArray(shim) ? shim : shim.deps;
  27550. if (config.wrapShim) {
  27551. singleContents = '(function(root) {\n' +
  27552. namespaceWithDot + 'define("' + moduleName + '", ' +
  27553. (shimDeps && shimDeps.length ?
  27554. build.makeJsArrayString(shimDeps) + ', ' : '[], ') +
  27555. 'function() {\n' +
  27556. ' return (function() {\n' +
  27557. singleContents +
  27558. // Start with a \n in case last line is a comment
  27559. // in the singleContents, like a sourceURL comment.
  27560. '\n' + (shim.exportsFn ? shim.exportsFn() : '') +
  27561. '\n' +
  27562. ' }).apply(root, arguments);\n' +
  27563. '});\n' +
  27564. '}(this));\n';
  27565. } else {
  27566. singleContents += '\n' + namespaceWithDot + 'define("' + moduleName + '", ' +
  27567. (shimDeps && shimDeps.length ?
  27568. build.makeJsArrayString(shimDeps) + ', ' : '') +
  27569. (shim.exportsFn ? shim.exportsFn() : 'function(){}') +
  27570. ');\n';
  27571. }
  27572. } else {
  27573. singleContents += '\n' + namespaceWithDot + 'define("' + moduleName + '", function(){});\n';
  27574. }
  27575. }
  27576. //Add line break at end of file, instead of at beginning,
  27577. //so source map line numbers stay correct, but still allow
  27578. //for some space separation between files in case ASI issues
  27579. //for concatenation would cause an error otherwise.
  27580. singleContents += '\n';
  27581. //Add to the source map and to the final contents
  27582. fileContents = appendToFileContents(fileContents, singleContents, path, config, module,
  27583. sourceMapGenerator);
  27584. });
  27585. };
  27586. })).then(function () {
  27587. if (onLayerEnds.length) {
  27588. onLayerEnds.forEach(function (builder, index) {
  27589. var path;
  27590. if (typeof module.out === 'string') {
  27591. path = module.out;
  27592. } else if (typeof module._buildPath === 'string') {
  27593. path = module._buildPath;
  27594. }
  27595. builder.onLayerEnd(function (input) {
  27596. fileContents =
  27597. appendToFileContents(fileContents, "\n" + addSemiColon(input, config),
  27598. 'onLayerEnd' + index + '.js', config, module, sourceMapGenerator);
  27599. }, {
  27600. name: module.name,
  27601. path: path
  27602. });
  27603. });
  27604. }
  27605. if (module.create) {
  27606. //The ID is for a created layer. Write out
  27607. //a module definition for it in case the
  27608. //built file is used with enforceDefine
  27609. //(#432)
  27610. fileContents =
  27611. appendToFileContents(fileContents, '\n' + namespaceWithDot + 'define("' + module.name +
  27612. '", function(){});\n', 'module-create.js', config, module,
  27613. sourceMapGenerator);
  27614. }
  27615. //Add a require at the end to kick start module execution, if that
  27616. //was desired. Usually this is only specified when using small shim
  27617. //loaders like almond.
  27618. if (module.insertRequire) {
  27619. fileContents =
  27620. appendToFileContents(fileContents, '\n' + namespaceWithDot + 'require(["' + module.insertRequire.join('", "') +
  27621. '"]);\n', 'module-insertRequire.js', config, module,
  27622. sourceMapGenerator);
  27623. }
  27624. });
  27625. }).then(function () {
  27626. if (config.wrap && config.wrap.__endMap) {
  27627. config.wrap.__endMap.forEach(function (wrapFunction) {
  27628. fileContents = wrapFunction(fileContents, config, sourceMapGenerator);
  27629. });
  27630. }
  27631. return {
  27632. text: fileContents,
  27633. buildText: buildFileContents,
  27634. sourceMap: sourceMapGenerator ?
  27635. JSON.stringify(sourceMapGenerator.toJSON(), null, ' ') :
  27636. undefined
  27637. };
  27638. });
  27639. };
  27640. //Converts an JS array of strings to a string representation.
  27641. //Not using JSON.stringify() for Rhino's sake.
  27642. build.makeJsArrayString = function (ary) {
  27643. return '["' + ary.map(function (item) {
  27644. //Escape any double quotes, backslashes
  27645. return lang.jsEscape(item);
  27646. }).join('","') + '"]';
  27647. };
  27648. build.toTransport = function (namespace, moduleName, path, contents, layer, options) {
  27649. var baseUrl = layer && layer.context.config.baseUrl;
  27650. function onFound(info) {
  27651. //Only mark this module as having a name if not a named module,
  27652. //or if a named module and the name matches expectations.
  27653. if (layer && (info.needsId || info.foundId === moduleName)) {
  27654. layer.modulesWithNames[moduleName] = true;
  27655. }
  27656. }
  27657. //Convert path to be a local one to the baseUrl, useful for
  27658. //useSourceUrl.
  27659. if (baseUrl) {
  27660. path = path.replace(baseUrl, '');
  27661. }
  27662. return transform.toTransport(namespace, moduleName, path, contents, onFound, options);
  27663. };
  27664. return build;
  27665. });
  27666. }
  27667. /**
  27668. * Sets the default baseUrl for requirejs to be directory of top level
  27669. * script.
  27670. */
  27671. function setBaseUrl(fileName) {
  27672. //Use the file name's directory as the baseUrl if available.
  27673. dir = fileName.replace(/\\/g, '/');
  27674. if (dir.indexOf('/') !== -1) {
  27675. dir = dir.split('/');
  27676. dir.pop();
  27677. dir = dir.join('/');
  27678. //Make sure dir is JS-escaped, since it will be part of a JS string.
  27679. exec("require({baseUrl: '" + dir.replace(/[\\"']/g, '\\$&') + "'});");
  27680. }
  27681. }
  27682. function createRjsApi() {
  27683. //Create a method that will run the optimzer given an object
  27684. //config.
  27685. requirejs.optimize = function (config, callback, errback) {
  27686. if (!loadedOptimizedLib) {
  27687. loadLib();
  27688. loadedOptimizedLib = true;
  27689. }
  27690. //Create the function that will be called once build modules
  27691. //have been loaded.
  27692. var runBuild = function (build, logger, quit) {
  27693. //Make sure config has a log level, and if not,
  27694. //make it "silent" by default.
  27695. config.logLevel = config.hasOwnProperty('logLevel') ?
  27696. config.logLevel : logger.SILENT;
  27697. //Reset build internals first in case this is part
  27698. //of a long-running server process that could have
  27699. //exceptioned out in a bad state. It is only defined
  27700. //after the first call though.
  27701. if (requirejs._buildReset) {
  27702. requirejs._buildReset();
  27703. requirejs._cacheReset();
  27704. }
  27705. function done(result) {
  27706. //And clean up, in case something else triggers
  27707. //a build in another pathway.
  27708. if (requirejs._buildReset) {
  27709. requirejs._buildReset();
  27710. requirejs._cacheReset();
  27711. }
  27712. // Ensure errors get propagated to the errback
  27713. if (result instanceof Error) {
  27714. throw result;
  27715. }
  27716. return result;
  27717. }
  27718. errback = errback || function (err) {
  27719. // Using console here since logger may have
  27720. // turned off error logging. Since quit is
  27721. // called want to be sure a message is printed.
  27722. console.log(err);
  27723. quit(1);
  27724. };
  27725. build(config).then(done, done).then(callback, errback);
  27726. };
  27727. requirejs({
  27728. context: 'build'
  27729. }, ['build', 'logger', 'env!env/quit'], runBuild);
  27730. };
  27731. requirejs.tools = {
  27732. useLib: function (contextName, callback) {
  27733. if (!callback) {
  27734. callback = contextName;
  27735. contextName = 'uselib';
  27736. }
  27737. if (!useLibLoaded[contextName]) {
  27738. loadLib();
  27739. useLibLoaded[contextName] = true;
  27740. }
  27741. var req = requirejs({
  27742. context: contextName
  27743. });
  27744. req(['build'], function () {
  27745. callback(req);
  27746. });
  27747. }
  27748. };
  27749. requirejs.define = define;
  27750. }
  27751. //If in Node, and included via a require('requirejs'), just export and
  27752. //THROW IT ON THE GROUND!
  27753. if (env === 'node' && reqMain !== module) {
  27754. setBaseUrl(path.resolve(reqMain ? reqMain.filename : '.'));
  27755. createRjsApi();
  27756. module.exports = requirejs;
  27757. return;
  27758. } else if (env === 'browser') {
  27759. //Only option is to use the API.
  27760. setBaseUrl(location.href);
  27761. createRjsApi();
  27762. return;
  27763. } else if ((env === 'rhino' || env === 'xpconnect') &&
  27764. //User sets up requirejsAsLib variable to indicate it is loaded
  27765. //via load() to be used as a library.
  27766. typeof requirejsAsLib !== 'undefined' && requirejsAsLib) {
  27767. //This script is loaded via rhino's load() method, expose the
  27768. //API and get out.
  27769. setBaseUrl(fileName);
  27770. createRjsApi();
  27771. return;
  27772. }
  27773. if (commandOption === 'o') {
  27774. //Do the optimizer work.
  27775. loadLib();
  27776. /*
  27777. * Create a build.js file that has the build options you want and pass that
  27778. * build file to this file to do the build. See example.build.js for more information.
  27779. */
  27780. /*jslint strict: false, nomen: false */
  27781. /*global require: false */
  27782. require({
  27783. baseUrl: require.s.contexts._.config.baseUrl,
  27784. //Use a separate context than the default context so that the
  27785. //build can use the default context.
  27786. context: 'build',
  27787. catchError: {
  27788. define: true
  27789. }
  27790. }, ['env!env/args', 'env!env/quit', 'logger', 'build'],
  27791. function (args, quit, logger, build) {
  27792. build(args).then(function () {}, function (err) {
  27793. logger.error(err);
  27794. quit(1);
  27795. });
  27796. });
  27797. } else if (commandOption === 'v') {
  27798. console.log('r.js: ' + version +
  27799. ', RequireJS: ' + this.requirejsVars.require.version +
  27800. ', UglifyJS: 2.8.29');
  27801. } else if (commandOption === 'convert') {
  27802. loadLib();
  27803. this.requirejsVars.require(['env!env/args', 'commonJs', 'env!env/print'],
  27804. function (args, commonJs, print) {
  27805. var srcDir, outDir;
  27806. srcDir = args[0];
  27807. outDir = args[1];
  27808. if (!srcDir || !outDir) {
  27809. print('Usage: path/to/commonjs/modules output/dir');
  27810. return;
  27811. }
  27812. commonJs.convertDir(args[0], args[1]);
  27813. });
  27814. } else {
  27815. //Just run an app
  27816. //Load the bundled libraries for use in the app.
  27817. if (commandOption === 'lib') {
  27818. loadLib();
  27819. }
  27820. setBaseUrl(fileName);
  27821. if (exists(fileName)) {
  27822. exec(readFile(fileName), fileName);
  27823. } else {
  27824. showHelp();
  27825. }
  27826. }
  27827. }((typeof console !== 'undefined' ? console : undefined),
  27828. (typeof Packages !== 'undefined' || (typeof window === 'undefined' &&
  27829. typeof Components !== 'undefined' && Components.interfaces) ?
  27830. Array.prototype.slice.call(arguments, 0) : []),
  27831. (typeof readFile !== 'undefined' ? readFile : undefined)));