03078b0482cdd24473480fd3e96c38667dedad52cc0857aadd157dca5fedf33d725d1a18a5b4beb70766745824408856a4b5a1202fbc41cb1da56f91872c12 1003 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351
  1. /*
  2. @license
  3. Rollup.js v3.29.4
  4. Sat, 21 Sep 2024 06:29:06 GMT - commit 2ef77c00ec2635d42697cff2c0567ccc8db34fb4
  5. https://github.com/rollup/rollup
  6. Released under the MIT License.
  7. */
  8. 'use strict';
  9. const process$1 = require('node:process');
  10. const tty = require('tty');
  11. const node_path = require('node:path');
  12. const require$$0$1 = require('path');
  13. const node_perf_hooks = require('node:perf_hooks');
  14. const node_crypto = require('node:crypto');
  15. const promises = require('node:fs/promises');
  16. function _interopNamespaceDefault(e) {
  17. const n = Object.create(null, { [Symbol.toStringTag]: { value: 'Module' } });
  18. if (e) {
  19. for (const k in e) {
  20. n[k] = e[k];
  21. }
  22. }
  23. n.default = e;
  24. return n;
  25. }
  26. const tty__namespace = /*#__PURE__*/_interopNamespaceDefault(tty);
  27. var version$1 = "3.29.4";
  28. function ensureArray$1(items) {
  29. if (Array.isArray(items)) {
  30. return items.filter(Boolean);
  31. }
  32. if (items) {
  33. return [items];
  34. }
  35. return [];
  36. }
  37. var BuildPhase;
  38. (function (BuildPhase) {
  39. BuildPhase[BuildPhase["LOAD_AND_PARSE"] = 0] = "LOAD_AND_PARSE";
  40. BuildPhase[BuildPhase["ANALYSE"] = 1] = "ANALYSE";
  41. BuildPhase[BuildPhase["GENERATE"] = 2] = "GENERATE";
  42. })(BuildPhase || (BuildPhase = {}));
  43. const createHash = () => node_crypto.createHash('sha256');
  44. function getOrCreate(map, key, init) {
  45. const existing = map.get(key);
  46. if (existing !== undefined) {
  47. return existing;
  48. }
  49. const value = init();
  50. map.set(key, value);
  51. return value;
  52. }
  53. function getNewSet() {
  54. return new Set();
  55. }
  56. function getNewArray() {
  57. return [];
  58. }
  59. const chars$1 = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
  60. const base$1 = 64;
  61. function toBase64(value) {
  62. let outString = '';
  63. do {
  64. const currentDigit = value % base$1;
  65. value = (value / base$1) | 0;
  66. outString = chars$1[currentDigit] + outString;
  67. } while (value !== 0);
  68. return outString;
  69. }
  70. /** @typedef {import('./types').Location} Location */
  71. /**
  72. * @param {import('./types').Range} range
  73. * @param {number} index
  74. */
  75. function rangeContains(range, index) {
  76. return range.start <= index && index < range.end;
  77. }
  78. /**
  79. * @param {string} source
  80. * @param {import('./types').Options} [options]
  81. */
  82. function getLocator$1(source, options = {}) {
  83. const { offsetLine = 0, offsetColumn = 0 } = options;
  84. let start = 0;
  85. const ranges = source.split('\n').map((line, i) => {
  86. const end = start + line.length + 1;
  87. /** @type {import('./types').Range} */
  88. const range = { start, end, line: i };
  89. start = end;
  90. return range;
  91. });
  92. let i = 0;
  93. /**
  94. * @param {string | number} search
  95. * @param {number} [index]
  96. * @returns {Location | undefined}
  97. */
  98. function locator(search, index) {
  99. if (typeof search === 'string') {
  100. search = source.indexOf(search, index ?? 0);
  101. }
  102. if (search === -1) return undefined;
  103. let range = ranges[i];
  104. const d = search >= range.end ? 1 : -1;
  105. while (range) {
  106. if (rangeContains(range, search)) {
  107. return {
  108. line: offsetLine + range.line,
  109. column: offsetColumn + search - range.start,
  110. character: search
  111. };
  112. }
  113. i += d;
  114. range = ranges[i];
  115. }
  116. }
  117. return locator;
  118. }
  119. /**
  120. * @param {string} source
  121. * @param {string | number} search
  122. * @param {import('./types').Options} [options]
  123. * @returns {Location | undefined}
  124. */
  125. function locate(source, search, options) {
  126. return getLocator$1(source, options)(search, options && options.startIndex);
  127. }
  128. function spaces(index) {
  129. let result = '';
  130. while (index--)
  131. result += ' ';
  132. return result;
  133. }
  134. function tabsToSpaces(value) {
  135. return value.replace(/^\t+/, match => match.split('\t').join(' '));
  136. }
  137. const LINE_TRUNCATE_LENGTH = 120;
  138. const MIN_CHARACTERS_SHOWN_AFTER_LOCATION = 10;
  139. const ELLIPSIS = '...';
  140. function getCodeFrame(source, line, column) {
  141. let lines = source.split('\n');
  142. // Needed if a plugin did not generate correct sourcemaps
  143. if (line > lines.length)
  144. return '';
  145. const maxLineLength = Math.max(tabsToSpaces(lines[line - 1].slice(0, column)).length +
  146. MIN_CHARACTERS_SHOWN_AFTER_LOCATION +
  147. ELLIPSIS.length, LINE_TRUNCATE_LENGTH);
  148. const frameStart = Math.max(0, line - 3);
  149. let frameEnd = Math.min(line + 2, lines.length);
  150. lines = lines.slice(frameStart, frameEnd);
  151. while (!/\S/.test(lines[lines.length - 1])) {
  152. lines.pop();
  153. frameEnd -= 1;
  154. }
  155. const digits = String(frameEnd).length;
  156. return lines
  157. .map((sourceLine, index) => {
  158. const isErrorLine = frameStart + index + 1 === line;
  159. let lineNumber = String(index + frameStart + 1);
  160. while (lineNumber.length < digits)
  161. lineNumber = ` ${lineNumber}`;
  162. let displayedLine = tabsToSpaces(sourceLine);
  163. if (displayedLine.length > maxLineLength) {
  164. displayedLine = `${displayedLine.slice(0, maxLineLength - ELLIPSIS.length)}${ELLIPSIS}`;
  165. }
  166. if (isErrorLine) {
  167. const indicator = spaces(digits + 2 + tabsToSpaces(sourceLine.slice(0, column)).length) + '^';
  168. return `${lineNumber}: ${displayedLine}\n${indicator}`;
  169. }
  170. return `${lineNumber}: ${displayedLine}`;
  171. })
  172. .join('\n');
  173. }
  174. const LOGLEVEL_SILENT = 'silent';
  175. const LOGLEVEL_ERROR = 'error';
  176. const LOGLEVEL_WARN = 'warn';
  177. const LOGLEVEL_INFO = 'info';
  178. const LOGLEVEL_DEBUG = 'debug';
  179. const logLevelPriority = {
  180. [LOGLEVEL_DEBUG]: 0,
  181. [LOGLEVEL_INFO]: 1,
  182. [LOGLEVEL_SILENT]: 3,
  183. [LOGLEVEL_WARN]: 2
  184. };
  185. const ABSOLUTE_PATH_REGEX = /^(?:\/|(?:[A-Za-z]:)?[/\\|])/;
  186. const RELATIVE_PATH_REGEX = /^\.?\.(\/|$)/;
  187. function isAbsolute(path) {
  188. return ABSOLUTE_PATH_REGEX.test(path);
  189. }
  190. function isRelative(path) {
  191. return RELATIVE_PATH_REGEX.test(path);
  192. }
  193. const BACKSLASH_REGEX = /\\/g;
  194. function normalize(path) {
  195. return path.replace(BACKSLASH_REGEX, '/');
  196. }
  197. function printQuotedStringList(list, verbs) {
  198. const isSingleItem = list.length <= 1;
  199. const quotedList = list.map(item => `"${item}"`);
  200. let output = isSingleItem
  201. ? quotedList[0]
  202. : `${quotedList.slice(0, -1).join(', ')} and ${quotedList.slice(-1)[0]}`;
  203. if (verbs) {
  204. output += ` ${isSingleItem ? verbs[0] : verbs[1]}`;
  205. }
  206. return output;
  207. }
  208. const ANY_SLASH_REGEX = /[/\\]/;
  209. function relative(from, to) {
  210. const fromParts = from.split(ANY_SLASH_REGEX).filter(Boolean);
  211. const toParts = to.split(ANY_SLASH_REGEX).filter(Boolean);
  212. if (fromParts[0] === '.')
  213. fromParts.shift();
  214. if (toParts[0] === '.')
  215. toParts.shift();
  216. while (fromParts[0] && toParts[0] && fromParts[0] === toParts[0]) {
  217. fromParts.shift();
  218. toParts.shift();
  219. }
  220. while (toParts[0] === '..' && fromParts.length > 0) {
  221. toParts.shift();
  222. fromParts.pop();
  223. }
  224. while (fromParts.pop()) {
  225. toParts.unshift('..');
  226. }
  227. return toParts.join('/');
  228. }
  229. function getAliasName(id) {
  230. const base = node_path.basename(id);
  231. return base.slice(0, Math.max(0, base.length - node_path.extname(id).length));
  232. }
  233. function relativeId(id) {
  234. if (!isAbsolute(id))
  235. return id;
  236. return relative(node_path.resolve(), id);
  237. }
  238. function isPathFragment(name) {
  239. // starting with "/", "./", "../", "C:/"
  240. return (name[0] === '/' || (name[0] === '.' && (name[1] === '/' || name[1] === '.')) || isAbsolute(name));
  241. }
  242. const UPPER_DIR_REGEX = /^(\.\.\/)*\.\.$/;
  243. function getImportPath(importerId, targetPath, stripJsExtension, ensureFileName) {
  244. while (targetPath.startsWith('../')) {
  245. targetPath = targetPath.slice(3);
  246. importerId = '_/' + importerId;
  247. }
  248. let relativePath = normalize(relative(node_path.dirname(importerId), targetPath));
  249. if (stripJsExtension && relativePath.endsWith('.js')) {
  250. relativePath = relativePath.slice(0, -3);
  251. }
  252. if (ensureFileName) {
  253. if (relativePath === '')
  254. return '../' + node_path.basename(targetPath);
  255. if (UPPER_DIR_REGEX.test(relativePath)) {
  256. return [...relativePath.split('/'), '..', node_path.basename(targetPath)].join('/');
  257. }
  258. }
  259. return relativePath ? (relativePath.startsWith('..') ? relativePath : './' + relativePath) : '.';
  260. }
  261. function isValidUrl(url) {
  262. try {
  263. new URL(url);
  264. }
  265. catch {
  266. return false;
  267. }
  268. return true;
  269. }
  270. function getRollupUrl(snippet) {
  271. return `https://rollupjs.org/${snippet}`;
  272. }
  273. function addTrailingSlashIfMissed(url) {
  274. if (!url.endsWith('/')) {
  275. return url + '/';
  276. }
  277. return url;
  278. }
  279. // troubleshooting
  280. const URL_AVOIDING_EVAL = 'troubleshooting/#avoiding-eval';
  281. const URL_NAME_IS_NOT_EXPORTED = 'troubleshooting/#error-name-is-not-exported-by-module';
  282. const URL_THIS_IS_UNDEFINED = 'troubleshooting/#error-this-is-undefined';
  283. const URL_TREATING_MODULE_AS_EXTERNAL_DEPENDENCY = 'troubleshooting/#warning-treating-module-as-external-dependency';
  284. const URL_SOURCEMAP_IS_LIKELY_TO_BE_INCORRECT = 'troubleshooting/#warning-sourcemap-is-likely-to-be-incorrect';
  285. // configuration-options
  286. const URL_MAXPARALLELFILEOPS = 'configuration-options/#maxparallelfileops';
  287. const URL_OUTPUT_AMD_ID = 'configuration-options/#output-amd-id';
  288. const URL_OUTPUT_AMD_BASEPATH = 'configuration-options/#output-amd-basepath';
  289. const URL_OUTPUT_DIR = 'configuration-options/#output-dir';
  290. const URL_OUTPUT_DYNAMICIMPORTFUNCTION = 'configuration-options/#output-dynamicimportfunction';
  291. const URL_OUTPUT_EXPORTS = 'configuration-options/#output-exports';
  292. const URL_OUTPUT_EXTEND = 'configuration-options/#output-extend';
  293. const URL_OUTPUT_FORMAT = 'configuration-options/#output-format';
  294. const URL_OUTPUT_GENERATEDCODE = 'configuration-options/#output-generatedcode';
  295. const URL_OUTPUT_EXPERIMENTALDEEPCHUNKOPTIMIZATION = 'configuration-options/#output-experimentaldeepdynamicchunkoptimization';
  296. const URL_OUTPUT_GENERATEDCODE_CONSTBINDINGS = 'configuration-options/#output-generatedcode-constbindings';
  297. const URL_OUTPUT_GENERATEDCODE_SYMBOLS = 'configuration-options/#output-generatedcode-symbols';
  298. const URL_OUTPUT_GLOBALS = 'configuration-options/#output-globals';
  299. const URL_OUTPUT_INLINEDYNAMICIMPORTS = 'configuration-options/#output-inlinedynamicimports';
  300. const URL_OUTPUT_INTEROP = 'configuration-options/#output-interop';
  301. const URL_OUTPUT_MANUALCHUNKS = 'configuration-options/#output-manualchunks';
  302. const URL_OUTPUT_NAME = 'configuration-options/#output-name';
  303. const URL_OUTPUT_PRESERVEMODULES = 'configuration-options/#output-preservemodules';
  304. const URL_OUTPUT_SOURCEMAPBASEURL = 'configuration-options/#output-sourcemapbaseurl';
  305. const URL_OUTPUT_SOURCEMAPFILE = 'configuration-options/#output-sourcemapfile';
  306. const URL_PRESERVEENTRYSIGNATURES = 'configuration-options/#preserveentrysignatures';
  307. const URL_TREESHAKE = 'configuration-options/#treeshake';
  308. const URL_TREESHAKE_MODULESIDEEFFECTS = 'configuration-options/#treeshake-modulesideeffects';
  309. const URL_WATCH = 'configuration-options/#watch';
  310. // command-line-interface
  311. const URL_BUNDLE_CONFIG_AS_CJS = 'command-line-interface/#bundleconfigascjs';
  312. const URL_CONFIGURATION_FILES = 'command-line-interface/#configuration-files';
  313. const URL_RENDERDYNAMICIMPORT = 'plugin-development/#renderdynamicimport';
  314. const URL_THIS_GETMODULEIDS = 'plugin-development/#this-getmoduleids';
  315. const URL_THIS_GETMODULEINFO = 'plugin-development/#this-getmoduleinfo';
  316. function error(base) {
  317. if (!(base instanceof Error)) {
  318. base = Object.assign(new Error(base.message), base);
  319. Object.defineProperty(base, 'name', { value: 'RollupError' });
  320. }
  321. throw base;
  322. }
  323. function augmentCodeLocation(properties, pos, source, id) {
  324. if (typeof pos === 'object') {
  325. const { line, column } = pos;
  326. properties.loc = { column, file: id, line };
  327. }
  328. else {
  329. properties.pos = pos;
  330. const { line, column } = locate(source, pos, { offsetLine: 1 });
  331. properties.loc = { column, file: id, line };
  332. }
  333. if (properties.frame === undefined) {
  334. const { line, column } = properties.loc;
  335. properties.frame = getCodeFrame(source, line, column);
  336. }
  337. }
  338. // Error codes should be sorted alphabetically while errors should be sorted by
  339. // error code below
  340. const ADDON_ERROR = 'ADDON_ERROR', ALREADY_CLOSED = 'ALREADY_CLOSED', AMBIGUOUS_EXTERNAL_NAMESPACES = 'AMBIGUOUS_EXTERNAL_NAMESPACES', ANONYMOUS_PLUGIN_CACHE = 'ANONYMOUS_PLUGIN_CACHE', ASSET_NOT_FINALISED = 'ASSET_NOT_FINALISED', ASSET_NOT_FOUND = 'ASSET_NOT_FOUND', ASSET_SOURCE_ALREADY_SET = 'ASSET_SOURCE_ALREADY_SET', ASSET_SOURCE_MISSING = 'ASSET_SOURCE_MISSING', BAD_LOADER = 'BAD_LOADER', CANNOT_CALL_NAMESPACE = 'CANNOT_CALL_NAMESPACE', CANNOT_EMIT_FROM_OPTIONS_HOOK = 'CANNOT_EMIT_FROM_OPTIONS_HOOK', CHUNK_NOT_GENERATED = 'CHUNK_NOT_GENERATED', CHUNK_INVALID = 'CHUNK_INVALID', CIRCULAR_DEPENDENCY = 'CIRCULAR_DEPENDENCY', CIRCULAR_REEXPORT = 'CIRCULAR_REEXPORT', CYCLIC_CROSS_CHUNK_REEXPORT = 'CYCLIC_CROSS_CHUNK_REEXPORT', DEPRECATED_FEATURE = 'DEPRECATED_FEATURE', DUPLICATE_IMPORT_OPTIONS = 'DUPLICATE_IMPORT_OPTIONS', DUPLICATE_PLUGIN_NAME = 'DUPLICATE_PLUGIN_NAME', EMPTY_BUNDLE = 'EMPTY_BUNDLE', EVAL = 'EVAL', EXTERNAL_MODULES_CANNOT_BE_INCLUDED_IN_MANUAL_CHUNKS = 'EXTERNAL_MODULES_CANNOT_BE_INCLUDED_IN_MANUAL_CHUNKS', EXTERNAL_MODULES_CANNOT_BE_TRANSFORMED_TO_MODULES = 'EXTERNAL_MODULES_CANNOT_BE_TRANSFORMED_TO_MODULES', EXTERNAL_SYNTHETIC_EXPORTS = 'EXTERNAL_SYNTHETIC_EXPORTS', FAIL_AFTER_WARNINGS = 'FAIL_AFTER_WARNINGS', FILE_NAME_CONFLICT = 'FILE_NAME_CONFLICT', FILE_NOT_FOUND = 'FILE_NOT_FOUND', FIRST_SIDE_EFFECT = 'FIRST_SIDE_EFFECT', ILLEGAL_IDENTIFIER_AS_NAME = 'ILLEGAL_IDENTIFIER_AS_NAME', ILLEGAL_REASSIGNMENT = 'ILLEGAL_REASSIGNMENT', INCONSISTENT_IMPORT_ASSERTIONS = 'INCONSISTENT_IMPORT_ASSERTIONS', INPUT_HOOK_IN_OUTPUT_PLUGIN = 'INPUT_HOOK_IN_OUTPUT_PLUGIN', INVALID_CHUNK = 'INVALID_CHUNK', INVALID_CONFIG_MODULE_FORMAT = 'INVALID_CONFIG_MODULE_FORMAT', INVALID_EXPORT_OPTION = 'INVALID_EXPORT_OPTION', INVALID_EXTERNAL_ID = 'INVALID_EXTERNAL_ID', INVALID_LOG_POSITION = 'INVALID_LOG_POSITION', INVALID_OPTION = 'INVALID_OPTION', INVALID_PLUGIN_HOOK = 'INVALID_PLUGIN_HOOK', INVALID_ROLLUP_PHASE = 'INVALID_ROLLUP_PHASE', INVALID_SETASSETSOURCE = 'INVALID_SETASSETSOURCE', INVALID_TLA_FORMAT = 'INVALID_TLA_FORMAT', MISSING_CONFIG = 'MISSING_CONFIG', MISSING_EXPORT = 'MISSING_EXPORT', MISSING_EXTERNAL_CONFIG = 'MISSING_EXTERNAL_CONFIG', MISSING_GLOBAL_NAME = 'MISSING_GLOBAL_NAME', MISSING_IMPLICIT_DEPENDANT = 'MISSING_IMPLICIT_DEPENDANT', MISSING_NAME_OPTION_FOR_IIFE_EXPORT = 'MISSING_NAME_OPTION_FOR_IIFE_EXPORT', MISSING_NODE_BUILTINS = 'MISSING_NODE_BUILTINS', MISSING_OPTION = 'MISSING_OPTION', MIXED_EXPORTS = 'MIXED_EXPORTS', MODULE_LEVEL_DIRECTIVE = 'MODULE_LEVEL_DIRECTIVE', NAMESPACE_CONFLICT = 'NAMESPACE_CONFLICT', NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE = 'NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE', ONLY_INLINE_SOURCEMAPS = 'ONLY_INLINE_SOURCEMAPS', OPTIMIZE_CHUNK_STATUS = 'OPTIMIZE_CHUNK_STATUS', PARSE_ERROR = 'PARSE_ERROR', PLUGIN_ERROR = 'PLUGIN_ERROR', SHIMMED_EXPORT = 'SHIMMED_EXPORT', SOURCEMAP_BROKEN = 'SOURCEMAP_BROKEN', SOURCEMAP_ERROR = 'SOURCEMAP_ERROR', SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT = 'SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT', THIS_IS_UNDEFINED = 'THIS_IS_UNDEFINED', UNEXPECTED_NAMED_IMPORT = 'UNEXPECTED_NAMED_IMPORT', UNKNOWN_OPTION = 'UNKNOWN_OPTION', UNRESOLVED_ENTRY = 'UNRESOLVED_ENTRY', UNRESOLVED_IMPORT = 'UNRESOLVED_IMPORT', UNUSED_EXTERNAL_IMPORT = 'UNUSED_EXTERNAL_IMPORT', VALIDATION_ERROR = 'VALIDATION_ERROR';
  341. function logAddonNotGenerated(message, hook, plugin) {
  342. return {
  343. code: ADDON_ERROR,
  344. message: `Could not retrieve "${hook}". Check configuration of plugin "${plugin}".
  345. \tError Message: ${message}`
  346. };
  347. }
  348. function logAlreadyClosed() {
  349. return {
  350. code: ALREADY_CLOSED,
  351. message: 'Bundle is already closed, no more calls to "generate" or "write" are allowed.'
  352. };
  353. }
  354. function logAmbiguousExternalNamespaces(binding, reexportingModule, usedModule, sources) {
  355. return {
  356. binding,
  357. code: AMBIGUOUS_EXTERNAL_NAMESPACES,
  358. ids: sources,
  359. message: `Ambiguous external namespace resolution: "${relativeId(reexportingModule)}" re-exports "${binding}" from one of the external modules ${printQuotedStringList(sources.map(module => relativeId(module)))}, guessing "${relativeId(usedModule)}".`,
  360. reexporter: reexportingModule
  361. };
  362. }
  363. function logAnonymousPluginCache() {
  364. return {
  365. code: ANONYMOUS_PLUGIN_CACHE,
  366. message: 'A plugin is trying to use the Rollup cache but is not declaring a plugin name or cacheKey.'
  367. };
  368. }
  369. function logAssetNotFinalisedForFileName(name) {
  370. return {
  371. code: ASSET_NOT_FINALISED,
  372. message: `Plugin error - Unable to get file name for asset "${name}". Ensure that the source is set and that generate is called first. If you reference assets via import.meta.ROLLUP_FILE_URL_<referenceId>, you need to either have set their source after "renderStart" or need to provide an explicit "fileName" when emitting them.`
  373. };
  374. }
  375. function logAssetReferenceIdNotFoundForSetSource(assetReferenceId) {
  376. return {
  377. code: ASSET_NOT_FOUND,
  378. message: `Plugin error - Unable to set the source for unknown asset "${assetReferenceId}".`
  379. };
  380. }
  381. function logAssetSourceAlreadySet(name) {
  382. return {
  383. code: ASSET_SOURCE_ALREADY_SET,
  384. message: `Unable to set the source for asset "${name}", source already set.`
  385. };
  386. }
  387. function logNoAssetSourceSet(assetName) {
  388. return {
  389. code: ASSET_SOURCE_MISSING,
  390. message: `Plugin error creating asset "${assetName}" - no asset source set.`
  391. };
  392. }
  393. function logBadLoader(id) {
  394. return {
  395. code: BAD_LOADER,
  396. message: `Error loading "${relativeId(id)}": plugin load hook should return a string, a { code, map } object, or nothing/null.`
  397. };
  398. }
  399. function logCannotCallNamespace(name) {
  400. return {
  401. code: CANNOT_CALL_NAMESPACE,
  402. message: `Cannot call a namespace ("${name}").`
  403. };
  404. }
  405. function logCannotEmitFromOptionsHook() {
  406. return {
  407. code: CANNOT_EMIT_FROM_OPTIONS_HOOK,
  408. message: `Cannot emit files or set asset sources in the "outputOptions" hook, use the "renderStart" hook instead.`
  409. };
  410. }
  411. function logChunkNotGeneratedForFileName(name) {
  412. return {
  413. code: CHUNK_NOT_GENERATED,
  414. message: `Plugin error - Unable to get file name for emitted chunk "${name}". You can only get file names once chunks have been generated after the "renderStart" hook.`
  415. };
  416. }
  417. function logChunkInvalid({ fileName, code }, exception) {
  418. const errorProperties = {
  419. code: CHUNK_INVALID,
  420. message: `Chunk "${fileName}" is not valid JavaScript: ${exception.message}.`
  421. };
  422. augmentCodeLocation(errorProperties, exception.loc, code, fileName);
  423. return errorProperties;
  424. }
  425. function logCircularDependency(cyclePath) {
  426. return {
  427. code: CIRCULAR_DEPENDENCY,
  428. ids: cyclePath,
  429. message: `Circular dependency: ${cyclePath.map(relativeId).join(' -> ')}`
  430. };
  431. }
  432. function logCircularReexport(exportName, exporter) {
  433. return {
  434. code: CIRCULAR_REEXPORT,
  435. exporter,
  436. message: `"${exportName}" cannot be exported from "${relativeId(exporter)}" as it is a reexport that references itself.`
  437. };
  438. }
  439. function logCyclicCrossChunkReexport(exportName, exporter, reexporter, importer, preserveModules) {
  440. return {
  441. code: CYCLIC_CROSS_CHUNK_REEXPORT,
  442. exporter,
  443. id: importer,
  444. message: `Export "${exportName}" of module "${relativeId(exporter)}" was reexported through module "${relativeId(reexporter)}" while both modules are dependencies of each other and will end up in different chunks by current Rollup settings. This scenario is not well supported at the moment as it will produce a circular dependency between chunks and will likely lead to broken execution order.\nEither change the import in "${relativeId(importer)}" to point directly to the exporting module or ${preserveModules ? 'do not use "output.preserveModules"' : 'reconfigure "output.manualChunks"'} to ensure these modules end up in the same chunk.`,
  445. reexporter
  446. };
  447. }
  448. function logDeprecation(deprecation, urlSnippet, plugin) {
  449. return {
  450. code: DEPRECATED_FEATURE,
  451. message: deprecation,
  452. url: getRollupUrl(urlSnippet),
  453. ...(plugin ? { plugin } : {})
  454. };
  455. }
  456. function logDuplicateImportOptions() {
  457. return {
  458. code: DUPLICATE_IMPORT_OPTIONS,
  459. message: 'Either use --input, or pass input path as argument'
  460. };
  461. }
  462. function logDuplicatePluginName(plugin) {
  463. return {
  464. code: DUPLICATE_PLUGIN_NAME,
  465. message: `The plugin name ${plugin} is being used twice in the same build. Plugin names must be distinct or provide a cacheKey (please post an issue to the plugin if you are a plugin user).`
  466. };
  467. }
  468. function logEmptyChunk(chunkName) {
  469. return {
  470. code: EMPTY_BUNDLE,
  471. message: `Generated an empty chunk: "${chunkName}".`,
  472. names: [chunkName]
  473. };
  474. }
  475. function logEval(id) {
  476. return {
  477. code: EVAL,
  478. id,
  479. message: `Use of eval in "${relativeId(id)}" is strongly discouraged as it poses security risks and may cause issues with minification.`,
  480. url: getRollupUrl(URL_AVOIDING_EVAL)
  481. };
  482. }
  483. function logExternalSyntheticExports(id, importer) {
  484. return {
  485. code: EXTERNAL_SYNTHETIC_EXPORTS,
  486. exporter: id,
  487. message: `External "${id}" cannot have "syntheticNamedExports" enabled (imported by "${relativeId(importer)}").`
  488. };
  489. }
  490. function logFailAfterWarnings() {
  491. return {
  492. code: FAIL_AFTER_WARNINGS,
  493. message: 'Warnings occurred and --failAfterWarnings flag present.'
  494. };
  495. }
  496. function logFileNameConflict(fileName) {
  497. return {
  498. code: FILE_NAME_CONFLICT,
  499. message: `The emitted file "${fileName}" overwrites a previously emitted file of the same name.`
  500. };
  501. }
  502. function logFileReferenceIdNotFoundForFilename(assetReferenceId) {
  503. return {
  504. code: FILE_NOT_FOUND,
  505. message: `Plugin error - Unable to get file name for unknown file "${assetReferenceId}".`
  506. };
  507. }
  508. function logFirstSideEffect(source, id, { line, column }) {
  509. return {
  510. code: FIRST_SIDE_EFFECT,
  511. message: `First side effect in ${relativeId(id)} is at (${line}:${column})\n${getCodeFrame(source, line, column)}`
  512. };
  513. }
  514. function logIllegalIdentifierAsName(name) {
  515. return {
  516. code: ILLEGAL_IDENTIFIER_AS_NAME,
  517. message: `Given name "${name}" is not a legal JS identifier. If you need this, you can try "output.extend: true".`,
  518. url: getRollupUrl(URL_OUTPUT_EXTEND)
  519. };
  520. }
  521. function logIllegalImportReassignment(name, importingId) {
  522. return {
  523. code: ILLEGAL_REASSIGNMENT,
  524. message: `Illegal reassignment of import "${name}" in "${relativeId(importingId)}".`
  525. };
  526. }
  527. function logInconsistentImportAssertions(existingAssertions, newAssertions, source, importer) {
  528. return {
  529. code: INCONSISTENT_IMPORT_ASSERTIONS,
  530. message: `Module "${relativeId(importer)}" tried to import "${relativeId(source)}" with ${formatAssertions$1(newAssertions)} assertions, but it was already imported elsewhere with ${formatAssertions$1(existingAssertions)} assertions. Please ensure that import assertions for the same module are always consistent.`
  531. };
  532. }
  533. const formatAssertions$1 = (assertions) => {
  534. const entries = Object.entries(assertions);
  535. if (entries.length === 0)
  536. return 'no';
  537. return entries.map(([key, value]) => `"${key}": "${value}"`).join(', ');
  538. };
  539. function logInputHookInOutputPlugin(pluginName, hookName) {
  540. return {
  541. code: INPUT_HOOK_IN_OUTPUT_PLUGIN,
  542. message: `The "${hookName}" hook used by the output plugin ${pluginName} is a build time hook and will not be run for that plugin. Either this plugin cannot be used as an output plugin, or it should have an option to configure it as an output plugin.`
  543. };
  544. }
  545. function logCannotAssignModuleToChunk(moduleId, assignToAlias, currentAlias) {
  546. return {
  547. code: INVALID_CHUNK,
  548. message: `Cannot assign "${relativeId(moduleId)}" to the "${assignToAlias}" chunk as it is already in the "${currentAlias}" chunk.`
  549. };
  550. }
  551. function logCannotBundleConfigAsEsm(originalError) {
  552. return {
  553. cause: originalError,
  554. code: INVALID_CONFIG_MODULE_FORMAT,
  555. message: `Rollup transpiled your configuration to an ES module even though it appears to contain CommonJS elements. To resolve this, you can pass the "--bundleConfigAsCjs" flag to Rollup or change your configuration to only contain valid ESM code.\n\nOriginal error: ${originalError.message}`,
  556. stack: originalError.stack,
  557. url: getRollupUrl(URL_BUNDLE_CONFIG_AS_CJS)
  558. };
  559. }
  560. function logCannotLoadConfigAsCjs(originalError) {
  561. return {
  562. cause: originalError,
  563. code: INVALID_CONFIG_MODULE_FORMAT,
  564. message: `Node tried to load your configuration file as CommonJS even though it is likely an ES module. To resolve this, change the extension of your configuration to ".mjs", set "type": "module" in your package.json file or pass the "--bundleConfigAsCjs" flag.\n\nOriginal error: ${originalError.message}`,
  565. stack: originalError.stack,
  566. url: getRollupUrl(URL_BUNDLE_CONFIG_AS_CJS)
  567. };
  568. }
  569. function logCannotLoadConfigAsEsm(originalError) {
  570. return {
  571. cause: originalError,
  572. code: INVALID_CONFIG_MODULE_FORMAT,
  573. message: `Node tried to load your configuration as an ES module even though it is likely CommonJS. To resolve this, change the extension of your configuration to ".cjs" or pass the "--bundleConfigAsCjs" flag.\n\nOriginal error: ${originalError.message}`,
  574. stack: originalError.stack,
  575. url: getRollupUrl(URL_BUNDLE_CONFIG_AS_CJS)
  576. };
  577. }
  578. function logInvalidExportOptionValue(optionValue) {
  579. return {
  580. code: INVALID_EXPORT_OPTION,
  581. message: `"output.exports" must be "default", "named", "none", "auto", or left unspecified (defaults to "auto"), received "${optionValue}".`,
  582. url: getRollupUrl(URL_OUTPUT_EXPORTS)
  583. };
  584. }
  585. function logIncompatibleExportOptionValue(optionValue, keys, entryModule) {
  586. return {
  587. code: INVALID_EXPORT_OPTION,
  588. message: `"${optionValue}" was specified for "output.exports", but entry module "${relativeId(entryModule)}" has the following exports: ${printQuotedStringList(keys)}`,
  589. url: getRollupUrl(URL_OUTPUT_EXPORTS)
  590. };
  591. }
  592. function logInternalIdCannotBeExternal(source, importer) {
  593. return {
  594. code: INVALID_EXTERNAL_ID,
  595. message: `"${source}" is imported as an external by "${relativeId(importer)}", but is already an existing non-external module id.`
  596. };
  597. }
  598. function logInvalidLogPosition(plugin) {
  599. return {
  600. code: INVALID_LOG_POSITION,
  601. message: `Plugin "${plugin}" tried to add a file position to a log or warning. This is only supported in the "transform" hook at the moment and will be ignored.`
  602. };
  603. }
  604. function logInvalidOption(option, urlSnippet, explanation, value) {
  605. return {
  606. code: INVALID_OPTION,
  607. message: `Invalid value ${value === undefined ? '' : `${JSON.stringify(value)} `}for option "${option}" - ${explanation}.`,
  608. url: getRollupUrl(urlSnippet)
  609. };
  610. }
  611. function logInvalidAddonPluginHook(hook, plugin) {
  612. return {
  613. code: INVALID_PLUGIN_HOOK,
  614. hook,
  615. message: `Error running plugin hook "${hook}" for plugin "${plugin}", expected a string, a function hook or an object with a "handler" string or function.`,
  616. plugin
  617. };
  618. }
  619. function logInvalidFunctionPluginHook(hook, plugin) {
  620. return {
  621. code: INVALID_PLUGIN_HOOK,
  622. hook,
  623. message: `Error running plugin hook "${hook}" for plugin "${plugin}", expected a function hook or an object with a "handler" function.`,
  624. plugin
  625. };
  626. }
  627. function logInvalidRollupPhaseForAddWatchFile() {
  628. return {
  629. code: INVALID_ROLLUP_PHASE,
  630. message: `Cannot call "addWatchFile" after the build has finished.`
  631. };
  632. }
  633. function logInvalidRollupPhaseForChunkEmission() {
  634. return {
  635. code: INVALID_ROLLUP_PHASE,
  636. message: `Cannot emit chunks after module loading has finished.`
  637. };
  638. }
  639. function logInvalidSetAssetSourceCall() {
  640. return {
  641. code: INVALID_SETASSETSOURCE,
  642. message: `setAssetSource cannot be called in transform for caching reasons. Use emitFile with a source, or call setAssetSource in another hook.`
  643. };
  644. }
  645. function logInvalidFormatForTopLevelAwait(id, format) {
  646. return {
  647. code: INVALID_TLA_FORMAT,
  648. id,
  649. message: `Module format "${format}" does not support top-level await. Use the "es" or "system" output formats rather.`
  650. };
  651. }
  652. function logMissingConfig() {
  653. return {
  654. code: MISSING_CONFIG,
  655. message: 'Config file must export an options object, or an array of options objects',
  656. url: getRollupUrl(URL_CONFIGURATION_FILES)
  657. };
  658. }
  659. function logMissingExport(binding, importingModule, exporter) {
  660. const isJson = node_path.extname(exporter) === '.json';
  661. return {
  662. binding,
  663. code: MISSING_EXPORT,
  664. exporter,
  665. id: importingModule,
  666. message: `"${binding}" is not exported by "${relativeId(exporter)}", imported by "${relativeId(importingModule)}".${isJson ? ' (Note that you need @rollup/plugin-json to import JSON files)' : ''}`,
  667. url: getRollupUrl(URL_NAME_IS_NOT_EXPORTED)
  668. };
  669. }
  670. function logMissingExternalConfig(file) {
  671. return {
  672. code: MISSING_EXTERNAL_CONFIG,
  673. message: `Could not resolve config file "${file}"`
  674. };
  675. }
  676. function logMissingGlobalName(externalId, guess) {
  677. return {
  678. code: MISSING_GLOBAL_NAME,
  679. id: externalId,
  680. message: `No name was provided for external module "${externalId}" in "output.globals" – guessing "${guess}".`,
  681. names: [guess],
  682. url: getRollupUrl(URL_OUTPUT_GLOBALS)
  683. };
  684. }
  685. function logImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore) {
  686. return {
  687. code: MISSING_IMPLICIT_DEPENDANT,
  688. message: `Module "${relativeId(unresolvedId)}" that should be implicitly loaded before "${relativeId(implicitlyLoadedBefore)}" cannot be external.`
  689. };
  690. }
  691. function logUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore) {
  692. return {
  693. code: MISSING_IMPLICIT_DEPENDANT,
  694. message: `Module "${relativeId(unresolvedId)}" that should be implicitly loaded before "${relativeId(implicitlyLoadedBefore)}" could not be resolved.`
  695. };
  696. }
  697. function logImplicitDependantIsNotIncluded(module) {
  698. const implicitDependencies = [...module.implicitlyLoadedBefore]
  699. .map(dependency => relativeId(dependency.id))
  700. .sort();
  701. return {
  702. code: MISSING_IMPLICIT_DEPENDANT,
  703. message: `Module "${relativeId(module.id)}" that should be implicitly loaded before ${printQuotedStringList(implicitDependencies)} is not included in the module graph. Either it was not imported by an included module or only via a tree-shaken dynamic import, or no imported bindings were used and it had otherwise no side-effects.`
  704. };
  705. }
  706. function logMissingNameOptionForIifeExport() {
  707. return {
  708. code: MISSING_NAME_OPTION_FOR_IIFE_EXPORT,
  709. message: `If you do not supply "output.name", you may not be able to access the exports of an IIFE bundle.`,
  710. url: getRollupUrl(URL_OUTPUT_NAME)
  711. };
  712. }
  713. function logMissingNameOptionForUmdExport() {
  714. return {
  715. code: MISSING_NAME_OPTION_FOR_IIFE_EXPORT,
  716. message: 'You must supply "output.name" for UMD bundles that have exports so that the exports are accessible in environments without a module loader.',
  717. url: getRollupUrl(URL_OUTPUT_NAME)
  718. };
  719. }
  720. function logMissingNodeBuiltins(externalBuiltins) {
  721. return {
  722. code: MISSING_NODE_BUILTINS,
  723. ids: externalBuiltins,
  724. message: `Creating a browser bundle that depends on Node.js built-in modules (${printQuotedStringList(externalBuiltins)}). You might need to include https://github.com/FredKSchott/rollup-plugin-polyfill-node`
  725. };
  726. }
  727. // eslint-disable-next-line unicorn/prevent-abbreviations
  728. function logMissingFileOrDirOption() {
  729. return {
  730. code: MISSING_OPTION,
  731. message: 'You must specify "output.file" or "output.dir" for the build.',
  732. url: getRollupUrl(URL_OUTPUT_DIR)
  733. };
  734. }
  735. function logMixedExport(facadeModuleId, name) {
  736. return {
  737. code: MIXED_EXPORTS,
  738. id: facadeModuleId,
  739. message: `Entry module "${relativeId(facadeModuleId)}" is using named and default exports together. Consumers of your bundle will have to use \`${name || 'chunk'}.default\` to access the default export, which may not be what you want. Use \`output.exports: "named"\` to disable this warning.`,
  740. url: getRollupUrl(URL_OUTPUT_EXPORTS)
  741. };
  742. }
  743. function logModuleLevelDirective(directive, id) {
  744. return {
  745. code: MODULE_LEVEL_DIRECTIVE,
  746. id,
  747. message: `Module level directives cause errors when bundled, "${directive}" in "${relativeId(id)}" was ignored.`
  748. };
  749. }
  750. function logNamespaceConflict(binding, reexportingModuleId, sources) {
  751. return {
  752. binding,
  753. code: NAMESPACE_CONFLICT,
  754. ids: sources,
  755. message: `Conflicting namespaces: "${relativeId(reexportingModuleId)}" re-exports "${binding}" from one of the modules ${printQuotedStringList(sources.map(moduleId => relativeId(moduleId)))} (will be ignored).`,
  756. reexporter: reexportingModuleId
  757. };
  758. }
  759. function logNoTransformMapOrAstWithoutCode(pluginName) {
  760. return {
  761. code: NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE,
  762. message: `The plugin "${pluginName}" returned a "map" or "ast" without returning ` +
  763. 'a "code". This will be ignored.'
  764. };
  765. }
  766. function logOnlyInlineSourcemapsForStdout() {
  767. return {
  768. code: ONLY_INLINE_SOURCEMAPS,
  769. message: 'Only inline sourcemaps are supported when bundling to stdout.'
  770. };
  771. }
  772. function logOptimizeChunkStatus(chunks, smallChunks, pointInTime) {
  773. return {
  774. code: OPTIMIZE_CHUNK_STATUS,
  775. message: `${pointInTime}, there are\n` +
  776. `${chunks} chunks, of which\n` +
  777. `${smallChunks} are below minChunkSize.`
  778. };
  779. }
  780. function logParseError(error, moduleId) {
  781. let message = error.message.replace(/ \(\d+:\d+\)$/, '');
  782. if (moduleId.endsWith('.json')) {
  783. message += ' (Note that you need @rollup/plugin-json to import JSON files)';
  784. }
  785. else if (!moduleId.endsWith('.js')) {
  786. message += ' (Note that you need plugins to import files that are not JavaScript)';
  787. }
  788. return {
  789. cause: error,
  790. code: PARSE_ERROR,
  791. id: moduleId,
  792. message
  793. };
  794. }
  795. function logPluginError(error, plugin, { hook, id } = {}) {
  796. const code = error.code;
  797. if (!error.pluginCode &&
  798. code != null &&
  799. (typeof code !== 'string' || (typeof code === 'string' && !code.startsWith('PLUGIN_')))) {
  800. error.pluginCode = code;
  801. }
  802. error.code = PLUGIN_ERROR;
  803. error.plugin = plugin;
  804. if (hook) {
  805. error.hook = hook;
  806. }
  807. if (id) {
  808. error.id = id;
  809. }
  810. return error;
  811. }
  812. function logShimmedExport(id, binding) {
  813. return {
  814. binding,
  815. code: SHIMMED_EXPORT,
  816. exporter: id,
  817. message: `Missing export "${binding}" has been shimmed in module "${relativeId(id)}".`
  818. };
  819. }
  820. function logSourcemapBroken(plugin) {
  821. return {
  822. code: SOURCEMAP_BROKEN,
  823. message: `Sourcemap is likely to be incorrect: a plugin (${plugin}) was used to transform files, but didn't generate a sourcemap for the transformation. Consult the plugin documentation for help`,
  824. plugin,
  825. url: getRollupUrl(URL_SOURCEMAP_IS_LIKELY_TO_BE_INCORRECT)
  826. };
  827. }
  828. function logConflictingSourcemapSources(filename) {
  829. return {
  830. code: SOURCEMAP_BROKEN,
  831. message: `Multiple conflicting contents for sourcemap source ${filename}`
  832. };
  833. }
  834. function logInvalidSourcemapForError(error, id, column, line, pos) {
  835. return {
  836. cause: error,
  837. code: SOURCEMAP_ERROR,
  838. id,
  839. loc: {
  840. column,
  841. file: id,
  842. line
  843. },
  844. message: `Error when using sourcemap for reporting an error: ${error.message}`,
  845. pos
  846. };
  847. }
  848. function logSyntheticNamedExportsNeedNamespaceExport(id, syntheticNamedExportsOption) {
  849. return {
  850. code: SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT,
  851. exporter: id,
  852. message: `Module "${relativeId(id)}" that is marked with \`syntheticNamedExports: ${JSON.stringify(syntheticNamedExportsOption)}\` needs ${typeof syntheticNamedExportsOption === 'string' && syntheticNamedExportsOption !== 'default'
  853. ? `an explicit export named "${syntheticNamedExportsOption}"`
  854. : 'a default export'} that does not reexport an unresolved named export of the same module.`
  855. };
  856. }
  857. function logThisIsUndefined() {
  858. return {
  859. code: THIS_IS_UNDEFINED,
  860. message: `The 'this' keyword is equivalent to 'undefined' at the top level of an ES module, and has been rewritten`,
  861. url: getRollupUrl(URL_THIS_IS_UNDEFINED)
  862. };
  863. }
  864. function logUnexpectedNamedImport(id, imported, isReexport) {
  865. const importType = isReexport ? 'reexport' : 'import';
  866. return {
  867. code: UNEXPECTED_NAMED_IMPORT,
  868. exporter: id,
  869. message: `The named export "${imported}" was ${importType}ed from the external module "${relativeId(id)}" even though its interop type is "defaultOnly". Either remove or change this ${importType} or change the value of the "output.interop" option.`,
  870. url: getRollupUrl(URL_OUTPUT_INTEROP)
  871. };
  872. }
  873. function logUnexpectedNamespaceReexport(id) {
  874. return {
  875. code: UNEXPECTED_NAMED_IMPORT,
  876. exporter: id,
  877. message: `There was a namespace "*" reexport from the external module "${relativeId(id)}" even though its interop type is "defaultOnly". This will be ignored as namespace reexports only reexport named exports. If this is not intended, either remove or change this reexport or change the value of the "output.interop" option.`,
  878. url: getRollupUrl(URL_OUTPUT_INTEROP)
  879. };
  880. }
  881. function logUnknownOption(optionType, unknownOptions, validOptions) {
  882. return {
  883. code: UNKNOWN_OPTION,
  884. message: `Unknown ${optionType}: ${unknownOptions.join(', ')}. Allowed options: ${validOptions.join(', ')}`
  885. };
  886. }
  887. function logEntryCannotBeExternal(unresolvedId) {
  888. return {
  889. code: UNRESOLVED_ENTRY,
  890. message: `Entry module "${relativeId(unresolvedId)}" cannot be external.`
  891. };
  892. }
  893. function logExternalModulesCannotBeIncludedInManualChunks(source) {
  894. return {
  895. code: EXTERNAL_MODULES_CANNOT_BE_INCLUDED_IN_MANUAL_CHUNKS,
  896. message: `"${source}" cannot be included in manualChunks because it is resolved as an external module by the "external" option or plugins.`
  897. };
  898. }
  899. function logExternalModulesCannotBeTransformedToModules(source) {
  900. return {
  901. code: EXTERNAL_MODULES_CANNOT_BE_TRANSFORMED_TO_MODULES,
  902. message: `${source} is resolved as a module now, but it was an external module before. Please check whether there are conflicts in your Rollup options "external" and "manualChunks", manualChunks cannot include external modules.`
  903. };
  904. }
  905. function logUnresolvedEntry(unresolvedId) {
  906. return {
  907. code: UNRESOLVED_ENTRY,
  908. message: `Could not resolve entry module "${relativeId(unresolvedId)}".`
  909. };
  910. }
  911. function logUnresolvedImport(source, importer) {
  912. return {
  913. code: UNRESOLVED_IMPORT,
  914. exporter: source,
  915. id: importer,
  916. message: `Could not resolve "${source}" from "${relativeId(importer)}"`
  917. };
  918. }
  919. function logUnresolvedImportTreatedAsExternal(source, importer) {
  920. return {
  921. code: UNRESOLVED_IMPORT,
  922. exporter: source,
  923. id: importer,
  924. message: `"${source}" is imported by "${relativeId(importer)}", but could not be resolved – treating it as an external dependency.`,
  925. url: getRollupUrl(URL_TREATING_MODULE_AS_EXTERNAL_DEPENDENCY)
  926. };
  927. }
  928. function logUnusedExternalImports(externalId, names, importers) {
  929. return {
  930. code: UNUSED_EXTERNAL_IMPORT,
  931. exporter: externalId,
  932. ids: importers,
  933. message: `${printQuotedStringList(names, [
  934. 'is',
  935. 'are'
  936. ])} imported from external module "${externalId}" but never used in ${printQuotedStringList(importers.map(importer => relativeId(importer)))}.`,
  937. names
  938. };
  939. }
  940. function logFailedValidation(message) {
  941. return {
  942. code: VALIDATION_ERROR,
  943. message
  944. };
  945. }
  946. function warnDeprecation(deprecation, urlSnippet, activeDeprecation, options, plugin) {
  947. warnDeprecationWithOptions(deprecation, urlSnippet, activeDeprecation, options.onLog, options.strictDeprecations, plugin);
  948. }
  949. function warnDeprecationWithOptions(deprecation, urlSnippet, activeDeprecation, log, strictDeprecations, plugin) {
  950. if (activeDeprecation || strictDeprecations) {
  951. const warning = logDeprecation(deprecation, urlSnippet, plugin);
  952. if (strictDeprecations) {
  953. return error(warning);
  954. }
  955. log(LOGLEVEL_WARN, warning);
  956. }
  957. }
  958. // Four random characters from the private use area to minimize risk of
  959. // conflicts
  960. const hashPlaceholderLeft = '!~{';
  961. const hashPlaceholderRight = '}~';
  962. const hashPlaceholderOverhead = hashPlaceholderLeft.length + hashPlaceholderRight.length;
  963. // This is the size of a sha256
  964. const maxHashSize = 64;
  965. const defaultHashSize = 8;
  966. const getHashPlaceholderGenerator = () => {
  967. let nextIndex = 0;
  968. return (optionName, hashSize = defaultHashSize) => {
  969. if (hashSize > maxHashSize) {
  970. return error(logFailedValidation(`Hashes cannot be longer than ${maxHashSize} characters, received ${hashSize}. Check the "${optionName}" option.`));
  971. }
  972. const placeholder = `${hashPlaceholderLeft}${toBase64(++nextIndex).padStart(hashSize - hashPlaceholderOverhead, '0')}${hashPlaceholderRight}`;
  973. if (placeholder.length > hashSize) {
  974. return error(logFailedValidation(`To generate hashes for this number of chunks (currently ${nextIndex}), you need a minimum hash size of ${placeholder.length}, received ${hashSize}. Check the "${optionName}" option.`));
  975. }
  976. return placeholder;
  977. };
  978. };
  979. const REPLACER_REGEX = new RegExp(`${hashPlaceholderLeft}[0-9a-zA-Z_$]{1,${maxHashSize - hashPlaceholderOverhead}}${hashPlaceholderRight}`, 'g');
  980. const replacePlaceholders = (code, hashesByPlaceholder) => code.replace(REPLACER_REGEX, placeholder => hashesByPlaceholder.get(placeholder) || placeholder);
  981. const replaceSinglePlaceholder = (code, placeholder, value) => code.replace(REPLACER_REGEX, match => (match === placeholder ? value : match));
  982. const replacePlaceholdersWithDefaultAndGetContainedPlaceholders = (code, placeholders) => {
  983. const containedPlaceholders = new Set();
  984. const transformedCode = code.replace(REPLACER_REGEX, placeholder => {
  985. if (placeholders.has(placeholder)) {
  986. containedPlaceholders.add(placeholder);
  987. return `${hashPlaceholderLeft}${'0'.repeat(placeholder.length - hashPlaceholderOverhead)}${hashPlaceholderRight}`;
  988. }
  989. return placeholder;
  990. });
  991. return { containedPlaceholders, transformedCode };
  992. };
  993. const lowercaseBundleKeys = Symbol('bundleKeys');
  994. const FILE_PLACEHOLDER = {
  995. type: 'placeholder'
  996. };
  997. const getOutputBundle = (outputBundleBase) => {
  998. const reservedLowercaseBundleKeys = new Set();
  999. return new Proxy(outputBundleBase, {
  1000. deleteProperty(target, key) {
  1001. if (typeof key === 'string') {
  1002. reservedLowercaseBundleKeys.delete(key.toLowerCase());
  1003. }
  1004. return Reflect.deleteProperty(target, key);
  1005. },
  1006. get(target, key) {
  1007. if (key === lowercaseBundleKeys) {
  1008. return reservedLowercaseBundleKeys;
  1009. }
  1010. return Reflect.get(target, key);
  1011. },
  1012. set(target, key, value) {
  1013. if (typeof key === 'string') {
  1014. reservedLowercaseBundleKeys.add(key.toLowerCase());
  1015. }
  1016. return Reflect.set(target, key, value);
  1017. }
  1018. });
  1019. };
  1020. const removeUnreferencedAssets = (outputBundle) => {
  1021. const unreferencedAssets = new Set();
  1022. const bundleEntries = Object.values(outputBundle);
  1023. for (const asset of bundleEntries) {
  1024. asset.type === 'asset' && asset.needsCodeReference && unreferencedAssets.add(asset.fileName);
  1025. }
  1026. for (const chunk of bundleEntries) {
  1027. if (chunk.type === 'chunk') {
  1028. for (const referencedFile of chunk.referencedFiles) {
  1029. unreferencedAssets.has(referencedFile) && unreferencedAssets.delete(referencedFile);
  1030. }
  1031. }
  1032. }
  1033. for (const file of unreferencedAssets) {
  1034. delete outputBundle[file];
  1035. }
  1036. };
  1037. function renderNamePattern(pattern, patternName, replacements) {
  1038. if (isPathFragment(pattern))
  1039. return error(logFailedValidation(`Invalid pattern "${pattern}" for "${patternName}", patterns can be neither absolute nor relative paths. If you want your files to be stored in a subdirectory, write its name without a leading slash like this: subdirectory/pattern.`));
  1040. return pattern.replace(/\[(\w+)(:\d+)?]/g, (_match, type, size) => {
  1041. if (!replacements.hasOwnProperty(type) || (size && type !== 'hash')) {
  1042. return error(logFailedValidation(`"[${type}${size || ''}]" is not a valid placeholder in the "${patternName}" pattern.`));
  1043. }
  1044. const replacement = replacements[type](size && Number.parseInt(size.slice(1)));
  1045. if (isPathFragment(replacement))
  1046. return error(logFailedValidation(`Invalid substitution "${replacement}" for placeholder "[${type}]" in "${patternName}" pattern, can be neither absolute nor relative path.`));
  1047. return replacement;
  1048. });
  1049. }
  1050. function makeUnique(name, { [lowercaseBundleKeys]: reservedLowercaseBundleKeys }) {
  1051. if (!reservedLowercaseBundleKeys.has(name.toLowerCase()))
  1052. return name;
  1053. const extension = node_path.extname(name);
  1054. name = name.slice(0, Math.max(0, name.length - extension.length));
  1055. let uniqueName, uniqueIndex = 1;
  1056. while (reservedLowercaseBundleKeys.has((uniqueName = name + ++uniqueIndex + extension).toLowerCase()))
  1057. ;
  1058. return uniqueName;
  1059. }
  1060. function getSourceHash(source) {
  1061. return createHash().update(source).digest('hex');
  1062. }
  1063. function generateAssetFileName(name, source, sourceHash, outputOptions, bundle) {
  1064. const emittedName = outputOptions.sanitizeFileName(name || 'asset');
  1065. return makeUnique(renderNamePattern(typeof outputOptions.assetFileNames === 'function'
  1066. ? outputOptions.assetFileNames({ name, source, type: 'asset' })
  1067. : outputOptions.assetFileNames, 'output.assetFileNames', {
  1068. ext: () => node_path.extname(emittedName).slice(1),
  1069. extname: () => node_path.extname(emittedName),
  1070. hash: size => sourceHash.slice(0, Math.max(0, size || defaultHashSize)),
  1071. name: () => emittedName.slice(0, Math.max(0, emittedName.length - node_path.extname(emittedName).length))
  1072. }), bundle);
  1073. }
  1074. function reserveFileNameInBundle(fileName, { bundle }, log) {
  1075. if (bundle[lowercaseBundleKeys].has(fileName.toLowerCase())) {
  1076. log(LOGLEVEL_WARN, logFileNameConflict(fileName));
  1077. }
  1078. else {
  1079. bundle[fileName] = FILE_PLACEHOLDER;
  1080. }
  1081. }
  1082. const emittedFileTypes = new Set(['chunk', 'asset', 'prebuilt-chunk']);
  1083. function hasValidType(emittedFile) {
  1084. return Boolean(emittedFile &&
  1085. emittedFileTypes.has(emittedFile.type));
  1086. }
  1087. function hasValidName(emittedFile) {
  1088. const validatedName = emittedFile.fileName || emittedFile.name;
  1089. return !validatedName || (typeof validatedName === 'string' && !isPathFragment(validatedName));
  1090. }
  1091. function getValidSource(source, emittedFile, fileReferenceId) {
  1092. if (!(typeof source === 'string' || source instanceof Uint8Array)) {
  1093. const assetName = emittedFile.fileName || emittedFile.name || fileReferenceId;
  1094. return error(logFailedValidation(`Could not set source for ${typeof assetName === 'string' ? `asset "${assetName}"` : 'unnamed asset'}, asset source needs to be a string, Uint8Array or Buffer.`));
  1095. }
  1096. return source;
  1097. }
  1098. function getAssetFileName(file, referenceId) {
  1099. if (typeof file.fileName !== 'string') {
  1100. return error(logAssetNotFinalisedForFileName(file.name || referenceId));
  1101. }
  1102. return file.fileName;
  1103. }
  1104. function getChunkFileName(file, facadeChunkByModule) {
  1105. if (file.fileName) {
  1106. return file.fileName;
  1107. }
  1108. if (facadeChunkByModule) {
  1109. return facadeChunkByModule.get(file.module).getFileName();
  1110. }
  1111. return error(logChunkNotGeneratedForFileName(file.fileName || file.name));
  1112. }
  1113. class FileEmitter {
  1114. constructor(graph, options, baseFileEmitter) {
  1115. this.graph = graph;
  1116. this.options = options;
  1117. this.facadeChunkByModule = null;
  1118. this.nextIdBase = 1;
  1119. this.output = null;
  1120. this.outputFileEmitters = [];
  1121. this.emitFile = (emittedFile) => {
  1122. if (!hasValidType(emittedFile)) {
  1123. return error(logFailedValidation(`Emitted files must be of type "asset", "chunk" or "prebuilt-chunk", received "${emittedFile && emittedFile.type}".`));
  1124. }
  1125. if (emittedFile.type === 'prebuilt-chunk') {
  1126. return this.emitPrebuiltChunk(emittedFile);
  1127. }
  1128. if (!hasValidName(emittedFile)) {
  1129. return error(logFailedValidation(`The "fileName" or "name" properties of emitted chunks and assets must be strings that are neither absolute nor relative paths, received "${emittedFile.fileName || emittedFile.name}".`));
  1130. }
  1131. if (emittedFile.type === 'chunk') {
  1132. return this.emitChunk(emittedFile);
  1133. }
  1134. return this.emitAsset(emittedFile);
  1135. };
  1136. this.finaliseAssets = () => {
  1137. for (const [referenceId, emittedFile] of this.filesByReferenceId) {
  1138. if (emittedFile.type === 'asset' && typeof emittedFile.fileName !== 'string')
  1139. return error(logNoAssetSourceSet(emittedFile.name || referenceId));
  1140. }
  1141. };
  1142. this.getFileName = (fileReferenceId) => {
  1143. const emittedFile = this.filesByReferenceId.get(fileReferenceId);
  1144. if (!emittedFile)
  1145. return error(logFileReferenceIdNotFoundForFilename(fileReferenceId));
  1146. if (emittedFile.type === 'chunk') {
  1147. return getChunkFileName(emittedFile, this.facadeChunkByModule);
  1148. }
  1149. if (emittedFile.type === 'prebuilt-chunk') {
  1150. return emittedFile.fileName;
  1151. }
  1152. return getAssetFileName(emittedFile, fileReferenceId);
  1153. };
  1154. this.setAssetSource = (referenceId, requestedSource) => {
  1155. const consumedFile = this.filesByReferenceId.get(referenceId);
  1156. if (!consumedFile)
  1157. return error(logAssetReferenceIdNotFoundForSetSource(referenceId));
  1158. if (consumedFile.type !== 'asset') {
  1159. return error(logFailedValidation(`Asset sources can only be set for emitted assets but "${referenceId}" is an emitted chunk.`));
  1160. }
  1161. if (consumedFile.source !== undefined) {
  1162. return error(logAssetSourceAlreadySet(consumedFile.name || referenceId));
  1163. }
  1164. const source = getValidSource(requestedSource, consumedFile, referenceId);
  1165. if (this.output) {
  1166. this.finalizeAdditionalAsset(consumedFile, source, this.output);
  1167. }
  1168. else {
  1169. consumedFile.source = source;
  1170. for (const emitter of this.outputFileEmitters) {
  1171. emitter.finalizeAdditionalAsset(consumedFile, source, emitter.output);
  1172. }
  1173. }
  1174. };
  1175. this.setChunkInformation = (facadeChunkByModule) => {
  1176. this.facadeChunkByModule = facadeChunkByModule;
  1177. };
  1178. this.setOutputBundle = (bundle, outputOptions) => {
  1179. const output = (this.output = {
  1180. bundle,
  1181. fileNamesBySource: new Map(),
  1182. outputOptions
  1183. });
  1184. for (const emittedFile of this.filesByReferenceId.values()) {
  1185. if (emittedFile.fileName) {
  1186. reserveFileNameInBundle(emittedFile.fileName, output, this.options.onLog);
  1187. }
  1188. }
  1189. const consumedAssetsByHash = new Map();
  1190. for (const consumedFile of this.filesByReferenceId.values()) {
  1191. if (consumedFile.type === 'asset' && consumedFile.source !== undefined) {
  1192. if (consumedFile.fileName) {
  1193. this.finalizeAdditionalAsset(consumedFile, consumedFile.source, output);
  1194. }
  1195. else {
  1196. const sourceHash = getSourceHash(consumedFile.source);
  1197. getOrCreate(consumedAssetsByHash, sourceHash, () => []).push(consumedFile);
  1198. }
  1199. }
  1200. else if (consumedFile.type === 'prebuilt-chunk') {
  1201. this.output.bundle[consumedFile.fileName] = this.createPrebuiltChunk(consumedFile);
  1202. }
  1203. }
  1204. for (const [sourceHash, consumedFiles] of consumedAssetsByHash) {
  1205. this.finalizeAssetsWithSameSource(consumedFiles, sourceHash, output);
  1206. }
  1207. };
  1208. this.filesByReferenceId = baseFileEmitter
  1209. ? new Map(baseFileEmitter.filesByReferenceId)
  1210. : new Map();
  1211. baseFileEmitter?.addOutputFileEmitter(this);
  1212. }
  1213. addOutputFileEmitter(outputFileEmitter) {
  1214. this.outputFileEmitters.push(outputFileEmitter);
  1215. }
  1216. assignReferenceId(file, idBase) {
  1217. let referenceId = idBase;
  1218. do {
  1219. referenceId = createHash().update(referenceId).digest('hex').slice(0, 8);
  1220. } while (this.filesByReferenceId.has(referenceId) ||
  1221. this.outputFileEmitters.some(({ filesByReferenceId }) => filesByReferenceId.has(referenceId)));
  1222. file.referenceId = referenceId;
  1223. this.filesByReferenceId.set(referenceId, file);
  1224. for (const { filesByReferenceId } of this.outputFileEmitters) {
  1225. filesByReferenceId.set(referenceId, file);
  1226. }
  1227. return referenceId;
  1228. }
  1229. createPrebuiltChunk(prebuiltChunk) {
  1230. return {
  1231. code: prebuiltChunk.code,
  1232. dynamicImports: [],
  1233. exports: prebuiltChunk.exports || [],
  1234. facadeModuleId: null,
  1235. fileName: prebuiltChunk.fileName,
  1236. implicitlyLoadedBefore: [],
  1237. importedBindings: {},
  1238. imports: [],
  1239. isDynamicEntry: false,
  1240. isEntry: false,
  1241. isImplicitEntry: false,
  1242. map: prebuiltChunk.map || null,
  1243. moduleIds: [],
  1244. modules: {},
  1245. name: prebuiltChunk.fileName,
  1246. preliminaryFileName: prebuiltChunk.fileName,
  1247. referencedFiles: [],
  1248. sourcemapFileName: prebuiltChunk.sourcemapFileName || null,
  1249. type: 'chunk'
  1250. };
  1251. }
  1252. emitAsset(emittedAsset) {
  1253. const source = emittedAsset.source === undefined
  1254. ? undefined
  1255. : getValidSource(emittedAsset.source, emittedAsset, null);
  1256. const consumedAsset = {
  1257. fileName: emittedAsset.fileName,
  1258. name: emittedAsset.name,
  1259. needsCodeReference: !!emittedAsset.needsCodeReference,
  1260. referenceId: '',
  1261. source,
  1262. type: 'asset'
  1263. };
  1264. const referenceId = this.assignReferenceId(consumedAsset, emittedAsset.fileName || emittedAsset.name || String(this.nextIdBase++));
  1265. if (this.output) {
  1266. this.emitAssetWithReferenceId(consumedAsset, this.output);
  1267. }
  1268. else {
  1269. for (const fileEmitter of this.outputFileEmitters) {
  1270. fileEmitter.emitAssetWithReferenceId(consumedAsset, fileEmitter.output);
  1271. }
  1272. }
  1273. return referenceId;
  1274. }
  1275. emitAssetWithReferenceId(consumedAsset, output) {
  1276. const { fileName, source } = consumedAsset;
  1277. if (fileName) {
  1278. reserveFileNameInBundle(fileName, output, this.options.onLog);
  1279. }
  1280. if (source !== undefined) {
  1281. this.finalizeAdditionalAsset(consumedAsset, source, output);
  1282. }
  1283. }
  1284. emitChunk(emittedChunk) {
  1285. if (this.graph.phase > BuildPhase.LOAD_AND_PARSE) {
  1286. return error(logInvalidRollupPhaseForChunkEmission());
  1287. }
  1288. if (typeof emittedChunk.id !== 'string') {
  1289. return error(logFailedValidation(`Emitted chunks need to have a valid string id, received "${emittedChunk.id}"`));
  1290. }
  1291. const consumedChunk = {
  1292. fileName: emittedChunk.fileName,
  1293. module: null,
  1294. name: emittedChunk.name || emittedChunk.id,
  1295. referenceId: '',
  1296. type: 'chunk'
  1297. };
  1298. this.graph.moduleLoader
  1299. .emitChunk(emittedChunk)
  1300. .then(module => (consumedChunk.module = module))
  1301. .catch(() => {
  1302. // Avoid unhandled Promise rejection as the error will be thrown later
  1303. // once module loading has finished
  1304. });
  1305. return this.assignReferenceId(consumedChunk, emittedChunk.id);
  1306. }
  1307. emitPrebuiltChunk(emitPrebuiltChunk) {
  1308. if (typeof emitPrebuiltChunk.code !== 'string') {
  1309. return error(logFailedValidation(`Emitted prebuilt chunks need to have a valid string code, received "${emitPrebuiltChunk.code}".`));
  1310. }
  1311. if (typeof emitPrebuiltChunk.fileName !== 'string' ||
  1312. isPathFragment(emitPrebuiltChunk.fileName)) {
  1313. return error(logFailedValidation(`The "fileName" property of emitted prebuilt chunks must be strings that are neither absolute nor relative paths, received "${emitPrebuiltChunk.fileName}".`));
  1314. }
  1315. const consumedPrebuiltChunk = {
  1316. code: emitPrebuiltChunk.code,
  1317. exports: emitPrebuiltChunk.exports,
  1318. fileName: emitPrebuiltChunk.fileName,
  1319. map: emitPrebuiltChunk.map,
  1320. referenceId: '',
  1321. type: 'prebuilt-chunk'
  1322. };
  1323. const referenceId = this.assignReferenceId(consumedPrebuiltChunk, consumedPrebuiltChunk.fileName);
  1324. if (this.output) {
  1325. this.output.bundle[consumedPrebuiltChunk.fileName] =
  1326. this.createPrebuiltChunk(consumedPrebuiltChunk);
  1327. }
  1328. return referenceId;
  1329. }
  1330. finalizeAdditionalAsset(consumedFile, source, { bundle, fileNamesBySource, outputOptions }) {
  1331. let { fileName, needsCodeReference, referenceId } = consumedFile;
  1332. // Deduplicate assets if an explicit fileName is not provided
  1333. if (!fileName) {
  1334. const sourceHash = getSourceHash(source);
  1335. fileName = fileNamesBySource.get(sourceHash);
  1336. if (!fileName) {
  1337. fileName = generateAssetFileName(consumedFile.name, source, sourceHash, outputOptions, bundle);
  1338. fileNamesBySource.set(sourceHash, fileName);
  1339. }
  1340. }
  1341. // We must not modify the original assets to avoid interaction between outputs
  1342. const assetWithFileName = { ...consumedFile, fileName, source };
  1343. this.filesByReferenceId.set(referenceId, assetWithFileName);
  1344. const existingAsset = bundle[fileName];
  1345. if (existingAsset?.type === 'asset') {
  1346. existingAsset.needsCodeReference && (existingAsset.needsCodeReference = needsCodeReference);
  1347. }
  1348. else {
  1349. bundle[fileName] = {
  1350. fileName,
  1351. name: consumedFile.name,
  1352. needsCodeReference,
  1353. source,
  1354. type: 'asset'
  1355. };
  1356. }
  1357. }
  1358. finalizeAssetsWithSameSource(consumedFiles, sourceHash, { bundle, fileNamesBySource, outputOptions }) {
  1359. let fileName = '';
  1360. let usedConsumedFile;
  1361. let needsCodeReference = true;
  1362. for (const consumedFile of consumedFiles) {
  1363. needsCodeReference && (needsCodeReference = consumedFile.needsCodeReference);
  1364. const assetFileName = generateAssetFileName(consumedFile.name, consumedFile.source, sourceHash, outputOptions, bundle);
  1365. if (!fileName ||
  1366. assetFileName.length < fileName.length ||
  1367. (assetFileName.length === fileName.length && assetFileName < fileName)) {
  1368. fileName = assetFileName;
  1369. usedConsumedFile = consumedFile;
  1370. }
  1371. }
  1372. fileNamesBySource.set(sourceHash, fileName);
  1373. for (const consumedFile of consumedFiles) {
  1374. // We must not modify the original assets to avoid interaction between outputs
  1375. const assetWithFileName = { ...consumedFile, fileName };
  1376. this.filesByReferenceId.set(consumedFile.referenceId, assetWithFileName);
  1377. }
  1378. bundle[fileName] = {
  1379. fileName,
  1380. name: usedConsumedFile.name,
  1381. needsCodeReference,
  1382. source: usedConsumedFile.source,
  1383. type: 'asset'
  1384. };
  1385. }
  1386. }
  1387. const ANONYMOUS_PLUGIN_PREFIX = 'at position ';
  1388. const ANONYMOUS_OUTPUT_PLUGIN_PREFIX = 'at output position ';
  1389. function createPluginCache(cache) {
  1390. return {
  1391. delete(id) {
  1392. return delete cache[id];
  1393. },
  1394. get(id) {
  1395. const item = cache[id];
  1396. if (!item)
  1397. return;
  1398. item[0] = 0;
  1399. return item[1];
  1400. },
  1401. has(id) {
  1402. const item = cache[id];
  1403. if (!item)
  1404. return false;
  1405. item[0] = 0;
  1406. return true;
  1407. },
  1408. set(id, value) {
  1409. cache[id] = [0, value];
  1410. }
  1411. };
  1412. }
  1413. function getTrackedPluginCache(pluginCache, onUse) {
  1414. return {
  1415. delete(id) {
  1416. onUse();
  1417. return pluginCache.delete(id);
  1418. },
  1419. get(id) {
  1420. onUse();
  1421. return pluginCache.get(id);
  1422. },
  1423. has(id) {
  1424. onUse();
  1425. return pluginCache.has(id);
  1426. },
  1427. set(id, value) {
  1428. onUse();
  1429. return pluginCache.set(id, value);
  1430. }
  1431. };
  1432. }
  1433. const NO_CACHE = {
  1434. delete() {
  1435. return false;
  1436. },
  1437. get() {
  1438. return undefined;
  1439. },
  1440. has() {
  1441. return false;
  1442. },
  1443. set() { }
  1444. };
  1445. function uncacheablePluginError(pluginName) {
  1446. if (pluginName.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  1447. pluginName.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX)) {
  1448. return error(logAnonymousPluginCache());
  1449. }
  1450. return error(logDuplicatePluginName(pluginName));
  1451. }
  1452. function getCacheForUncacheablePlugin(pluginName) {
  1453. return {
  1454. delete() {
  1455. return uncacheablePluginError(pluginName);
  1456. },
  1457. get() {
  1458. return uncacheablePluginError(pluginName);
  1459. },
  1460. has() {
  1461. return uncacheablePluginError(pluginName);
  1462. },
  1463. set() {
  1464. return uncacheablePluginError(pluginName);
  1465. }
  1466. };
  1467. }
  1468. const BLANK = Object.freeze(Object.create(null));
  1469. const EMPTY_OBJECT = Object.freeze({});
  1470. const EMPTY_ARRAY = Object.freeze([]);
  1471. const EMPTY_SET = Object.freeze(new (class extends Set {
  1472. add() {
  1473. throw new Error('Cannot add to empty set');
  1474. }
  1475. })());
  1476. const doNothing = () => { };
  1477. async function asyncFlatten(array) {
  1478. do {
  1479. array = (await Promise.all(array)).flat(Infinity);
  1480. } while (array.some((v) => v?.then));
  1481. return array;
  1482. }
  1483. const getOnLog = (config, logLevel, printLog = defaultPrintLog) => {
  1484. const { onwarn, onLog } = config;
  1485. const defaultOnLog = getDefaultOnLog(printLog, onwarn);
  1486. if (onLog) {
  1487. const minimalPriority = logLevelPriority[logLevel];
  1488. return (level, log) => onLog(level, addLogToString(log), (level, handledLog) => {
  1489. if (level === LOGLEVEL_ERROR) {
  1490. return error(normalizeLog(handledLog));
  1491. }
  1492. if (logLevelPriority[level] >= minimalPriority) {
  1493. defaultOnLog(level, normalizeLog(handledLog));
  1494. }
  1495. });
  1496. }
  1497. return defaultOnLog;
  1498. };
  1499. const getDefaultOnLog = (printLog, onwarn) => onwarn
  1500. ? (level, log) => {
  1501. if (level === LOGLEVEL_WARN) {
  1502. onwarn(addLogToString(log), warning => printLog(LOGLEVEL_WARN, normalizeLog(warning)));
  1503. }
  1504. else {
  1505. printLog(level, log);
  1506. }
  1507. }
  1508. : printLog;
  1509. const addLogToString = (log) => {
  1510. Object.defineProperty(log, 'toString', {
  1511. value: () => getExtendedLogMessage(log),
  1512. writable: true
  1513. });
  1514. return log;
  1515. };
  1516. const normalizeLog = (log) => typeof log === 'string'
  1517. ? { message: log }
  1518. : typeof log === 'function'
  1519. ? normalizeLog(log())
  1520. : log;
  1521. const getExtendedLogMessage = (log) => {
  1522. let prefix = '';
  1523. if (log.plugin) {
  1524. prefix += `(${log.plugin} plugin) `;
  1525. }
  1526. if (log.loc) {
  1527. prefix += `${relativeId(log.loc.file)} (${log.loc.line}:${log.loc.column}) `;
  1528. }
  1529. return prefix + log.message;
  1530. };
  1531. const defaultPrintLog = (level, log) => {
  1532. const message = getExtendedLogMessage(log);
  1533. switch (level) {
  1534. case LOGLEVEL_WARN: {
  1535. return console.warn(message);
  1536. }
  1537. case LOGLEVEL_DEBUG: {
  1538. return console.debug(message);
  1539. }
  1540. default: {
  1541. return console.info(message);
  1542. }
  1543. }
  1544. };
  1545. function warnUnknownOptions(passedOptions, validOptions, optionType, log, ignoredKeys = /$./) {
  1546. const validOptionSet = new Set(validOptions);
  1547. const unknownOptions = Object.keys(passedOptions).filter(key => !(validOptionSet.has(key) || ignoredKeys.test(key)));
  1548. if (unknownOptions.length > 0) {
  1549. log(LOGLEVEL_WARN, logUnknownOption(optionType, unknownOptions, [...validOptionSet].sort()));
  1550. }
  1551. }
  1552. const treeshakePresets = {
  1553. recommended: {
  1554. annotations: true,
  1555. correctVarValueBeforeDeclaration: false,
  1556. manualPureFunctions: EMPTY_ARRAY,
  1557. moduleSideEffects: () => true,
  1558. propertyReadSideEffects: true,
  1559. tryCatchDeoptimization: true,
  1560. unknownGlobalSideEffects: false
  1561. },
  1562. safest: {
  1563. annotations: true,
  1564. correctVarValueBeforeDeclaration: true,
  1565. manualPureFunctions: EMPTY_ARRAY,
  1566. moduleSideEffects: () => true,
  1567. propertyReadSideEffects: true,
  1568. tryCatchDeoptimization: true,
  1569. unknownGlobalSideEffects: true
  1570. },
  1571. smallest: {
  1572. annotations: true,
  1573. correctVarValueBeforeDeclaration: false,
  1574. manualPureFunctions: EMPTY_ARRAY,
  1575. moduleSideEffects: () => false,
  1576. propertyReadSideEffects: false,
  1577. tryCatchDeoptimization: false,
  1578. unknownGlobalSideEffects: false
  1579. }
  1580. };
  1581. const generatedCodePresets = {
  1582. es2015: {
  1583. arrowFunctions: true,
  1584. constBindings: true,
  1585. objectShorthand: true,
  1586. reservedNamesAsProps: true,
  1587. symbols: true
  1588. },
  1589. es5: {
  1590. arrowFunctions: false,
  1591. constBindings: false,
  1592. objectShorthand: false,
  1593. reservedNamesAsProps: true,
  1594. symbols: false
  1595. }
  1596. };
  1597. const objectifyOption = (value) => value && typeof value === 'object' ? value : {};
  1598. const objectifyOptionWithPresets = (presets, optionName, urlSnippet, additionalValues) => (value) => {
  1599. if (typeof value === 'string') {
  1600. const preset = presets[value];
  1601. if (preset) {
  1602. return preset;
  1603. }
  1604. error(logInvalidOption(optionName, urlSnippet, `valid values are ${additionalValues}${printQuotedStringList(Object.keys(presets))}. You can also supply an object for more fine-grained control`, value));
  1605. }
  1606. return objectifyOption(value);
  1607. };
  1608. const getOptionWithPreset = (value, presets, optionName, urlSnippet, additionalValues) => {
  1609. const presetName = value?.preset;
  1610. if (presetName) {
  1611. const preset = presets[presetName];
  1612. if (preset) {
  1613. return { ...preset, ...value };
  1614. }
  1615. else {
  1616. error(logInvalidOption(`${optionName}.preset`, urlSnippet, `valid values are ${printQuotedStringList(Object.keys(presets))}`, presetName));
  1617. }
  1618. }
  1619. return objectifyOptionWithPresets(presets, optionName, urlSnippet, additionalValues)(value);
  1620. };
  1621. const normalizePluginOption = async (plugins) => (await asyncFlatten([plugins])).filter(Boolean);
  1622. function getLogHandler(level, code, logger, pluginName, logLevel) {
  1623. if (logLevelPriority[level] < logLevelPriority[logLevel]) {
  1624. return doNothing;
  1625. }
  1626. return (log, pos) => {
  1627. if (pos != null) {
  1628. logger(LOGLEVEL_WARN, logInvalidLogPosition(pluginName));
  1629. }
  1630. log = normalizeLog(log);
  1631. if (log.code && !log.pluginCode) {
  1632. log.pluginCode = log.code;
  1633. }
  1634. log.code = code;
  1635. log.plugin = pluginName;
  1636. logger(level, log);
  1637. };
  1638. }
  1639. function getPluginContext(plugin, pluginCache, graph, options, fileEmitter, existingPluginNames) {
  1640. const { logLevel, onLog } = options;
  1641. let cacheable = true;
  1642. if (typeof plugin.cacheKey !== 'string') {
  1643. if (plugin.name.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  1644. plugin.name.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX) ||
  1645. existingPluginNames.has(plugin.name)) {
  1646. cacheable = false;
  1647. }
  1648. else {
  1649. existingPluginNames.add(plugin.name);
  1650. }
  1651. }
  1652. let cacheInstance;
  1653. if (!pluginCache) {
  1654. cacheInstance = NO_CACHE;
  1655. }
  1656. else if (cacheable) {
  1657. const cacheKey = plugin.cacheKey || plugin.name;
  1658. cacheInstance = createPluginCache(pluginCache[cacheKey] || (pluginCache[cacheKey] = Object.create(null)));
  1659. }
  1660. else {
  1661. cacheInstance = getCacheForUncacheablePlugin(plugin.name);
  1662. }
  1663. return {
  1664. addWatchFile(id) {
  1665. if (graph.phase >= BuildPhase.GENERATE) {
  1666. return this.error(logInvalidRollupPhaseForAddWatchFile());
  1667. }
  1668. graph.watchFiles[id] = true;
  1669. },
  1670. cache: cacheInstance,
  1671. debug: getLogHandler(LOGLEVEL_DEBUG, 'PLUGIN_LOG', onLog, plugin.name, logLevel),
  1672. emitFile: fileEmitter.emitFile.bind(fileEmitter),
  1673. error(error_) {
  1674. return error(logPluginError(normalizeLog(error_), plugin.name));
  1675. },
  1676. getFileName: fileEmitter.getFileName,
  1677. getModuleIds: () => graph.modulesById.keys(),
  1678. getModuleInfo: graph.getModuleInfo,
  1679. getWatchFiles: () => Object.keys(graph.watchFiles),
  1680. info: getLogHandler(LOGLEVEL_INFO, 'PLUGIN_LOG', onLog, plugin.name, logLevel),
  1681. load(resolvedId) {
  1682. return graph.moduleLoader.preloadModule(resolvedId);
  1683. },
  1684. meta: {
  1685. rollupVersion: version$1,
  1686. watchMode: graph.watchMode
  1687. },
  1688. get moduleIds() {
  1689. function* wrappedModuleIds() {
  1690. // We are wrapping this in a generator to only show the message once we are actually iterating
  1691. warnDeprecation(`Accessing "this.moduleIds" on the plugin context by plugin ${plugin.name} is deprecated. The "this.getModuleIds" plugin context function should be used instead.`, URL_THIS_GETMODULEIDS, true, options, plugin.name);
  1692. yield* moduleIds;
  1693. }
  1694. const moduleIds = graph.modulesById.keys();
  1695. return wrappedModuleIds();
  1696. },
  1697. parse: graph.contextParse.bind(graph),
  1698. resolve(source, importer, { assertions, custom, isEntry, skipSelf } = BLANK) {
  1699. return graph.moduleLoader.resolveId(source, importer, custom, isEntry, assertions || EMPTY_OBJECT, skipSelf ? [{ importer, plugin, source }] : null);
  1700. },
  1701. setAssetSource: fileEmitter.setAssetSource,
  1702. warn: getLogHandler(LOGLEVEL_WARN, 'PLUGIN_WARNING', onLog, plugin.name, logLevel)
  1703. };
  1704. }
  1705. // This will make sure no input hook is omitted
  1706. const inputHookNames = {
  1707. buildEnd: 1,
  1708. buildStart: 1,
  1709. closeBundle: 1,
  1710. closeWatcher: 1,
  1711. load: 1,
  1712. moduleParsed: 1,
  1713. onLog: 1,
  1714. options: 1,
  1715. resolveDynamicImport: 1,
  1716. resolveId: 1,
  1717. shouldTransformCachedModule: 1,
  1718. transform: 1,
  1719. watchChange: 1
  1720. };
  1721. const inputHooks = Object.keys(inputHookNames);
  1722. class PluginDriver {
  1723. constructor(graph, options, userPlugins, pluginCache, basePluginDriver) {
  1724. this.graph = graph;
  1725. this.options = options;
  1726. this.pluginCache = pluginCache;
  1727. this.sortedPlugins = new Map();
  1728. this.unfulfilledActions = new Set();
  1729. this.fileEmitter = new FileEmitter(graph, options, basePluginDriver && basePluginDriver.fileEmitter);
  1730. this.emitFile = this.fileEmitter.emitFile.bind(this.fileEmitter);
  1731. this.getFileName = this.fileEmitter.getFileName.bind(this.fileEmitter);
  1732. this.finaliseAssets = this.fileEmitter.finaliseAssets.bind(this.fileEmitter);
  1733. this.setChunkInformation = this.fileEmitter.setChunkInformation.bind(this.fileEmitter);
  1734. this.setOutputBundle = this.fileEmitter.setOutputBundle.bind(this.fileEmitter);
  1735. this.plugins = [...(basePluginDriver ? basePluginDriver.plugins : []), ...userPlugins];
  1736. const existingPluginNames = new Set();
  1737. this.pluginContexts = new Map(this.plugins.map(plugin => [
  1738. plugin,
  1739. getPluginContext(plugin, pluginCache, graph, options, this.fileEmitter, existingPluginNames)
  1740. ]));
  1741. if (basePluginDriver) {
  1742. for (const plugin of userPlugins) {
  1743. for (const hook of inputHooks) {
  1744. if (hook in plugin) {
  1745. options.onLog(LOGLEVEL_WARN, logInputHookInOutputPlugin(plugin.name, hook));
  1746. }
  1747. }
  1748. }
  1749. }
  1750. }
  1751. createOutputPluginDriver(plugins) {
  1752. return new PluginDriver(this.graph, this.options, plugins, this.pluginCache, this);
  1753. }
  1754. getUnfulfilledHookActions() {
  1755. return this.unfulfilledActions;
  1756. }
  1757. // chains, first non-null result stops and returns
  1758. hookFirst(hookName, parameters, replaceContext, skipped) {
  1759. return this.hookFirstAndGetPlugin(hookName, parameters, replaceContext, skipped).then(result => result && result[0]);
  1760. }
  1761. // chains, first non-null result stops and returns result and last plugin
  1762. async hookFirstAndGetPlugin(hookName, parameters, replaceContext, skipped) {
  1763. for (const plugin of this.getSortedPlugins(hookName)) {
  1764. if (skipped?.has(plugin))
  1765. continue;
  1766. const result = await this.runHook(hookName, parameters, plugin, replaceContext);
  1767. if (result != null)
  1768. return [result, plugin];
  1769. }
  1770. return null;
  1771. }
  1772. // chains synchronously, first non-null result stops and returns
  1773. hookFirstSync(hookName, parameters, replaceContext) {
  1774. for (const plugin of this.getSortedPlugins(hookName)) {
  1775. const result = this.runHookSync(hookName, parameters, plugin, replaceContext);
  1776. if (result != null)
  1777. return result;
  1778. }
  1779. return null;
  1780. }
  1781. // parallel, ignores returns
  1782. async hookParallel(hookName, parameters, replaceContext) {
  1783. const parallelPromises = [];
  1784. for (const plugin of this.getSortedPlugins(hookName)) {
  1785. if (plugin[hookName].sequential) {
  1786. await Promise.all(parallelPromises);
  1787. parallelPromises.length = 0;
  1788. await this.runHook(hookName, parameters, plugin, replaceContext);
  1789. }
  1790. else {
  1791. parallelPromises.push(this.runHook(hookName, parameters, plugin, replaceContext));
  1792. }
  1793. }
  1794. await Promise.all(parallelPromises);
  1795. }
  1796. // chains, reduces returned value, handling the reduced value as the first hook argument
  1797. hookReduceArg0(hookName, [argument0, ...rest], reduce, replaceContext) {
  1798. let promise = Promise.resolve(argument0);
  1799. for (const plugin of this.getSortedPlugins(hookName)) {
  1800. promise = promise.then(argument0 => this.runHook(hookName, [argument0, ...rest], plugin, replaceContext).then(result => reduce.call(this.pluginContexts.get(plugin), argument0, result, plugin)));
  1801. }
  1802. return promise;
  1803. }
  1804. // chains synchronously, reduces returned value, handling the reduced value as the first hook argument
  1805. hookReduceArg0Sync(hookName, [argument0, ...rest], reduce, replaceContext) {
  1806. for (const plugin of this.getSortedPlugins(hookName)) {
  1807. const parameters = [argument0, ...rest];
  1808. const result = this.runHookSync(hookName, parameters, plugin, replaceContext);
  1809. argument0 = reduce.call(this.pluginContexts.get(plugin), argument0, result, plugin);
  1810. }
  1811. return argument0;
  1812. }
  1813. // chains, reduces returned value to type string, handling the reduced value separately. permits hooks as values.
  1814. async hookReduceValue(hookName, initialValue, parameters, reducer) {
  1815. const results = [];
  1816. const parallelResults = [];
  1817. for (const plugin of this.getSortedPlugins(hookName, validateAddonPluginHandler)) {
  1818. if (plugin[hookName].sequential) {
  1819. results.push(...(await Promise.all(parallelResults)));
  1820. parallelResults.length = 0;
  1821. results.push(await this.runHook(hookName, parameters, plugin));
  1822. }
  1823. else {
  1824. parallelResults.push(this.runHook(hookName, parameters, plugin));
  1825. }
  1826. }
  1827. results.push(...(await Promise.all(parallelResults)));
  1828. return results.reduce(reducer, await initialValue);
  1829. }
  1830. // chains synchronously, reduces returned value to type T, handling the reduced value separately. permits hooks as values.
  1831. hookReduceValueSync(hookName, initialValue, parameters, reduce, replaceContext) {
  1832. let accumulator = initialValue;
  1833. for (const plugin of this.getSortedPlugins(hookName)) {
  1834. const result = this.runHookSync(hookName, parameters, plugin, replaceContext);
  1835. accumulator = reduce.call(this.pluginContexts.get(plugin), accumulator, result, plugin);
  1836. }
  1837. return accumulator;
  1838. }
  1839. // chains, ignores returns
  1840. hookSeq(hookName, parameters, replaceContext) {
  1841. let promise = Promise.resolve();
  1842. for (const plugin of this.getSortedPlugins(hookName)) {
  1843. promise = promise.then(() => this.runHook(hookName, parameters, plugin, replaceContext));
  1844. }
  1845. return promise.then(noReturn);
  1846. }
  1847. getSortedPlugins(hookName, validateHandler) {
  1848. return getOrCreate(this.sortedPlugins, hookName, () => getSortedValidatedPlugins(hookName, this.plugins, validateHandler));
  1849. }
  1850. // Implementation signature
  1851. runHook(hookName, parameters, plugin, replaceContext) {
  1852. // We always filter for plugins that support the hook before running it
  1853. const hook = plugin[hookName];
  1854. const handler = typeof hook === 'object' ? hook.handler : hook;
  1855. let context = this.pluginContexts.get(plugin);
  1856. if (replaceContext) {
  1857. context = replaceContext(context, plugin);
  1858. }
  1859. let action = null;
  1860. return Promise.resolve()
  1861. .then(() => {
  1862. if (typeof handler !== 'function') {
  1863. return handler;
  1864. }
  1865. // eslint-disable-next-line @typescript-eslint/ban-types
  1866. const hookResult = handler.apply(context, parameters);
  1867. if (!hookResult?.then) {
  1868. // short circuit for non-thenables and non-Promises
  1869. return hookResult;
  1870. }
  1871. // Track pending hook actions to properly error out when
  1872. // unfulfilled promises cause rollup to abruptly and confusingly
  1873. // exit with a successful 0 return code but without producing any
  1874. // output, errors or warnings.
  1875. action = [plugin.name, hookName, parameters];
  1876. this.unfulfilledActions.add(action);
  1877. // Although it would be more elegant to just return hookResult here
  1878. // and put the .then() handler just above the .catch() handler below,
  1879. // doing so would subtly change the defacto async event dispatch order
  1880. // which at least one test and some plugins in the wild may depend on.
  1881. return Promise.resolve(hookResult).then(result => {
  1882. // action was fulfilled
  1883. this.unfulfilledActions.delete(action);
  1884. return result;
  1885. });
  1886. })
  1887. .catch(error_ => {
  1888. if (action !== null) {
  1889. // action considered to be fulfilled since error being handled
  1890. this.unfulfilledActions.delete(action);
  1891. }
  1892. return error(logPluginError(error_, plugin.name, { hook: hookName }));
  1893. });
  1894. }
  1895. /**
  1896. * Run a sync plugin hook and return the result.
  1897. * @param hookName Name of the plugin hook. Must be in `PluginHooks`.
  1898. * @param args Arguments passed to the plugin hook.
  1899. * @param plugin The acutal plugin
  1900. * @param replaceContext When passed, the plugin context can be overridden.
  1901. */
  1902. runHookSync(hookName, parameters, plugin, replaceContext) {
  1903. const hook = plugin[hookName];
  1904. const handler = typeof hook === 'object' ? hook.handler : hook;
  1905. let context = this.pluginContexts.get(plugin);
  1906. if (replaceContext) {
  1907. context = replaceContext(context, plugin);
  1908. }
  1909. try {
  1910. // eslint-disable-next-line @typescript-eslint/ban-types
  1911. return handler.apply(context, parameters);
  1912. }
  1913. catch (error_) {
  1914. return error(logPluginError(error_, plugin.name, { hook: hookName }));
  1915. }
  1916. }
  1917. }
  1918. function getSortedValidatedPlugins(hookName, plugins, validateHandler = validateFunctionPluginHandler) {
  1919. const pre = [];
  1920. const normal = [];
  1921. const post = [];
  1922. for (const plugin of plugins) {
  1923. const hook = plugin[hookName];
  1924. if (hook) {
  1925. if (typeof hook === 'object') {
  1926. validateHandler(hook.handler, hookName, plugin);
  1927. if (hook.order === 'pre') {
  1928. pre.push(plugin);
  1929. continue;
  1930. }
  1931. if (hook.order === 'post') {
  1932. post.push(plugin);
  1933. continue;
  1934. }
  1935. }
  1936. else {
  1937. validateHandler(hook, hookName, plugin);
  1938. }
  1939. normal.push(plugin);
  1940. }
  1941. }
  1942. return [...pre, ...normal, ...post];
  1943. }
  1944. function validateFunctionPluginHandler(handler, hookName, plugin) {
  1945. if (typeof handler !== 'function') {
  1946. error(logInvalidFunctionPluginHook(hookName, plugin.name));
  1947. }
  1948. }
  1949. function validateAddonPluginHandler(handler, hookName, plugin) {
  1950. if (typeof handler !== 'string' && typeof handler !== 'function') {
  1951. return error(logInvalidAddonPluginHook(hookName, plugin.name));
  1952. }
  1953. }
  1954. function noReturn() { }
  1955. function getLogger(plugins, onLog, watchMode, logLevel) {
  1956. plugins = getSortedValidatedPlugins('onLog', plugins);
  1957. const minimalPriority = logLevelPriority[logLevel];
  1958. const logger = (level, log, skipped = EMPTY_SET) => {
  1959. const logPriority = logLevelPriority[level];
  1960. if (logPriority < minimalPriority) {
  1961. return;
  1962. }
  1963. for (const plugin of plugins) {
  1964. if (skipped.has(plugin))
  1965. continue;
  1966. const { onLog: pluginOnLog } = plugin;
  1967. const getLogHandler = (level) => {
  1968. if (logLevelPriority[level] < minimalPriority) {
  1969. return doNothing;
  1970. }
  1971. return log => logger(level, normalizeLog(log), new Set(skipped).add(plugin));
  1972. };
  1973. const handler = 'handler' in pluginOnLog ? pluginOnLog.handler : pluginOnLog;
  1974. if (handler.call({
  1975. debug: getLogHandler(LOGLEVEL_DEBUG),
  1976. error: (log) => error(normalizeLog(log)),
  1977. info: getLogHandler(LOGLEVEL_INFO),
  1978. meta: { rollupVersion: version$1, watchMode },
  1979. warn: getLogHandler(LOGLEVEL_WARN)
  1980. }, level, log) === false) {
  1981. return;
  1982. }
  1983. }
  1984. onLog(level, log);
  1985. };
  1986. return logger;
  1987. }
  1988. const commandAliases = {
  1989. c: 'config',
  1990. d: 'dir',
  1991. e: 'external',
  1992. f: 'format',
  1993. g: 'globals',
  1994. h: 'help',
  1995. i: 'input',
  1996. m: 'sourcemap',
  1997. n: 'name',
  1998. o: 'file',
  1999. p: 'plugin',
  2000. v: 'version',
  2001. w: 'watch'
  2002. };
  2003. const EMPTY_COMMAND_OPTIONS = { external: [], globals: undefined };
  2004. async function mergeOptions(config, watchMode, rawCommandOptions = EMPTY_COMMAND_OPTIONS, printLog) {
  2005. const command = getCommandOptions(rawCommandOptions);
  2006. const plugins = await normalizePluginOption(config.plugins);
  2007. const logLevel = config.logLevel || LOGLEVEL_INFO;
  2008. const onLog = getOnLog(config, logLevel, printLog);
  2009. const log = getLogger(plugins, onLog, watchMode, logLevel);
  2010. const inputOptions = await mergeInputOptions(config, command, plugins, log, onLog);
  2011. if (command.output) {
  2012. Object.assign(command, command.output);
  2013. }
  2014. const outputOptionsArray = ensureArray$1(config.output);
  2015. if (outputOptionsArray.length === 0)
  2016. outputOptionsArray.push({});
  2017. const outputOptions = await Promise.all(outputOptionsArray.map(singleOutputOptions => mergeOutputOptions(singleOutputOptions, command, log)));
  2018. warnUnknownOptions(command, [
  2019. ...Object.keys(inputOptions),
  2020. ...Object.keys(outputOptions[0]).filter(option => option !== 'sourcemapIgnoreList' && option !== 'sourcemapPathTransform'),
  2021. ...Object.keys(commandAliases),
  2022. 'bundleConfigAsCjs',
  2023. 'config',
  2024. 'environment',
  2025. 'filterLogs',
  2026. 'plugin',
  2027. 'silent',
  2028. 'failAfterWarnings',
  2029. 'stdin',
  2030. 'waitForBundleInput',
  2031. 'configPlugin'
  2032. ], 'CLI flags', log, /^_$|output$|config/);
  2033. inputOptions.output = outputOptions;
  2034. return inputOptions;
  2035. }
  2036. function getCommandOptions(rawCommandOptions) {
  2037. const external = rawCommandOptions.external && typeof rawCommandOptions.external === 'string'
  2038. ? rawCommandOptions.external.split(',')
  2039. : [];
  2040. return {
  2041. ...rawCommandOptions,
  2042. external,
  2043. globals: typeof rawCommandOptions.globals === 'string'
  2044. ? rawCommandOptions.globals.split(',').reduce((globals, globalDefinition) => {
  2045. const [id, variableName] = globalDefinition.split(':');
  2046. globals[id] = variableName;
  2047. if (!external.includes(id)) {
  2048. external.push(id);
  2049. }
  2050. return globals;
  2051. }, Object.create(null))
  2052. : undefined
  2053. };
  2054. }
  2055. function mergeInputOptions(config, overrides, plugins, log, onLog) {
  2056. const getOption = (name) => overrides[name] ?? config[name];
  2057. const inputOptions = {
  2058. acorn: getOption('acorn'),
  2059. acornInjectPlugins: config.acornInjectPlugins,
  2060. cache: config.cache,
  2061. context: getOption('context'),
  2062. experimentalCacheExpiry: getOption('experimentalCacheExpiry'),
  2063. experimentalLogSideEffects: getOption('experimentalLogSideEffects'),
  2064. external: getExternal(config, overrides),
  2065. inlineDynamicImports: getOption('inlineDynamicImports'),
  2066. input: getOption('input') || [],
  2067. logLevel: getOption('logLevel'),
  2068. makeAbsoluteExternalsRelative: getOption('makeAbsoluteExternalsRelative'),
  2069. manualChunks: getOption('manualChunks'),
  2070. maxParallelFileOps: getOption('maxParallelFileOps'),
  2071. maxParallelFileReads: getOption('maxParallelFileReads'),
  2072. moduleContext: getOption('moduleContext'),
  2073. onLog,
  2074. onwarn: undefined,
  2075. perf: getOption('perf'),
  2076. plugins,
  2077. preserveEntrySignatures: getOption('preserveEntrySignatures'),
  2078. preserveModules: getOption('preserveModules'),
  2079. preserveSymlinks: getOption('preserveSymlinks'),
  2080. shimMissingExports: getOption('shimMissingExports'),
  2081. strictDeprecations: getOption('strictDeprecations'),
  2082. treeshake: getObjectOption(config, overrides, 'treeshake', objectifyOptionWithPresets(treeshakePresets, 'treeshake', URL_TREESHAKE, 'false, true, ')),
  2083. watch: getWatch(config, overrides)
  2084. };
  2085. warnUnknownOptions(config, Object.keys(inputOptions), 'input options', log, /^output$/);
  2086. return inputOptions;
  2087. }
  2088. const getExternal = (config, overrides) => {
  2089. const configExternal = config.external;
  2090. return typeof configExternal === 'function'
  2091. ? (source, importer, isResolved) => configExternal(source, importer, isResolved) || overrides.external.includes(source)
  2092. : [...ensureArray$1(configExternal), ...overrides.external];
  2093. };
  2094. const getObjectOption = (config, overrides, name, objectifyValue = objectifyOption) => {
  2095. const commandOption = normalizeObjectOptionValue(overrides[name], objectifyValue);
  2096. const configOption = normalizeObjectOptionValue(config[name], objectifyValue);
  2097. if (commandOption !== undefined) {
  2098. return commandOption && { ...configOption, ...commandOption };
  2099. }
  2100. return configOption;
  2101. };
  2102. const getWatch = (config, overrides) => config.watch !== false && getObjectOption(config, overrides, 'watch');
  2103. const isWatchEnabled = (optionValue) => {
  2104. if (Array.isArray(optionValue)) {
  2105. return optionValue.reduce((result, value) => (typeof value === 'boolean' ? value : result), false);
  2106. }
  2107. return optionValue === true;
  2108. };
  2109. const normalizeObjectOptionValue = (optionValue, objectifyValue) => {
  2110. if (!optionValue) {
  2111. return optionValue;
  2112. }
  2113. if (Array.isArray(optionValue)) {
  2114. return optionValue.reduce((result, value) => value && result && { ...result, ...objectifyValue(value) }, {});
  2115. }
  2116. return objectifyValue(optionValue);
  2117. };
  2118. async function mergeOutputOptions(config, overrides, log) {
  2119. const getOption = (name) => overrides[name] ?? config[name];
  2120. const outputOptions = {
  2121. amd: getObjectOption(config, overrides, 'amd'),
  2122. assetFileNames: getOption('assetFileNames'),
  2123. banner: getOption('banner'),
  2124. chunkFileNames: getOption('chunkFileNames'),
  2125. compact: getOption('compact'),
  2126. dir: getOption('dir'),
  2127. dynamicImportFunction: getOption('dynamicImportFunction'),
  2128. dynamicImportInCjs: getOption('dynamicImportInCjs'),
  2129. entryFileNames: getOption('entryFileNames'),
  2130. esModule: getOption('esModule'),
  2131. experimentalDeepDynamicChunkOptimization: getOption('experimentalDeepDynamicChunkOptimization'),
  2132. experimentalMinChunkSize: getOption('experimentalMinChunkSize'),
  2133. exports: getOption('exports'),
  2134. extend: getOption('extend'),
  2135. externalImportAssertions: getOption('externalImportAssertions'),
  2136. externalLiveBindings: getOption('externalLiveBindings'),
  2137. file: getOption('file'),
  2138. footer: getOption('footer'),
  2139. format: getOption('format'),
  2140. freeze: getOption('freeze'),
  2141. generatedCode: getObjectOption(config, overrides, 'generatedCode', objectifyOptionWithPresets(generatedCodePresets, 'output.generatedCode', URL_OUTPUT_GENERATEDCODE, '')),
  2142. globals: getOption('globals'),
  2143. hoistTransitiveImports: getOption('hoistTransitiveImports'),
  2144. indent: getOption('indent'),
  2145. inlineDynamicImports: getOption('inlineDynamicImports'),
  2146. interop: getOption('interop'),
  2147. intro: getOption('intro'),
  2148. manualChunks: getOption('manualChunks'),
  2149. minifyInternalExports: getOption('minifyInternalExports'),
  2150. name: getOption('name'),
  2151. namespaceToStringTag: getOption('namespaceToStringTag'),
  2152. noConflict: getOption('noConflict'),
  2153. outro: getOption('outro'),
  2154. paths: getOption('paths'),
  2155. plugins: await normalizePluginOption(config.plugins),
  2156. preferConst: getOption('preferConst'),
  2157. preserveModules: getOption('preserveModules'),
  2158. preserveModulesRoot: getOption('preserveModulesRoot'),
  2159. sanitizeFileName: getOption('sanitizeFileName'),
  2160. sourcemap: getOption('sourcemap'),
  2161. sourcemapBaseUrl: getOption('sourcemapBaseUrl'),
  2162. sourcemapExcludeSources: getOption('sourcemapExcludeSources'),
  2163. sourcemapFile: getOption('sourcemapFile'),
  2164. sourcemapFileNames: getOption('sourcemapFileNames'),
  2165. sourcemapIgnoreList: getOption('sourcemapIgnoreList'),
  2166. sourcemapPathTransform: getOption('sourcemapPathTransform'),
  2167. strict: getOption('strict'),
  2168. systemNullSetters: getOption('systemNullSetters'),
  2169. validate: getOption('validate')
  2170. };
  2171. warnUnknownOptions(config, Object.keys(outputOptions), 'output options', log);
  2172. return outputOptions;
  2173. }
  2174. const {
  2175. env = {},
  2176. argv = [],
  2177. platform = "",
  2178. } = typeof process === "undefined" ? {} : process;
  2179. const isDisabled = "NO_COLOR" in env || argv.includes("--no-color");
  2180. const isForced = "FORCE_COLOR" in env || argv.includes("--color");
  2181. const isWindows = platform === "win32";
  2182. const isDumbTerminal = env.TERM === "dumb";
  2183. const isCompatibleTerminal =
  2184. tty__namespace && tty__namespace.isatty && tty__namespace.isatty(1) && env.TERM && !isDumbTerminal;
  2185. const isCI =
  2186. "CI" in env &&
  2187. ("GITHUB_ACTIONS" in env || "GITLAB_CI" in env || "CIRCLECI" in env);
  2188. const isColorSupported =
  2189. !isDisabled &&
  2190. (isForced || (isWindows && !isDumbTerminal) || isCompatibleTerminal || isCI);
  2191. const replaceClose = (
  2192. index,
  2193. string,
  2194. close,
  2195. replace,
  2196. head = string.substring(0, index) + replace,
  2197. tail = string.substring(index + close.length),
  2198. next = tail.indexOf(close)
  2199. ) => head + (next < 0 ? tail : replaceClose(next, tail, close, replace));
  2200. const clearBleed = (index, string, open, close, replace) =>
  2201. index < 0
  2202. ? open + string + close
  2203. : open + replaceClose(index, string, close, replace) + close;
  2204. const filterEmpty =
  2205. (open, close, replace = open, at = open.length + 1) =>
  2206. (string) =>
  2207. string || !(string === "" || string === undefined)
  2208. ? clearBleed(
  2209. ("" + string).indexOf(close, at),
  2210. string,
  2211. open,
  2212. close,
  2213. replace
  2214. )
  2215. : "";
  2216. const init = (open, close, replace) =>
  2217. filterEmpty(`\x1b[${open}m`, `\x1b[${close}m`, replace);
  2218. const colors = {
  2219. reset: init(0, 0),
  2220. bold: init(1, 22, "\x1b[22m\x1b[1m"),
  2221. dim: init(2, 22, "\x1b[22m\x1b[2m"),
  2222. italic: init(3, 23),
  2223. underline: init(4, 24),
  2224. inverse: init(7, 27),
  2225. hidden: init(8, 28),
  2226. strikethrough: init(9, 29),
  2227. black: init(30, 39),
  2228. red: init(31, 39),
  2229. green: init(32, 39),
  2230. yellow: init(33, 39),
  2231. blue: init(34, 39),
  2232. magenta: init(35, 39),
  2233. cyan: init(36, 39),
  2234. white: init(37, 39),
  2235. gray: init(90, 39),
  2236. bgBlack: init(40, 49),
  2237. bgRed: init(41, 49),
  2238. bgGreen: init(42, 49),
  2239. bgYellow: init(43, 49),
  2240. bgBlue: init(44, 49),
  2241. bgMagenta: init(45, 49),
  2242. bgCyan: init(46, 49),
  2243. bgWhite: init(47, 49),
  2244. blackBright: init(90, 39),
  2245. redBright: init(91, 39),
  2246. greenBright: init(92, 39),
  2247. yellowBright: init(93, 39),
  2248. blueBright: init(94, 39),
  2249. magentaBright: init(95, 39),
  2250. cyanBright: init(96, 39),
  2251. whiteBright: init(97, 39),
  2252. bgBlackBright: init(100, 49),
  2253. bgRedBright: init(101, 49),
  2254. bgGreenBright: init(102, 49),
  2255. bgYellowBright: init(103, 49),
  2256. bgBlueBright: init(104, 49),
  2257. bgMagentaBright: init(105, 49),
  2258. bgCyanBright: init(106, 49),
  2259. bgWhiteBright: init(107, 49),
  2260. };
  2261. const createColors = ({ useColor = isColorSupported } = {}) =>
  2262. useColor
  2263. ? colors
  2264. : Object.keys(colors).reduce(
  2265. (colors, key) => ({ ...colors, [key]: String }),
  2266. {}
  2267. );
  2268. const {
  2269. reset,
  2270. bold: bold$1,
  2271. dim: dim$1,
  2272. italic,
  2273. underline: underline$1,
  2274. inverse,
  2275. hidden,
  2276. strikethrough,
  2277. black,
  2278. red: red$1,
  2279. green: green$1,
  2280. yellow: yellow$1,
  2281. blue,
  2282. magenta,
  2283. cyan: cyan$1,
  2284. white,
  2285. gray: gray$1,
  2286. bgBlack,
  2287. bgRed,
  2288. bgGreen,
  2289. bgYellow,
  2290. bgBlue,
  2291. bgMagenta,
  2292. bgCyan,
  2293. bgWhite,
  2294. blackBright,
  2295. redBright,
  2296. greenBright,
  2297. yellowBright,
  2298. blueBright,
  2299. magentaBright,
  2300. cyanBright,
  2301. whiteBright,
  2302. bgBlackBright,
  2303. bgRedBright,
  2304. bgGreenBright,
  2305. bgYellowBright,
  2306. bgBlueBright,
  2307. bgMagentaBright,
  2308. bgCyanBright,
  2309. bgWhiteBright,
  2310. } = createColors();
  2311. // @see https://no-color.org
  2312. // @see https://www.npmjs.com/package/chalk
  2313. const { bold, cyan, dim, gray, green, red, underline, yellow } = createColors({
  2314. useColor: process$1.env.FORCE_COLOR !== '0' && !process$1.env.NO_COLOR
  2315. });
  2316. // log to stderr to keep `rollup main.js > bundle.js` from breaking
  2317. const stderr = (...parameters) => process$1.stderr.write(`${parameters.join('')}\n`);
  2318. function handleError(error, recover = false) {
  2319. const name = error.name || error.cause?.name;
  2320. const nameSection = name ? `${name}: ` : '';
  2321. const pluginSection = error.plugin ? `(plugin ${error.plugin}) ` : '';
  2322. const message = `${pluginSection}${nameSection}${error.message}`;
  2323. const outputLines = [bold(red(`[!] ${bold(message.toString())}`))];
  2324. if (error.url) {
  2325. outputLines.push(cyan(error.url));
  2326. }
  2327. if (error.loc) {
  2328. outputLines.push(`${relativeId((error.loc.file || error.id))} (${error.loc.line}:${error.loc.column})`);
  2329. }
  2330. else if (error.id) {
  2331. outputLines.push(relativeId(error.id));
  2332. }
  2333. if (error.frame) {
  2334. outputLines.push(dim(error.frame));
  2335. }
  2336. if (error.stack) {
  2337. outputLines.push(dim(error.stack?.replace(`${nameSection}${error.message}\n`, '')));
  2338. }
  2339. outputLines.push('', '');
  2340. stderr(outputLines.join('\n'));
  2341. if (!recover)
  2342. process$1.exit(1);
  2343. }
  2344. const comma = ','.charCodeAt(0);
  2345. const semicolon = ';'.charCodeAt(0);
  2346. const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  2347. const intToChar = new Uint8Array(64); // 64 possible chars.
  2348. const charToInt = new Uint8Array(128); // z is 122 in ASCII
  2349. for (let i = 0; i < chars.length; i++) {
  2350. const c = chars.charCodeAt(i);
  2351. intToChar[i] = c;
  2352. charToInt[c] = i;
  2353. }
  2354. // Provide a fallback for older environments.
  2355. const td = typeof TextDecoder !== 'undefined'
  2356. ? /* #__PURE__ */ new TextDecoder()
  2357. : typeof Buffer !== 'undefined'
  2358. ? {
  2359. decode(buf) {
  2360. const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
  2361. return out.toString();
  2362. },
  2363. }
  2364. : {
  2365. decode(buf) {
  2366. let out = '';
  2367. for (let i = 0; i < buf.length; i++) {
  2368. out += String.fromCharCode(buf[i]);
  2369. }
  2370. return out;
  2371. },
  2372. };
  2373. function decode(mappings) {
  2374. const state = new Int32Array(5);
  2375. const decoded = [];
  2376. let index = 0;
  2377. do {
  2378. const semi = indexOf(mappings, index);
  2379. const line = [];
  2380. let sorted = true;
  2381. let lastCol = 0;
  2382. state[0] = 0;
  2383. for (let i = index; i < semi; i++) {
  2384. let seg;
  2385. i = decodeInteger(mappings, i, state, 0); // genColumn
  2386. const col = state[0];
  2387. if (col < lastCol)
  2388. sorted = false;
  2389. lastCol = col;
  2390. if (hasMoreVlq(mappings, i, semi)) {
  2391. i = decodeInteger(mappings, i, state, 1); // sourcesIndex
  2392. i = decodeInteger(mappings, i, state, 2); // sourceLine
  2393. i = decodeInteger(mappings, i, state, 3); // sourceColumn
  2394. if (hasMoreVlq(mappings, i, semi)) {
  2395. i = decodeInteger(mappings, i, state, 4); // namesIndex
  2396. seg = [col, state[1], state[2], state[3], state[4]];
  2397. }
  2398. else {
  2399. seg = [col, state[1], state[2], state[3]];
  2400. }
  2401. }
  2402. else {
  2403. seg = [col];
  2404. }
  2405. line.push(seg);
  2406. }
  2407. if (!sorted)
  2408. sort(line);
  2409. decoded.push(line);
  2410. index = semi + 1;
  2411. } while (index <= mappings.length);
  2412. return decoded;
  2413. }
  2414. function indexOf(mappings, index) {
  2415. const idx = mappings.indexOf(';', index);
  2416. return idx === -1 ? mappings.length : idx;
  2417. }
  2418. function decodeInteger(mappings, pos, state, j) {
  2419. let value = 0;
  2420. let shift = 0;
  2421. let integer = 0;
  2422. do {
  2423. const c = mappings.charCodeAt(pos++);
  2424. integer = charToInt[c];
  2425. value |= (integer & 31) << shift;
  2426. shift += 5;
  2427. } while (integer & 32);
  2428. const shouldNegate = value & 1;
  2429. value >>>= 1;
  2430. if (shouldNegate) {
  2431. value = -0x80000000 | -value;
  2432. }
  2433. state[j] += value;
  2434. return pos;
  2435. }
  2436. function hasMoreVlq(mappings, i, length) {
  2437. if (i >= length)
  2438. return false;
  2439. return mappings.charCodeAt(i) !== comma;
  2440. }
  2441. function sort(line) {
  2442. line.sort(sortComparator);
  2443. }
  2444. function sortComparator(a, b) {
  2445. return a[0] - b[0];
  2446. }
  2447. function encode(decoded) {
  2448. const state = new Int32Array(5);
  2449. const bufLength = 1024 * 16;
  2450. const subLength = bufLength - 36;
  2451. const buf = new Uint8Array(bufLength);
  2452. const sub = buf.subarray(0, subLength);
  2453. let pos = 0;
  2454. let out = '';
  2455. for (let i = 0; i < decoded.length; i++) {
  2456. const line = decoded[i];
  2457. if (i > 0) {
  2458. if (pos === bufLength) {
  2459. out += td.decode(buf);
  2460. pos = 0;
  2461. }
  2462. buf[pos++] = semicolon;
  2463. }
  2464. if (line.length === 0)
  2465. continue;
  2466. state[0] = 0;
  2467. for (let j = 0; j < line.length; j++) {
  2468. const segment = line[j];
  2469. // We can push up to 5 ints, each int can take at most 7 chars, and we
  2470. // may push a comma.
  2471. if (pos > subLength) {
  2472. out += td.decode(sub);
  2473. buf.copyWithin(0, subLength, pos);
  2474. pos -= subLength;
  2475. }
  2476. if (j > 0)
  2477. buf[pos++] = comma;
  2478. pos = encodeInteger(buf, pos, state, segment, 0); // genColumn
  2479. if (segment.length === 1)
  2480. continue;
  2481. pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex
  2482. pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine
  2483. pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn
  2484. if (segment.length === 4)
  2485. continue;
  2486. pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex
  2487. }
  2488. }
  2489. return out + td.decode(buf.subarray(0, pos));
  2490. }
  2491. function encodeInteger(buf, pos, state, segment, j) {
  2492. const next = segment[j];
  2493. let num = next - state[j];
  2494. state[j] = next;
  2495. num = num < 0 ? (-num << 1) | 1 : num << 1;
  2496. do {
  2497. let clamped = num & 0b011111;
  2498. num >>>= 5;
  2499. if (num > 0)
  2500. clamped |= 0b100000;
  2501. buf[pos++] = intToChar[clamped];
  2502. } while (num > 0);
  2503. return pos;
  2504. }
  2505. class BitSet {
  2506. constructor(arg) {
  2507. this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
  2508. }
  2509. add(n) {
  2510. this.bits[n >> 5] |= 1 << (n & 31);
  2511. }
  2512. has(n) {
  2513. return !!(this.bits[n >> 5] & (1 << (n & 31)));
  2514. }
  2515. }
  2516. let Chunk$1 = class Chunk {
  2517. constructor(start, end, content) {
  2518. this.start = start;
  2519. this.end = end;
  2520. this.original = content;
  2521. this.intro = '';
  2522. this.outro = '';
  2523. this.content = content;
  2524. this.storeName = false;
  2525. this.edited = false;
  2526. {
  2527. this.previous = null;
  2528. this.next = null;
  2529. }
  2530. }
  2531. appendLeft(content) {
  2532. this.outro += content;
  2533. }
  2534. appendRight(content) {
  2535. this.intro = this.intro + content;
  2536. }
  2537. clone() {
  2538. const chunk = new Chunk(this.start, this.end, this.original);
  2539. chunk.intro = this.intro;
  2540. chunk.outro = this.outro;
  2541. chunk.content = this.content;
  2542. chunk.storeName = this.storeName;
  2543. chunk.edited = this.edited;
  2544. return chunk;
  2545. }
  2546. contains(index) {
  2547. return this.start < index && index < this.end;
  2548. }
  2549. eachNext(fn) {
  2550. let chunk = this;
  2551. while (chunk) {
  2552. fn(chunk);
  2553. chunk = chunk.next;
  2554. }
  2555. }
  2556. eachPrevious(fn) {
  2557. let chunk = this;
  2558. while (chunk) {
  2559. fn(chunk);
  2560. chunk = chunk.previous;
  2561. }
  2562. }
  2563. edit(content, storeName, contentOnly) {
  2564. this.content = content;
  2565. if (!contentOnly) {
  2566. this.intro = '';
  2567. this.outro = '';
  2568. }
  2569. this.storeName = storeName;
  2570. this.edited = true;
  2571. return this;
  2572. }
  2573. prependLeft(content) {
  2574. this.outro = content + this.outro;
  2575. }
  2576. prependRight(content) {
  2577. this.intro = content + this.intro;
  2578. }
  2579. split(index) {
  2580. const sliceIndex = index - this.start;
  2581. const originalBefore = this.original.slice(0, sliceIndex);
  2582. const originalAfter = this.original.slice(sliceIndex);
  2583. this.original = originalBefore;
  2584. const newChunk = new Chunk(index, this.end, originalAfter);
  2585. newChunk.outro = this.outro;
  2586. this.outro = '';
  2587. this.end = index;
  2588. if (this.edited) {
  2589. // after split we should save the edit content record into the correct chunk
  2590. // to make sure sourcemap correct
  2591. // For example:
  2592. // ' test'.trim()
  2593. // split -> ' ' + 'test'
  2594. // ✔️ edit -> '' + 'test'
  2595. // ✖️ edit -> 'test' + ''
  2596. // TODO is this block necessary?...
  2597. newChunk.edit('', false);
  2598. this.content = '';
  2599. } else {
  2600. this.content = originalBefore;
  2601. }
  2602. newChunk.next = this.next;
  2603. if (newChunk.next) newChunk.next.previous = newChunk;
  2604. newChunk.previous = this;
  2605. this.next = newChunk;
  2606. return newChunk;
  2607. }
  2608. toString() {
  2609. return this.intro + this.content + this.outro;
  2610. }
  2611. trimEnd(rx) {
  2612. this.outro = this.outro.replace(rx, '');
  2613. if (this.outro.length) return true;
  2614. const trimmed = this.content.replace(rx, '');
  2615. if (trimmed.length) {
  2616. if (trimmed !== this.content) {
  2617. this.split(this.start + trimmed.length).edit('', undefined, true);
  2618. if (this.edited) {
  2619. // save the change, if it has been edited
  2620. this.edit(trimmed, this.storeName, true);
  2621. }
  2622. }
  2623. return true;
  2624. } else {
  2625. this.edit('', undefined, true);
  2626. this.intro = this.intro.replace(rx, '');
  2627. if (this.intro.length) return true;
  2628. }
  2629. }
  2630. trimStart(rx) {
  2631. this.intro = this.intro.replace(rx, '');
  2632. if (this.intro.length) return true;
  2633. const trimmed = this.content.replace(rx, '');
  2634. if (trimmed.length) {
  2635. if (trimmed !== this.content) {
  2636. const newChunk = this.split(this.end - trimmed.length);
  2637. if (this.edited) {
  2638. // save the change, if it has been edited
  2639. newChunk.edit(trimmed, this.storeName, true);
  2640. }
  2641. this.edit('', undefined, true);
  2642. }
  2643. return true;
  2644. } else {
  2645. this.edit('', undefined, true);
  2646. this.outro = this.outro.replace(rx, '');
  2647. if (this.outro.length) return true;
  2648. }
  2649. }
  2650. };
  2651. function getBtoa() {
  2652. if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
  2653. return (str) => window.btoa(unescape(encodeURIComponent(str)));
  2654. } else if (typeof Buffer === 'function') {
  2655. return (str) => Buffer.from(str, 'utf-8').toString('base64');
  2656. } else {
  2657. return () => {
  2658. throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
  2659. };
  2660. }
  2661. }
  2662. const btoa = /*#__PURE__*/ getBtoa();
  2663. class SourceMap {
  2664. constructor(properties) {
  2665. this.version = 3;
  2666. this.file = properties.file;
  2667. this.sources = properties.sources;
  2668. this.sourcesContent = properties.sourcesContent;
  2669. this.names = properties.names;
  2670. this.mappings = encode(properties.mappings);
  2671. if (typeof properties.x_google_ignoreList !== 'undefined') {
  2672. this.x_google_ignoreList = properties.x_google_ignoreList;
  2673. }
  2674. }
  2675. toString() {
  2676. return JSON.stringify(this);
  2677. }
  2678. toUrl() {
  2679. return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
  2680. }
  2681. }
  2682. function guessIndent(code) {
  2683. const lines = code.split('\n');
  2684. const tabbed = lines.filter((line) => /^\t+/.test(line));
  2685. const spaced = lines.filter((line) => /^ {2,}/.test(line));
  2686. if (tabbed.length === 0 && spaced.length === 0) {
  2687. return null;
  2688. }
  2689. // More lines tabbed than spaced? Assume tabs, and
  2690. // default to tabs in the case of a tie (or nothing
  2691. // to go on)
  2692. if (tabbed.length >= spaced.length) {
  2693. return '\t';
  2694. }
  2695. // Otherwise, we need to guess the multiple
  2696. const min = spaced.reduce((previous, current) => {
  2697. const numSpaces = /^ +/.exec(current)[0].length;
  2698. return Math.min(numSpaces, previous);
  2699. }, Infinity);
  2700. return new Array(min + 1).join(' ');
  2701. }
  2702. function getRelativePath(from, to) {
  2703. const fromParts = from.split(/[/\\]/);
  2704. const toParts = to.split(/[/\\]/);
  2705. fromParts.pop(); // get dirname
  2706. while (fromParts[0] === toParts[0]) {
  2707. fromParts.shift();
  2708. toParts.shift();
  2709. }
  2710. if (fromParts.length) {
  2711. let i = fromParts.length;
  2712. while (i--) fromParts[i] = '..';
  2713. }
  2714. return fromParts.concat(toParts).join('/');
  2715. }
  2716. const toString$1 = Object.prototype.toString;
  2717. function isObject$1(thing) {
  2718. return toString$1.call(thing) === '[object Object]';
  2719. }
  2720. function getLocator(source) {
  2721. const originalLines = source.split('\n');
  2722. const lineOffsets = [];
  2723. for (let i = 0, pos = 0; i < originalLines.length; i++) {
  2724. lineOffsets.push(pos);
  2725. pos += originalLines[i].length + 1;
  2726. }
  2727. return function locate(index) {
  2728. let i = 0;
  2729. let j = lineOffsets.length;
  2730. while (i < j) {
  2731. const m = (i + j) >> 1;
  2732. if (index < lineOffsets[m]) {
  2733. j = m;
  2734. } else {
  2735. i = m + 1;
  2736. }
  2737. }
  2738. const line = i - 1;
  2739. const column = index - lineOffsets[line];
  2740. return { line, column };
  2741. };
  2742. }
  2743. const wordRegex = /\w/;
  2744. class Mappings {
  2745. constructor(hires) {
  2746. this.hires = hires;
  2747. this.generatedCodeLine = 0;
  2748. this.generatedCodeColumn = 0;
  2749. this.raw = [];
  2750. this.rawSegments = this.raw[this.generatedCodeLine] = [];
  2751. this.pending = null;
  2752. }
  2753. addEdit(sourceIndex, content, loc, nameIndex) {
  2754. if (content.length) {
  2755. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  2756. if (nameIndex >= 0) {
  2757. segment.push(nameIndex);
  2758. }
  2759. this.rawSegments.push(segment);
  2760. } else if (this.pending) {
  2761. this.rawSegments.push(this.pending);
  2762. }
  2763. this.advance(content);
  2764. this.pending = null;
  2765. }
  2766. addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
  2767. let originalCharIndex = chunk.start;
  2768. let first = true;
  2769. // when iterating each char, check if it's in a word boundary
  2770. let charInHiresBoundary = false;
  2771. while (originalCharIndex < chunk.end) {
  2772. if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
  2773. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  2774. if (this.hires === 'boundary') {
  2775. // in hires "boundary", group segments per word boundary than per char
  2776. if (wordRegex.test(original[originalCharIndex])) {
  2777. // for first char in the boundary found, start the boundary by pushing a segment
  2778. if (!charInHiresBoundary) {
  2779. this.rawSegments.push(segment);
  2780. charInHiresBoundary = true;
  2781. }
  2782. } else {
  2783. // for non-word char, end the boundary by pushing a segment
  2784. this.rawSegments.push(segment);
  2785. charInHiresBoundary = false;
  2786. }
  2787. } else {
  2788. this.rawSegments.push(segment);
  2789. }
  2790. }
  2791. if (original[originalCharIndex] === '\n') {
  2792. loc.line += 1;
  2793. loc.column = 0;
  2794. this.generatedCodeLine += 1;
  2795. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  2796. this.generatedCodeColumn = 0;
  2797. first = true;
  2798. } else {
  2799. loc.column += 1;
  2800. this.generatedCodeColumn += 1;
  2801. first = false;
  2802. }
  2803. originalCharIndex += 1;
  2804. }
  2805. this.pending = null;
  2806. }
  2807. advance(str) {
  2808. if (!str) return;
  2809. const lines = str.split('\n');
  2810. if (lines.length > 1) {
  2811. for (let i = 0; i < lines.length - 1; i++) {
  2812. this.generatedCodeLine++;
  2813. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  2814. }
  2815. this.generatedCodeColumn = 0;
  2816. }
  2817. this.generatedCodeColumn += lines[lines.length - 1].length;
  2818. }
  2819. }
  2820. const n = '\n';
  2821. const warned = {
  2822. insertLeft: false,
  2823. insertRight: false,
  2824. storeName: false,
  2825. };
  2826. class MagicString {
  2827. constructor(string, options = {}) {
  2828. const chunk = new Chunk$1(0, string.length, string);
  2829. Object.defineProperties(this, {
  2830. original: { writable: true, value: string },
  2831. outro: { writable: true, value: '' },
  2832. intro: { writable: true, value: '' },
  2833. firstChunk: { writable: true, value: chunk },
  2834. lastChunk: { writable: true, value: chunk },
  2835. lastSearchedChunk: { writable: true, value: chunk },
  2836. byStart: { writable: true, value: {} },
  2837. byEnd: { writable: true, value: {} },
  2838. filename: { writable: true, value: options.filename },
  2839. indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
  2840. sourcemapLocations: { writable: true, value: new BitSet() },
  2841. storedNames: { writable: true, value: {} },
  2842. indentStr: { writable: true, value: undefined },
  2843. ignoreList: { writable: true, value: options.ignoreList },
  2844. });
  2845. this.byStart[0] = chunk;
  2846. this.byEnd[string.length] = chunk;
  2847. }
  2848. addSourcemapLocation(char) {
  2849. this.sourcemapLocations.add(char);
  2850. }
  2851. append(content) {
  2852. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  2853. this.outro += content;
  2854. return this;
  2855. }
  2856. appendLeft(index, content) {
  2857. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  2858. this._split(index);
  2859. const chunk = this.byEnd[index];
  2860. if (chunk) {
  2861. chunk.appendLeft(content);
  2862. } else {
  2863. this.intro += content;
  2864. }
  2865. return this;
  2866. }
  2867. appendRight(index, content) {
  2868. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  2869. this._split(index);
  2870. const chunk = this.byStart[index];
  2871. if (chunk) {
  2872. chunk.appendRight(content);
  2873. } else {
  2874. this.outro += content;
  2875. }
  2876. return this;
  2877. }
  2878. clone() {
  2879. const cloned = new MagicString(this.original, { filename: this.filename });
  2880. let originalChunk = this.firstChunk;
  2881. let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
  2882. while (originalChunk) {
  2883. cloned.byStart[clonedChunk.start] = clonedChunk;
  2884. cloned.byEnd[clonedChunk.end] = clonedChunk;
  2885. const nextOriginalChunk = originalChunk.next;
  2886. const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
  2887. if (nextClonedChunk) {
  2888. clonedChunk.next = nextClonedChunk;
  2889. nextClonedChunk.previous = clonedChunk;
  2890. clonedChunk = nextClonedChunk;
  2891. }
  2892. originalChunk = nextOriginalChunk;
  2893. }
  2894. cloned.lastChunk = clonedChunk;
  2895. if (this.indentExclusionRanges) {
  2896. cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
  2897. }
  2898. cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
  2899. cloned.intro = this.intro;
  2900. cloned.outro = this.outro;
  2901. return cloned;
  2902. }
  2903. generateDecodedMap(options) {
  2904. options = options || {};
  2905. const sourceIndex = 0;
  2906. const names = Object.keys(this.storedNames);
  2907. const mappings = new Mappings(options.hires);
  2908. const locate = getLocator(this.original);
  2909. if (this.intro) {
  2910. mappings.advance(this.intro);
  2911. }
  2912. this.firstChunk.eachNext((chunk) => {
  2913. const loc = locate(chunk.start);
  2914. if (chunk.intro.length) mappings.advance(chunk.intro);
  2915. if (chunk.edited) {
  2916. mappings.addEdit(
  2917. sourceIndex,
  2918. chunk.content,
  2919. loc,
  2920. chunk.storeName ? names.indexOf(chunk.original) : -1,
  2921. );
  2922. } else {
  2923. mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
  2924. }
  2925. if (chunk.outro.length) mappings.advance(chunk.outro);
  2926. });
  2927. return {
  2928. file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
  2929. sources: [
  2930. options.source ? getRelativePath(options.file || '', options.source) : options.file || '',
  2931. ],
  2932. sourcesContent: options.includeContent ? [this.original] : undefined,
  2933. names,
  2934. mappings: mappings.raw,
  2935. x_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined,
  2936. };
  2937. }
  2938. generateMap(options) {
  2939. return new SourceMap(this.generateDecodedMap(options));
  2940. }
  2941. _ensureindentStr() {
  2942. if (this.indentStr === undefined) {
  2943. this.indentStr = guessIndent(this.original);
  2944. }
  2945. }
  2946. _getRawIndentString() {
  2947. this._ensureindentStr();
  2948. return this.indentStr;
  2949. }
  2950. getIndentString() {
  2951. this._ensureindentStr();
  2952. return this.indentStr === null ? '\t' : this.indentStr;
  2953. }
  2954. indent(indentStr, options) {
  2955. const pattern = /^[^\r\n]/gm;
  2956. if (isObject$1(indentStr)) {
  2957. options = indentStr;
  2958. indentStr = undefined;
  2959. }
  2960. if (indentStr === undefined) {
  2961. this._ensureindentStr();
  2962. indentStr = this.indentStr || '\t';
  2963. }
  2964. if (indentStr === '') return this; // noop
  2965. options = options || {};
  2966. // Process exclusion ranges
  2967. const isExcluded = {};
  2968. if (options.exclude) {
  2969. const exclusions =
  2970. typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
  2971. exclusions.forEach((exclusion) => {
  2972. for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
  2973. isExcluded[i] = true;
  2974. }
  2975. });
  2976. }
  2977. let shouldIndentNextCharacter = options.indentStart !== false;
  2978. const replacer = (match) => {
  2979. if (shouldIndentNextCharacter) return `${indentStr}${match}`;
  2980. shouldIndentNextCharacter = true;
  2981. return match;
  2982. };
  2983. this.intro = this.intro.replace(pattern, replacer);
  2984. let charIndex = 0;
  2985. let chunk = this.firstChunk;
  2986. while (chunk) {
  2987. const end = chunk.end;
  2988. if (chunk.edited) {
  2989. if (!isExcluded[charIndex]) {
  2990. chunk.content = chunk.content.replace(pattern, replacer);
  2991. if (chunk.content.length) {
  2992. shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
  2993. }
  2994. }
  2995. } else {
  2996. charIndex = chunk.start;
  2997. while (charIndex < end) {
  2998. if (!isExcluded[charIndex]) {
  2999. const char = this.original[charIndex];
  3000. if (char === '\n') {
  3001. shouldIndentNextCharacter = true;
  3002. } else if (char !== '\r' && shouldIndentNextCharacter) {
  3003. shouldIndentNextCharacter = false;
  3004. if (charIndex === chunk.start) {
  3005. chunk.prependRight(indentStr);
  3006. } else {
  3007. this._splitChunk(chunk, charIndex);
  3008. chunk = chunk.next;
  3009. chunk.prependRight(indentStr);
  3010. }
  3011. }
  3012. }
  3013. charIndex += 1;
  3014. }
  3015. }
  3016. charIndex = chunk.end;
  3017. chunk = chunk.next;
  3018. }
  3019. this.outro = this.outro.replace(pattern, replacer);
  3020. return this;
  3021. }
  3022. insert() {
  3023. throw new Error(
  3024. 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)',
  3025. );
  3026. }
  3027. insertLeft(index, content) {
  3028. if (!warned.insertLeft) {
  3029. console.warn(
  3030. 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead',
  3031. ); // eslint-disable-line no-console
  3032. warned.insertLeft = true;
  3033. }
  3034. return this.appendLeft(index, content);
  3035. }
  3036. insertRight(index, content) {
  3037. if (!warned.insertRight) {
  3038. console.warn(
  3039. 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead',
  3040. ); // eslint-disable-line no-console
  3041. warned.insertRight = true;
  3042. }
  3043. return this.prependRight(index, content);
  3044. }
  3045. move(start, end, index) {
  3046. if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself');
  3047. this._split(start);
  3048. this._split(end);
  3049. this._split(index);
  3050. const first = this.byStart[start];
  3051. const last = this.byEnd[end];
  3052. const oldLeft = first.previous;
  3053. const oldRight = last.next;
  3054. const newRight = this.byStart[index];
  3055. if (!newRight && last === this.lastChunk) return this;
  3056. const newLeft = newRight ? newRight.previous : this.lastChunk;
  3057. if (oldLeft) oldLeft.next = oldRight;
  3058. if (oldRight) oldRight.previous = oldLeft;
  3059. if (newLeft) newLeft.next = first;
  3060. if (newRight) newRight.previous = last;
  3061. if (!first.previous) this.firstChunk = last.next;
  3062. if (!last.next) {
  3063. this.lastChunk = first.previous;
  3064. this.lastChunk.next = null;
  3065. }
  3066. first.previous = newLeft;
  3067. last.next = newRight || null;
  3068. if (!newLeft) this.firstChunk = first;
  3069. if (!newRight) this.lastChunk = last;
  3070. return this;
  3071. }
  3072. overwrite(start, end, content, options) {
  3073. options = options || {};
  3074. return this.update(start, end, content, { ...options, overwrite: !options.contentOnly });
  3075. }
  3076. update(start, end, content, options) {
  3077. if (typeof content !== 'string') throw new TypeError('replacement content must be a string');
  3078. while (start < 0) start += this.original.length;
  3079. while (end < 0) end += this.original.length;
  3080. if (end > this.original.length) throw new Error('end is out of bounds');
  3081. if (start === end)
  3082. throw new Error(
  3083. 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead',
  3084. );
  3085. this._split(start);
  3086. this._split(end);
  3087. if (options === true) {
  3088. if (!warned.storeName) {
  3089. console.warn(
  3090. 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string',
  3091. ); // eslint-disable-line no-console
  3092. warned.storeName = true;
  3093. }
  3094. options = { storeName: true };
  3095. }
  3096. const storeName = options !== undefined ? options.storeName : false;
  3097. const overwrite = options !== undefined ? options.overwrite : false;
  3098. if (storeName) {
  3099. const original = this.original.slice(start, end);
  3100. Object.defineProperty(this.storedNames, original, {
  3101. writable: true,
  3102. value: true,
  3103. enumerable: true,
  3104. });
  3105. }
  3106. const first = this.byStart[start];
  3107. const last = this.byEnd[end];
  3108. if (first) {
  3109. let chunk = first;
  3110. while (chunk !== last) {
  3111. if (chunk.next !== this.byStart[chunk.end]) {
  3112. throw new Error('Cannot overwrite across a split point');
  3113. }
  3114. chunk = chunk.next;
  3115. chunk.edit('', false);
  3116. }
  3117. first.edit(content, storeName, !overwrite);
  3118. } else {
  3119. // must be inserting at the end
  3120. const newChunk = new Chunk$1(start, end, '').edit(content, storeName);
  3121. // TODO last chunk in the array may not be the last chunk, if it's moved...
  3122. last.next = newChunk;
  3123. newChunk.previous = last;
  3124. }
  3125. return this;
  3126. }
  3127. prepend(content) {
  3128. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  3129. this.intro = content + this.intro;
  3130. return this;
  3131. }
  3132. prependLeft(index, content) {
  3133. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  3134. this._split(index);
  3135. const chunk = this.byEnd[index];
  3136. if (chunk) {
  3137. chunk.prependLeft(content);
  3138. } else {
  3139. this.intro = content + this.intro;
  3140. }
  3141. return this;
  3142. }
  3143. prependRight(index, content) {
  3144. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  3145. this._split(index);
  3146. const chunk = this.byStart[index];
  3147. if (chunk) {
  3148. chunk.prependRight(content);
  3149. } else {
  3150. this.outro = content + this.outro;
  3151. }
  3152. return this;
  3153. }
  3154. remove(start, end) {
  3155. while (start < 0) start += this.original.length;
  3156. while (end < 0) end += this.original.length;
  3157. if (start === end) return this;
  3158. if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
  3159. if (start > end) throw new Error('end must be greater than start');
  3160. this._split(start);
  3161. this._split(end);
  3162. let chunk = this.byStart[start];
  3163. while (chunk) {
  3164. chunk.intro = '';
  3165. chunk.outro = '';
  3166. chunk.edit('');
  3167. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  3168. }
  3169. return this;
  3170. }
  3171. lastChar() {
  3172. if (this.outro.length) return this.outro[this.outro.length - 1];
  3173. let chunk = this.lastChunk;
  3174. do {
  3175. if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
  3176. if (chunk.content.length) return chunk.content[chunk.content.length - 1];
  3177. if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
  3178. } while ((chunk = chunk.previous));
  3179. if (this.intro.length) return this.intro[this.intro.length - 1];
  3180. return '';
  3181. }
  3182. lastLine() {
  3183. let lineIndex = this.outro.lastIndexOf(n);
  3184. if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
  3185. let lineStr = this.outro;
  3186. let chunk = this.lastChunk;
  3187. do {
  3188. if (chunk.outro.length > 0) {
  3189. lineIndex = chunk.outro.lastIndexOf(n);
  3190. if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
  3191. lineStr = chunk.outro + lineStr;
  3192. }
  3193. if (chunk.content.length > 0) {
  3194. lineIndex = chunk.content.lastIndexOf(n);
  3195. if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
  3196. lineStr = chunk.content + lineStr;
  3197. }
  3198. if (chunk.intro.length > 0) {
  3199. lineIndex = chunk.intro.lastIndexOf(n);
  3200. if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
  3201. lineStr = chunk.intro + lineStr;
  3202. }
  3203. } while ((chunk = chunk.previous));
  3204. lineIndex = this.intro.lastIndexOf(n);
  3205. if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
  3206. return this.intro + lineStr;
  3207. }
  3208. slice(start = 0, end = this.original.length) {
  3209. while (start < 0) start += this.original.length;
  3210. while (end < 0) end += this.original.length;
  3211. let result = '';
  3212. // find start chunk
  3213. let chunk = this.firstChunk;
  3214. while (chunk && (chunk.start > start || chunk.end <= start)) {
  3215. // found end chunk before start
  3216. if (chunk.start < end && chunk.end >= end) {
  3217. return result;
  3218. }
  3219. chunk = chunk.next;
  3220. }
  3221. if (chunk && chunk.edited && chunk.start !== start)
  3222. throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
  3223. const startChunk = chunk;
  3224. while (chunk) {
  3225. if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
  3226. result += chunk.intro;
  3227. }
  3228. const containsEnd = chunk.start < end && chunk.end >= end;
  3229. if (containsEnd && chunk.edited && chunk.end !== end)
  3230. throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
  3231. const sliceStart = startChunk === chunk ? start - chunk.start : 0;
  3232. const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
  3233. result += chunk.content.slice(sliceStart, sliceEnd);
  3234. if (chunk.outro && (!containsEnd || chunk.end === end)) {
  3235. result += chunk.outro;
  3236. }
  3237. if (containsEnd) {
  3238. break;
  3239. }
  3240. chunk = chunk.next;
  3241. }
  3242. return result;
  3243. }
  3244. // TODO deprecate this? not really very useful
  3245. snip(start, end) {
  3246. const clone = this.clone();
  3247. clone.remove(0, start);
  3248. clone.remove(end, clone.original.length);
  3249. return clone;
  3250. }
  3251. _split(index) {
  3252. if (this.byStart[index] || this.byEnd[index]) return;
  3253. let chunk = this.lastSearchedChunk;
  3254. const searchForward = index > chunk.end;
  3255. while (chunk) {
  3256. if (chunk.contains(index)) return this._splitChunk(chunk, index);
  3257. chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
  3258. }
  3259. }
  3260. _splitChunk(chunk, index) {
  3261. if (chunk.edited && chunk.content.length) {
  3262. // zero-length edited chunks are a special case (overlapping replacements)
  3263. const loc = getLocator(this.original)(index);
  3264. throw new Error(
  3265. `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`,
  3266. );
  3267. }
  3268. const newChunk = chunk.split(index);
  3269. this.byEnd[index] = chunk;
  3270. this.byStart[index] = newChunk;
  3271. this.byEnd[newChunk.end] = newChunk;
  3272. if (chunk === this.lastChunk) this.lastChunk = newChunk;
  3273. this.lastSearchedChunk = chunk;
  3274. return true;
  3275. }
  3276. toString() {
  3277. let str = this.intro;
  3278. let chunk = this.firstChunk;
  3279. while (chunk) {
  3280. str += chunk.toString();
  3281. chunk = chunk.next;
  3282. }
  3283. return str + this.outro;
  3284. }
  3285. isEmpty() {
  3286. let chunk = this.firstChunk;
  3287. do {
  3288. if (
  3289. (chunk.intro.length && chunk.intro.trim()) ||
  3290. (chunk.content.length && chunk.content.trim()) ||
  3291. (chunk.outro.length && chunk.outro.trim())
  3292. )
  3293. return false;
  3294. } while ((chunk = chunk.next));
  3295. return true;
  3296. }
  3297. length() {
  3298. let chunk = this.firstChunk;
  3299. let length = 0;
  3300. do {
  3301. length += chunk.intro.length + chunk.content.length + chunk.outro.length;
  3302. } while ((chunk = chunk.next));
  3303. return length;
  3304. }
  3305. trimLines() {
  3306. return this.trim('[\\r\\n]');
  3307. }
  3308. trim(charType) {
  3309. return this.trimStart(charType).trimEnd(charType);
  3310. }
  3311. trimEndAborted(charType) {
  3312. const rx = new RegExp((charType || '\\s') + '+$');
  3313. this.outro = this.outro.replace(rx, '');
  3314. if (this.outro.length) return true;
  3315. let chunk = this.lastChunk;
  3316. do {
  3317. const end = chunk.end;
  3318. const aborted = chunk.trimEnd(rx);
  3319. // if chunk was trimmed, we have a new lastChunk
  3320. if (chunk.end !== end) {
  3321. if (this.lastChunk === chunk) {
  3322. this.lastChunk = chunk.next;
  3323. }
  3324. this.byEnd[chunk.end] = chunk;
  3325. this.byStart[chunk.next.start] = chunk.next;
  3326. this.byEnd[chunk.next.end] = chunk.next;
  3327. }
  3328. if (aborted) return true;
  3329. chunk = chunk.previous;
  3330. } while (chunk);
  3331. return false;
  3332. }
  3333. trimEnd(charType) {
  3334. this.trimEndAborted(charType);
  3335. return this;
  3336. }
  3337. trimStartAborted(charType) {
  3338. const rx = new RegExp('^' + (charType || '\\s') + '+');
  3339. this.intro = this.intro.replace(rx, '');
  3340. if (this.intro.length) return true;
  3341. let chunk = this.firstChunk;
  3342. do {
  3343. const end = chunk.end;
  3344. const aborted = chunk.trimStart(rx);
  3345. if (chunk.end !== end) {
  3346. // special case...
  3347. if (chunk === this.lastChunk) this.lastChunk = chunk.next;
  3348. this.byEnd[chunk.end] = chunk;
  3349. this.byStart[chunk.next.start] = chunk.next;
  3350. this.byEnd[chunk.next.end] = chunk.next;
  3351. }
  3352. if (aborted) return true;
  3353. chunk = chunk.next;
  3354. } while (chunk);
  3355. return false;
  3356. }
  3357. trimStart(charType) {
  3358. this.trimStartAborted(charType);
  3359. return this;
  3360. }
  3361. hasChanged() {
  3362. return this.original !== this.toString();
  3363. }
  3364. _replaceRegexp(searchValue, replacement) {
  3365. function getReplacement(match, str) {
  3366. if (typeof replacement === 'string') {
  3367. return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
  3368. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
  3369. if (i === '$') return '$';
  3370. if (i === '&') return match[0];
  3371. const num = +i;
  3372. if (num < match.length) return match[+i];
  3373. return `$${i}`;
  3374. });
  3375. } else {
  3376. return replacement(...match, match.index, str, match.groups);
  3377. }
  3378. }
  3379. function matchAll(re, str) {
  3380. let match;
  3381. const matches = [];
  3382. while ((match = re.exec(str))) {
  3383. matches.push(match);
  3384. }
  3385. return matches;
  3386. }
  3387. if (searchValue.global) {
  3388. const matches = matchAll(searchValue, this.original);
  3389. matches.forEach((match) => {
  3390. if (match.index != null)
  3391. this.overwrite(
  3392. match.index,
  3393. match.index + match[0].length,
  3394. getReplacement(match, this.original),
  3395. );
  3396. });
  3397. } else {
  3398. const match = this.original.match(searchValue);
  3399. if (match && match.index != null)
  3400. this.overwrite(
  3401. match.index,
  3402. match.index + match[0].length,
  3403. getReplacement(match, this.original),
  3404. );
  3405. }
  3406. return this;
  3407. }
  3408. _replaceString(string, replacement) {
  3409. const { original } = this;
  3410. const index = original.indexOf(string);
  3411. if (index !== -1) {
  3412. this.overwrite(index, index + string.length, replacement);
  3413. }
  3414. return this;
  3415. }
  3416. replace(searchValue, replacement) {
  3417. if (typeof searchValue === 'string') {
  3418. return this._replaceString(searchValue, replacement);
  3419. }
  3420. return this._replaceRegexp(searchValue, replacement);
  3421. }
  3422. _replaceAllString(string, replacement) {
  3423. const { original } = this;
  3424. const stringLength = string.length;
  3425. for (
  3426. let index = original.indexOf(string);
  3427. index !== -1;
  3428. index = original.indexOf(string, index + stringLength)
  3429. ) {
  3430. this.overwrite(index, index + stringLength, replacement);
  3431. }
  3432. return this;
  3433. }
  3434. replaceAll(searchValue, replacement) {
  3435. if (typeof searchValue === 'string') {
  3436. return this._replaceAllString(searchValue, replacement);
  3437. }
  3438. if (!searchValue.global) {
  3439. throw new TypeError(
  3440. 'MagicString.prototype.replaceAll called with a non-global RegExp argument',
  3441. );
  3442. }
  3443. return this._replaceRegexp(searchValue, replacement);
  3444. }
  3445. }
  3446. const hasOwnProp = Object.prototype.hasOwnProperty;
  3447. let Bundle$1 = class Bundle {
  3448. constructor(options = {}) {
  3449. this.intro = options.intro || '';
  3450. this.separator = options.separator !== undefined ? options.separator : '\n';
  3451. this.sources = [];
  3452. this.uniqueSources = [];
  3453. this.uniqueSourceIndexByFilename = {};
  3454. }
  3455. addSource(source) {
  3456. if (source instanceof MagicString) {
  3457. return this.addSource({
  3458. content: source,
  3459. filename: source.filename,
  3460. separator: this.separator,
  3461. });
  3462. }
  3463. if (!isObject$1(source) || !source.content) {
  3464. throw new Error(
  3465. 'bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`',
  3466. );
  3467. }
  3468. ['filename', 'ignoreList', 'indentExclusionRanges', 'separator'].forEach((option) => {
  3469. if (!hasOwnProp.call(source, option)) source[option] = source.content[option];
  3470. });
  3471. if (source.separator === undefined) {
  3472. // TODO there's a bunch of this sort of thing, needs cleaning up
  3473. source.separator = this.separator;
  3474. }
  3475. if (source.filename) {
  3476. if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {
  3477. this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;
  3478. this.uniqueSources.push({ filename: source.filename, content: source.content.original });
  3479. } else {
  3480. const uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];
  3481. if (source.content.original !== uniqueSource.content) {
  3482. throw new Error(`Illegal source: same filename (${source.filename}), different contents`);
  3483. }
  3484. }
  3485. }
  3486. this.sources.push(source);
  3487. return this;
  3488. }
  3489. append(str, options) {
  3490. this.addSource({
  3491. content: new MagicString(str),
  3492. separator: (options && options.separator) || '',
  3493. });
  3494. return this;
  3495. }
  3496. clone() {
  3497. const bundle = new Bundle({
  3498. intro: this.intro,
  3499. separator: this.separator,
  3500. });
  3501. this.sources.forEach((source) => {
  3502. bundle.addSource({
  3503. filename: source.filename,
  3504. content: source.content.clone(),
  3505. separator: source.separator,
  3506. });
  3507. });
  3508. return bundle;
  3509. }
  3510. generateDecodedMap(options = {}) {
  3511. const names = [];
  3512. let x_google_ignoreList = undefined;
  3513. this.sources.forEach((source) => {
  3514. Object.keys(source.content.storedNames).forEach((name) => {
  3515. if (!~names.indexOf(name)) names.push(name);
  3516. });
  3517. });
  3518. const mappings = new Mappings(options.hires);
  3519. if (this.intro) {
  3520. mappings.advance(this.intro);
  3521. }
  3522. this.sources.forEach((source, i) => {
  3523. if (i > 0) {
  3524. mappings.advance(this.separator);
  3525. }
  3526. const sourceIndex = source.filename ? this.uniqueSourceIndexByFilename[source.filename] : -1;
  3527. const magicString = source.content;
  3528. const locate = getLocator(magicString.original);
  3529. if (magicString.intro) {
  3530. mappings.advance(magicString.intro);
  3531. }
  3532. magicString.firstChunk.eachNext((chunk) => {
  3533. const loc = locate(chunk.start);
  3534. if (chunk.intro.length) mappings.advance(chunk.intro);
  3535. if (source.filename) {
  3536. if (chunk.edited) {
  3537. mappings.addEdit(
  3538. sourceIndex,
  3539. chunk.content,
  3540. loc,
  3541. chunk.storeName ? names.indexOf(chunk.original) : -1,
  3542. );
  3543. } else {
  3544. mappings.addUneditedChunk(
  3545. sourceIndex,
  3546. chunk,
  3547. magicString.original,
  3548. loc,
  3549. magicString.sourcemapLocations,
  3550. );
  3551. }
  3552. } else {
  3553. mappings.advance(chunk.content);
  3554. }
  3555. if (chunk.outro.length) mappings.advance(chunk.outro);
  3556. });
  3557. if (magicString.outro) {
  3558. mappings.advance(magicString.outro);
  3559. }
  3560. if (source.ignoreList && sourceIndex !== -1) {
  3561. if (x_google_ignoreList === undefined) {
  3562. x_google_ignoreList = [];
  3563. }
  3564. x_google_ignoreList.push(sourceIndex);
  3565. }
  3566. });
  3567. return {
  3568. file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
  3569. sources: this.uniqueSources.map((source) => {
  3570. return options.file ? getRelativePath(options.file, source.filename) : source.filename;
  3571. }),
  3572. sourcesContent: this.uniqueSources.map((source) => {
  3573. return options.includeContent ? source.content : null;
  3574. }),
  3575. names,
  3576. mappings: mappings.raw,
  3577. x_google_ignoreList,
  3578. };
  3579. }
  3580. generateMap(options) {
  3581. return new SourceMap(this.generateDecodedMap(options));
  3582. }
  3583. getIndentString() {
  3584. const indentStringCounts = {};
  3585. this.sources.forEach((source) => {
  3586. const indentStr = source.content._getRawIndentString();
  3587. if (indentStr === null) return;
  3588. if (!indentStringCounts[indentStr]) indentStringCounts[indentStr] = 0;
  3589. indentStringCounts[indentStr] += 1;
  3590. });
  3591. return (
  3592. Object.keys(indentStringCounts).sort((a, b) => {
  3593. return indentStringCounts[a] - indentStringCounts[b];
  3594. })[0] || '\t'
  3595. );
  3596. }
  3597. indent(indentStr) {
  3598. if (!arguments.length) {
  3599. indentStr = this.getIndentString();
  3600. }
  3601. if (indentStr === '') return this; // noop
  3602. let trailingNewline = !this.intro || this.intro.slice(-1) === '\n';
  3603. this.sources.forEach((source, i) => {
  3604. const separator = source.separator !== undefined ? source.separator : this.separator;
  3605. const indentStart = trailingNewline || (i > 0 && /\r?\n$/.test(separator));
  3606. source.content.indent(indentStr, {
  3607. exclude: source.indentExclusionRanges,
  3608. indentStart, //: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator )
  3609. });
  3610. trailingNewline = source.content.lastChar() === '\n';
  3611. });
  3612. if (this.intro) {
  3613. this.intro =
  3614. indentStr +
  3615. this.intro.replace(/^[^\n]/gm, (match, index) => {
  3616. return index > 0 ? indentStr + match : match;
  3617. });
  3618. }
  3619. return this;
  3620. }
  3621. prepend(str) {
  3622. this.intro = str + this.intro;
  3623. return this;
  3624. }
  3625. toString() {
  3626. const body = this.sources
  3627. .map((source, i) => {
  3628. const separator = source.separator !== undefined ? source.separator : this.separator;
  3629. const str = (i > 0 ? separator : '') + source.content.toString();
  3630. return str;
  3631. })
  3632. .join('');
  3633. return this.intro + body;
  3634. }
  3635. isEmpty() {
  3636. if (this.intro.length && this.intro.trim()) return false;
  3637. if (this.sources.some((source) => !source.content.isEmpty())) return false;
  3638. return true;
  3639. }
  3640. length() {
  3641. return this.sources.reduce(
  3642. (length, source) => length + source.content.length(),
  3643. this.intro.length,
  3644. );
  3645. }
  3646. trimLines() {
  3647. return this.trim('[\\r\\n]');
  3648. }
  3649. trim(charType) {
  3650. return this.trimStart(charType).trimEnd(charType);
  3651. }
  3652. trimStart(charType) {
  3653. const rx = new RegExp('^' + (charType || '\\s') + '+');
  3654. this.intro = this.intro.replace(rx, '');
  3655. if (!this.intro) {
  3656. let source;
  3657. let i = 0;
  3658. do {
  3659. source = this.sources[i++];
  3660. if (!source) {
  3661. break;
  3662. }
  3663. } while (!source.content.trimStartAborted(charType));
  3664. }
  3665. return this;
  3666. }
  3667. trimEnd(charType) {
  3668. const rx = new RegExp((charType || '\\s') + '+$');
  3669. let source;
  3670. let i = this.sources.length - 1;
  3671. do {
  3672. source = this.sources[i--];
  3673. if (!source) {
  3674. this.intro = this.intro.replace(rx, '');
  3675. break;
  3676. }
  3677. } while (!source.content.trimEndAborted(charType));
  3678. return this;
  3679. }
  3680. };
  3681. const needsEscapeRegEx = /[\n\r'\\\u2028\u2029]/;
  3682. const quoteNewlineRegEx = /([\n\r'\u2028\u2029])/g;
  3683. const backSlashRegEx = /\\/g;
  3684. function escapeId(id) {
  3685. if (!needsEscapeRegEx.test(id))
  3686. return id;
  3687. return id.replace(backSlashRegEx, '\\\\').replace(quoteNewlineRegEx, '\\$1');
  3688. }
  3689. class ExternalChunk {
  3690. constructor(module, options, inputBase) {
  3691. this.options = options;
  3692. this.inputBase = inputBase;
  3693. this.defaultVariableName = '';
  3694. this.namespaceVariableName = '';
  3695. this.variableName = '';
  3696. this.fileName = null;
  3697. this.importAssertions = null;
  3698. this.id = module.id;
  3699. this.moduleInfo = module.info;
  3700. this.renormalizeRenderPath = module.renormalizeRenderPath;
  3701. this.suggestedVariableName = module.suggestedVariableName;
  3702. }
  3703. getFileName() {
  3704. if (this.fileName) {
  3705. return this.fileName;
  3706. }
  3707. const { paths } = this.options;
  3708. return (this.fileName =
  3709. (typeof paths === 'function' ? paths(this.id) : paths[this.id]) ||
  3710. (this.renormalizeRenderPath ? normalize(node_path.relative(this.inputBase, this.id)) : this.id));
  3711. }
  3712. getImportAssertions(snippets) {
  3713. return (this.importAssertions || (this.importAssertions = formatAssertions(this.options.format === 'es' &&
  3714. this.options.externalImportAssertions &&
  3715. this.moduleInfo.assertions, snippets)));
  3716. }
  3717. getImportPath(importer) {
  3718. return escapeId(this.renormalizeRenderPath
  3719. ? getImportPath(importer, this.getFileName(), this.options.format === 'amd', false)
  3720. : this.getFileName());
  3721. }
  3722. }
  3723. function formatAssertions(assertions, { getObject }) {
  3724. if (!assertions) {
  3725. return null;
  3726. }
  3727. const assertionEntries = Object.entries(assertions).map(([key, value]) => [key, `'${value}'`]);
  3728. if (assertionEntries.length > 0) {
  3729. return getObject(assertionEntries, { lineBreakIndent: null });
  3730. }
  3731. return null;
  3732. }
  3733. const UnknownKey = Symbol('Unknown Key');
  3734. const UnknownNonAccessorKey = Symbol('Unknown Non-Accessor Key');
  3735. const UnknownInteger = Symbol('Unknown Integer');
  3736. const SymbolToStringTag = Symbol('Symbol.toStringTag');
  3737. const EMPTY_PATH = [];
  3738. const UNKNOWN_PATH = [UnknownKey];
  3739. // For deoptimizations, this means we are modifying an unknown property but did
  3740. // not lose track of the object or are creating a setter/getter;
  3741. // For assignment effects it means we do not check for setter/getter effects
  3742. // but only if something is mutated that is included, which is relevant for
  3743. // Object.defineProperty
  3744. const UNKNOWN_NON_ACCESSOR_PATH = [UnknownNonAccessorKey];
  3745. const UNKNOWN_INTEGER_PATH = [UnknownInteger];
  3746. const EntitiesKey = Symbol('Entities');
  3747. class PathTracker {
  3748. constructor() {
  3749. this.entityPaths = Object.create(null, {
  3750. [EntitiesKey]: { value: new Set() }
  3751. });
  3752. }
  3753. trackEntityAtPathAndGetIfTracked(path, entity) {
  3754. const trackedEntities = this.getEntities(path);
  3755. if (trackedEntities.has(entity))
  3756. return true;
  3757. trackedEntities.add(entity);
  3758. return false;
  3759. }
  3760. withTrackedEntityAtPath(path, entity, onUntracked, returnIfTracked) {
  3761. const trackedEntities = this.getEntities(path);
  3762. if (trackedEntities.has(entity))
  3763. return returnIfTracked;
  3764. trackedEntities.add(entity);
  3765. const result = onUntracked();
  3766. trackedEntities.delete(entity);
  3767. return result;
  3768. }
  3769. getEntities(path) {
  3770. let currentPaths = this.entityPaths;
  3771. for (const pathSegment of path) {
  3772. currentPaths = currentPaths[pathSegment] =
  3773. currentPaths[pathSegment] ||
  3774. Object.create(null, { [EntitiesKey]: { value: new Set() } });
  3775. }
  3776. return currentPaths[EntitiesKey];
  3777. }
  3778. }
  3779. const SHARED_RECURSION_TRACKER = new PathTracker();
  3780. class DiscriminatedPathTracker {
  3781. constructor() {
  3782. this.entityPaths = Object.create(null, {
  3783. [EntitiesKey]: { value: new Map() }
  3784. });
  3785. }
  3786. trackEntityAtPathAndGetIfTracked(path, discriminator, entity) {
  3787. let currentPaths = this.entityPaths;
  3788. for (const pathSegment of path) {
  3789. currentPaths = currentPaths[pathSegment] =
  3790. currentPaths[pathSegment] ||
  3791. Object.create(null, { [EntitiesKey]: { value: new Map() } });
  3792. }
  3793. const trackedEntities = getOrCreate(currentPaths[EntitiesKey], discriminator, (getNewSet));
  3794. if (trackedEntities.has(entity))
  3795. return true;
  3796. trackedEntities.add(entity);
  3797. return false;
  3798. }
  3799. }
  3800. const UnknownValue = Symbol('Unknown Value');
  3801. const UnknownTruthyValue = Symbol('Unknown Truthy Value');
  3802. class ExpressionEntity {
  3803. constructor() {
  3804. this.included = false;
  3805. }
  3806. deoptimizeArgumentsOnInteractionAtPath(interaction, _path, _recursionTracker) {
  3807. deoptimizeInteraction(interaction);
  3808. }
  3809. deoptimizePath(_path) { }
  3810. /**
  3811. * If possible it returns a stringifyable literal value for this node that
  3812. * can be used for inlining or comparing values. Otherwise, it should return
  3813. * UnknownValue.
  3814. */
  3815. getLiteralValueAtPath(_path, _recursionTracker, _origin) {
  3816. return UnknownValue;
  3817. }
  3818. getReturnExpressionWhenCalledAtPath(_path, _interaction, _recursionTracker, _origin) {
  3819. return UNKNOWN_RETURN_EXPRESSION;
  3820. }
  3821. hasEffectsOnInteractionAtPath(_path, _interaction, _context) {
  3822. return true;
  3823. }
  3824. include(_context, _includeChildrenRecursively, _options) {
  3825. this.included = true;
  3826. }
  3827. includeCallArguments(context, parameters) {
  3828. for (const argument of parameters) {
  3829. argument.include(context, false);
  3830. }
  3831. }
  3832. shouldBeIncluded(_context) {
  3833. return true;
  3834. }
  3835. }
  3836. const UNKNOWN_EXPRESSION = new (class UnknownExpression extends ExpressionEntity {
  3837. })();
  3838. const UNKNOWN_RETURN_EXPRESSION = [
  3839. UNKNOWN_EXPRESSION,
  3840. false
  3841. ];
  3842. const deoptimizeInteraction = (interaction) => {
  3843. for (const argument of interaction.args) {
  3844. argument?.deoptimizePath(UNKNOWN_PATH);
  3845. }
  3846. };
  3847. const INTERACTION_ACCESSED = 0;
  3848. const INTERACTION_ASSIGNED = 1;
  3849. const INTERACTION_CALLED = 2;
  3850. const NODE_INTERACTION_UNKNOWN_ACCESS = {
  3851. args: [null],
  3852. type: INTERACTION_ACCESSED
  3853. };
  3854. const NODE_INTERACTION_UNKNOWN_ASSIGNMENT = {
  3855. args: [null, UNKNOWN_EXPRESSION],
  3856. type: INTERACTION_ASSIGNED
  3857. };
  3858. // While this is technically a call without arguments, we can compare against
  3859. // this reference in places where precise values or this argument would make a
  3860. // difference
  3861. const NODE_INTERACTION_UNKNOWN_CALL = {
  3862. args: [null],
  3863. type: INTERACTION_CALLED,
  3864. withNew: false
  3865. };
  3866. class Variable extends ExpressionEntity {
  3867. constructor(name) {
  3868. super();
  3869. this.name = name;
  3870. this.alwaysRendered = false;
  3871. this.forbiddenNames = null;
  3872. this.initReached = false;
  3873. this.isId = false;
  3874. this.isReassigned = false;
  3875. this.kind = null;
  3876. this.renderBaseName = null;
  3877. this.renderName = null;
  3878. }
  3879. /**
  3880. * Binds identifiers that reference this variable to this variable.
  3881. * Necessary to be able to change variable names.
  3882. */
  3883. addReference(_identifier) { }
  3884. /**
  3885. * Prevent this variable from being renamed to this name to avoid name
  3886. * collisions
  3887. */
  3888. forbidName(name) {
  3889. (this.forbiddenNames || (this.forbiddenNames = new Set())).add(name);
  3890. }
  3891. getBaseVariableName() {
  3892. return this.renderBaseName || this.renderName || this.name;
  3893. }
  3894. getName(getPropertyAccess, useOriginalName) {
  3895. if (useOriginalName?.(this)) {
  3896. return this.name;
  3897. }
  3898. const name = this.renderName || this.name;
  3899. return this.renderBaseName ? `${this.renderBaseName}${getPropertyAccess(name)}` : name;
  3900. }
  3901. hasEffectsOnInteractionAtPath(path, { type }, _context) {
  3902. return type !== INTERACTION_ACCESSED || path.length > 0;
  3903. }
  3904. /**
  3905. * Marks this variable as being part of the bundle, which is usually the case when one of
  3906. * its identifiers becomes part of the bundle. Returns true if it has not been included
  3907. * previously.
  3908. * Once a variable is included, it should take care all its declarations are included.
  3909. */
  3910. include() {
  3911. this.included = true;
  3912. }
  3913. markCalledFromTryStatement() { }
  3914. setRenderNames(baseName, name) {
  3915. this.renderBaseName = baseName;
  3916. this.renderName = name;
  3917. }
  3918. }
  3919. class ExternalVariable extends Variable {
  3920. constructor(module, name) {
  3921. super(name);
  3922. this.referenced = false;
  3923. this.module = module;
  3924. this.isNamespace = name === '*';
  3925. }
  3926. addReference(identifier) {
  3927. this.referenced = true;
  3928. if (this.name === 'default' || this.name === '*') {
  3929. this.module.suggestName(identifier.name);
  3930. }
  3931. }
  3932. hasEffectsOnInteractionAtPath(path, { type }) {
  3933. return type !== INTERACTION_ACCESSED || path.length > (this.isNamespace ? 1 : 0);
  3934. }
  3935. include() {
  3936. if (!this.included) {
  3937. this.included = true;
  3938. this.module.used = true;
  3939. }
  3940. }
  3941. }
  3942. const RESERVED_NAMES = new Set([
  3943. 'await',
  3944. 'break',
  3945. 'case',
  3946. 'catch',
  3947. 'class',
  3948. 'const',
  3949. 'continue',
  3950. 'debugger',
  3951. 'default',
  3952. 'delete',
  3953. 'do',
  3954. 'else',
  3955. 'enum',
  3956. 'eval',
  3957. 'export',
  3958. 'extends',
  3959. 'false',
  3960. 'finally',
  3961. 'for',
  3962. 'function',
  3963. 'if',
  3964. 'implements',
  3965. 'import',
  3966. 'in',
  3967. 'instanceof',
  3968. 'interface',
  3969. 'let',
  3970. 'NaN',
  3971. 'new',
  3972. 'null',
  3973. 'package',
  3974. 'private',
  3975. 'protected',
  3976. 'public',
  3977. 'return',
  3978. 'static',
  3979. 'super',
  3980. 'switch',
  3981. 'this',
  3982. 'throw',
  3983. 'true',
  3984. 'try',
  3985. 'typeof',
  3986. 'undefined',
  3987. 'var',
  3988. 'void',
  3989. 'while',
  3990. 'with',
  3991. 'yield'
  3992. ]);
  3993. const RESERVED_NAMES$1 = RESERVED_NAMES;
  3994. const illegalCharacters = /[^\w$]/g;
  3995. const startsWithDigit = (value) => /\d/.test(value[0]);
  3996. const needsEscape = (value) => startsWithDigit(value) || RESERVED_NAMES$1.has(value) || value === 'arguments';
  3997. function isLegal(value) {
  3998. if (needsEscape(value)) {
  3999. return false;
  4000. }
  4001. return !illegalCharacters.test(value);
  4002. }
  4003. function makeLegal(value) {
  4004. value = value
  4005. .replace(/-(\w)/g, (_, letter) => letter.toUpperCase())
  4006. .replace(illegalCharacters, '_');
  4007. if (needsEscape(value))
  4008. value = `_${value}`;
  4009. return value || '_';
  4010. }
  4011. class ExternalModule {
  4012. constructor(options, id, moduleSideEffects, meta, renormalizeRenderPath, assertions) {
  4013. this.options = options;
  4014. this.id = id;
  4015. this.renormalizeRenderPath = renormalizeRenderPath;
  4016. this.dynamicImporters = [];
  4017. this.execIndex = Infinity;
  4018. this.exportedVariables = new Map();
  4019. this.importers = [];
  4020. this.reexported = false;
  4021. this.used = false;
  4022. this.declarations = new Map();
  4023. this.mostCommonSuggestion = 0;
  4024. this.nameSuggestions = new Map();
  4025. this.suggestedVariableName = makeLegal(id.split(/[/\\]/).pop());
  4026. const { importers, dynamicImporters } = this;
  4027. const info = (this.info = {
  4028. assertions,
  4029. ast: null,
  4030. code: null,
  4031. dynamicallyImportedIdResolutions: EMPTY_ARRAY,
  4032. dynamicallyImportedIds: EMPTY_ARRAY,
  4033. get dynamicImporters() {
  4034. return dynamicImporters.sort();
  4035. },
  4036. exportedBindings: null,
  4037. exports: null,
  4038. hasDefaultExport: null,
  4039. get hasModuleSideEffects() {
  4040. warnDeprecation('Accessing ModuleInfo.hasModuleSideEffects from plugins is deprecated. Please use ModuleInfo.moduleSideEffects instead.', URL_THIS_GETMODULEINFO, true, options);
  4041. return info.moduleSideEffects;
  4042. },
  4043. id,
  4044. implicitlyLoadedAfterOneOf: EMPTY_ARRAY,
  4045. implicitlyLoadedBefore: EMPTY_ARRAY,
  4046. importedIdResolutions: EMPTY_ARRAY,
  4047. importedIds: EMPTY_ARRAY,
  4048. get importers() {
  4049. return importers.sort();
  4050. },
  4051. isEntry: false,
  4052. isExternal: true,
  4053. isIncluded: null,
  4054. meta,
  4055. moduleSideEffects,
  4056. syntheticNamedExports: false
  4057. });
  4058. // Hide the deprecated key so that it only warns when accessed explicitly
  4059. Object.defineProperty(this.info, 'hasModuleSideEffects', {
  4060. enumerable: false
  4061. });
  4062. }
  4063. getVariableForExportName(name) {
  4064. const declaration = this.declarations.get(name);
  4065. if (declaration)
  4066. return [declaration];
  4067. const externalVariable = new ExternalVariable(this, name);
  4068. this.declarations.set(name, externalVariable);
  4069. this.exportedVariables.set(externalVariable, name);
  4070. return [externalVariable];
  4071. }
  4072. suggestName(name) {
  4073. const value = (this.nameSuggestions.get(name) ?? 0) + 1;
  4074. this.nameSuggestions.set(name, value);
  4075. if (value > this.mostCommonSuggestion) {
  4076. this.mostCommonSuggestion = value;
  4077. this.suggestedVariableName = name;
  4078. }
  4079. }
  4080. warnUnusedImports() {
  4081. const unused = [...this.declarations]
  4082. .filter(([name, declaration]) => name !== '*' && !declaration.included && !this.reexported && !declaration.referenced)
  4083. .map(([name]) => name);
  4084. if (unused.length === 0)
  4085. return;
  4086. const importersSet = new Set();
  4087. for (const name of unused) {
  4088. for (const importer of this.declarations.get(name).module.importers) {
  4089. importersSet.add(importer);
  4090. }
  4091. }
  4092. const importersArray = [...importersSet];
  4093. this.options.onLog(LOGLEVEL_WARN, logUnusedExternalImports(this.id, unused, importersArray));
  4094. }
  4095. }
  4096. function getDefaultExportFromCjs (x) {
  4097. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  4098. }
  4099. function getAugmentedNamespace(n) {
  4100. if (n.__esModule) return n;
  4101. var f = n.default;
  4102. if (typeof f == "function") {
  4103. var a = function a () {
  4104. if (this instanceof a) {
  4105. return Reflect.construct(f, arguments, this.constructor);
  4106. }
  4107. return f.apply(this, arguments);
  4108. };
  4109. a.prototype = f.prototype;
  4110. } else a = {};
  4111. Object.defineProperty(a, '__esModule', {value: true});
  4112. Object.keys(n).forEach(function (k) {
  4113. var d = Object.getOwnPropertyDescriptor(n, k);
  4114. Object.defineProperty(a, k, d.get ? d : {
  4115. enumerable: true,
  4116. get: function () {
  4117. return n[k];
  4118. }
  4119. });
  4120. });
  4121. return a;
  4122. }
  4123. var utils$3 = {};
  4124. const path$1 = require$$0$1;
  4125. const WIN_SLASH = '\\\\/';
  4126. const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
  4127. /**
  4128. * Posix glob regex
  4129. */
  4130. const DOT_LITERAL = '\\.';
  4131. const PLUS_LITERAL = '\\+';
  4132. const QMARK_LITERAL = '\\?';
  4133. const SLASH_LITERAL = '\\/';
  4134. const ONE_CHAR = '(?=.)';
  4135. const QMARK = '[^/]';
  4136. const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
  4137. const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
  4138. const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
  4139. const NO_DOT = `(?!${DOT_LITERAL})`;
  4140. const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
  4141. const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
  4142. const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
  4143. const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
  4144. const STAR = `${QMARK}*?`;
  4145. const POSIX_CHARS = {
  4146. DOT_LITERAL,
  4147. PLUS_LITERAL,
  4148. QMARK_LITERAL,
  4149. SLASH_LITERAL,
  4150. ONE_CHAR,
  4151. QMARK,
  4152. END_ANCHOR,
  4153. DOTS_SLASH,
  4154. NO_DOT,
  4155. NO_DOTS,
  4156. NO_DOT_SLASH,
  4157. NO_DOTS_SLASH,
  4158. QMARK_NO_DOT,
  4159. STAR,
  4160. START_ANCHOR
  4161. };
  4162. /**
  4163. * Windows glob regex
  4164. */
  4165. const WINDOWS_CHARS = {
  4166. ...POSIX_CHARS,
  4167. SLASH_LITERAL: `[${WIN_SLASH}]`,
  4168. QMARK: WIN_NO_SLASH,
  4169. STAR: `${WIN_NO_SLASH}*?`,
  4170. DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
  4171. NO_DOT: `(?!${DOT_LITERAL})`,
  4172. NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  4173. NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
  4174. NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  4175. QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
  4176. START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
  4177. END_ANCHOR: `(?:[${WIN_SLASH}]|$)`
  4178. };
  4179. /**
  4180. * POSIX Bracket Regex
  4181. */
  4182. const POSIX_REGEX_SOURCE$1 = {
  4183. alnum: 'a-zA-Z0-9',
  4184. alpha: 'a-zA-Z',
  4185. ascii: '\\x00-\\x7F',
  4186. blank: ' \\t',
  4187. cntrl: '\\x00-\\x1F\\x7F',
  4188. digit: '0-9',
  4189. graph: '\\x21-\\x7E',
  4190. lower: 'a-z',
  4191. print: '\\x20-\\x7E ',
  4192. punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
  4193. space: ' \\t\\r\\n\\v\\f',
  4194. upper: 'A-Z',
  4195. word: 'A-Za-z0-9_',
  4196. xdigit: 'A-Fa-f0-9'
  4197. };
  4198. var constants$2 = {
  4199. MAX_LENGTH: 1024 * 64,
  4200. POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1,
  4201. // regular expressions
  4202. REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
  4203. REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
  4204. REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
  4205. REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
  4206. REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
  4207. REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
  4208. // Replace globs with equivalent patterns to reduce parsing time.
  4209. REPLACEMENTS: {
  4210. '***': '*',
  4211. '**/**': '**',
  4212. '**/**/**': '**'
  4213. },
  4214. // Digits
  4215. CHAR_0: 48, /* 0 */
  4216. CHAR_9: 57, /* 9 */
  4217. // Alphabet chars.
  4218. CHAR_UPPERCASE_A: 65, /* A */
  4219. CHAR_LOWERCASE_A: 97, /* a */
  4220. CHAR_UPPERCASE_Z: 90, /* Z */
  4221. CHAR_LOWERCASE_Z: 122, /* z */
  4222. CHAR_LEFT_PARENTHESES: 40, /* ( */
  4223. CHAR_RIGHT_PARENTHESES: 41, /* ) */
  4224. CHAR_ASTERISK: 42, /* * */
  4225. // Non-alphabetic chars.
  4226. CHAR_AMPERSAND: 38, /* & */
  4227. CHAR_AT: 64, /* @ */
  4228. CHAR_BACKWARD_SLASH: 92, /* \ */
  4229. CHAR_CARRIAGE_RETURN: 13, /* \r */
  4230. CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */
  4231. CHAR_COLON: 58, /* : */
  4232. CHAR_COMMA: 44, /* , */
  4233. CHAR_DOT: 46, /* . */
  4234. CHAR_DOUBLE_QUOTE: 34, /* " */
  4235. CHAR_EQUAL: 61, /* = */
  4236. CHAR_EXCLAMATION_MARK: 33, /* ! */
  4237. CHAR_FORM_FEED: 12, /* \f */
  4238. CHAR_FORWARD_SLASH: 47, /* / */
  4239. CHAR_GRAVE_ACCENT: 96, /* ` */
  4240. CHAR_HASH: 35, /* # */
  4241. CHAR_HYPHEN_MINUS: 45, /* - */
  4242. CHAR_LEFT_ANGLE_BRACKET: 60, /* < */
  4243. CHAR_LEFT_CURLY_BRACE: 123, /* { */
  4244. CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */
  4245. CHAR_LINE_FEED: 10, /* \n */
  4246. CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
  4247. CHAR_PERCENT: 37, /* % */
  4248. CHAR_PLUS: 43, /* + */
  4249. CHAR_QUESTION_MARK: 63, /* ? */
  4250. CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */
  4251. CHAR_RIGHT_CURLY_BRACE: 125, /* } */
  4252. CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */
  4253. CHAR_SEMICOLON: 59, /* ; */
  4254. CHAR_SINGLE_QUOTE: 39, /* ' */
  4255. CHAR_SPACE: 32, /* */
  4256. CHAR_TAB: 9, /* \t */
  4257. CHAR_UNDERSCORE: 95, /* _ */
  4258. CHAR_VERTICAL_LINE: 124, /* | */
  4259. CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
  4260. SEP: path$1.sep,
  4261. /**
  4262. * Create EXTGLOB_CHARS
  4263. */
  4264. extglobChars(chars) {
  4265. return {
  4266. '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
  4267. '?': { type: 'qmark', open: '(?:', close: ')?' },
  4268. '+': { type: 'plus', open: '(?:', close: ')+' },
  4269. '*': { type: 'star', open: '(?:', close: ')*' },
  4270. '@': { type: 'at', open: '(?:', close: ')' }
  4271. };
  4272. },
  4273. /**
  4274. * Create GLOB_CHARS
  4275. */
  4276. globChars(win32) {
  4277. return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
  4278. }
  4279. };
  4280. (function (exports) {
  4281. const path = require$$0$1;
  4282. const win32 = process.platform === 'win32';
  4283. const {
  4284. REGEX_BACKSLASH,
  4285. REGEX_REMOVE_BACKSLASH,
  4286. REGEX_SPECIAL_CHARS,
  4287. REGEX_SPECIAL_CHARS_GLOBAL
  4288. } = constants$2;
  4289. exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  4290. exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
  4291. exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
  4292. exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
  4293. exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
  4294. exports.removeBackslashes = str => {
  4295. return str.replace(REGEX_REMOVE_BACKSLASH, match => {
  4296. return match === '\\' ? '' : match;
  4297. });
  4298. };
  4299. exports.supportsLookbehinds = () => {
  4300. const segs = process.version.slice(1).split('.').map(Number);
  4301. if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) {
  4302. return true;
  4303. }
  4304. return false;
  4305. };
  4306. exports.isWindows = options => {
  4307. if (options && typeof options.windows === 'boolean') {
  4308. return options.windows;
  4309. }
  4310. return win32 === true || path.sep === '\\';
  4311. };
  4312. exports.escapeLast = (input, char, lastIdx) => {
  4313. const idx = input.lastIndexOf(char, lastIdx);
  4314. if (idx === -1) return input;
  4315. if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
  4316. return `${input.slice(0, idx)}\\${input.slice(idx)}`;
  4317. };
  4318. exports.removePrefix = (input, state = {}) => {
  4319. let output = input;
  4320. if (output.startsWith('./')) {
  4321. output = output.slice(2);
  4322. state.prefix = './';
  4323. }
  4324. return output;
  4325. };
  4326. exports.wrapOutput = (input, state = {}, options = {}) => {
  4327. const prepend = options.contains ? '' : '^';
  4328. const append = options.contains ? '' : '$';
  4329. let output = `${prepend}(?:${input})${append}`;
  4330. if (state.negated === true) {
  4331. output = `(?:^(?!${output}).*$)`;
  4332. }
  4333. return output;
  4334. };
  4335. } (utils$3));
  4336. const utils$2 = utils$3;
  4337. const {
  4338. CHAR_ASTERISK, /* * */
  4339. CHAR_AT, /* @ */
  4340. CHAR_BACKWARD_SLASH, /* \ */
  4341. CHAR_COMMA, /* , */
  4342. CHAR_DOT, /* . */
  4343. CHAR_EXCLAMATION_MARK, /* ! */
  4344. CHAR_FORWARD_SLASH, /* / */
  4345. CHAR_LEFT_CURLY_BRACE, /* { */
  4346. CHAR_LEFT_PARENTHESES, /* ( */
  4347. CHAR_LEFT_SQUARE_BRACKET, /* [ */
  4348. CHAR_PLUS, /* + */
  4349. CHAR_QUESTION_MARK, /* ? */
  4350. CHAR_RIGHT_CURLY_BRACE, /* } */
  4351. CHAR_RIGHT_PARENTHESES, /* ) */
  4352. CHAR_RIGHT_SQUARE_BRACKET /* ] */
  4353. } = constants$2;
  4354. const isPathSeparator = code => {
  4355. return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
  4356. };
  4357. const depth = token => {
  4358. if (token.isPrefix !== true) {
  4359. token.depth = token.isGlobstar ? Infinity : 1;
  4360. }
  4361. };
  4362. /**
  4363. * Quickly scans a glob pattern and returns an object with a handful of
  4364. * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
  4365. * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
  4366. * with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
  4367. *
  4368. * ```js
  4369. * const pm = require('picomatch');
  4370. * console.log(pm.scan('foo/bar/*.js'));
  4371. * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
  4372. * ```
  4373. * @param {String} `str`
  4374. * @param {Object} `options`
  4375. * @return {Object} Returns an object with tokens and regex source string.
  4376. * @api public
  4377. */
  4378. const scan$1 = (input, options) => {
  4379. const opts = options || {};
  4380. const length = input.length - 1;
  4381. const scanToEnd = opts.parts === true || opts.scanToEnd === true;
  4382. const slashes = [];
  4383. const tokens = [];
  4384. const parts = [];
  4385. let str = input;
  4386. let index = -1;
  4387. let start = 0;
  4388. let lastIndex = 0;
  4389. let isBrace = false;
  4390. let isBracket = false;
  4391. let isGlob = false;
  4392. let isExtglob = false;
  4393. let isGlobstar = false;
  4394. let braceEscaped = false;
  4395. let backslashes = false;
  4396. let negated = false;
  4397. let negatedExtglob = false;
  4398. let finished = false;
  4399. let braces = 0;
  4400. let prev;
  4401. let code;
  4402. let token = { value: '', depth: 0, isGlob: false };
  4403. const eos = () => index >= length;
  4404. const peek = () => str.charCodeAt(index + 1);
  4405. const advance = () => {
  4406. prev = code;
  4407. return str.charCodeAt(++index);
  4408. };
  4409. while (index < length) {
  4410. code = advance();
  4411. let next;
  4412. if (code === CHAR_BACKWARD_SLASH) {
  4413. backslashes = token.backslashes = true;
  4414. code = advance();
  4415. if (code === CHAR_LEFT_CURLY_BRACE) {
  4416. braceEscaped = true;
  4417. }
  4418. continue;
  4419. }
  4420. if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
  4421. braces++;
  4422. while (eos() !== true && (code = advance())) {
  4423. if (code === CHAR_BACKWARD_SLASH) {
  4424. backslashes = token.backslashes = true;
  4425. advance();
  4426. continue;
  4427. }
  4428. if (code === CHAR_LEFT_CURLY_BRACE) {
  4429. braces++;
  4430. continue;
  4431. }
  4432. if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
  4433. isBrace = token.isBrace = true;
  4434. isGlob = token.isGlob = true;
  4435. finished = true;
  4436. if (scanToEnd === true) {
  4437. continue;
  4438. }
  4439. break;
  4440. }
  4441. if (braceEscaped !== true && code === CHAR_COMMA) {
  4442. isBrace = token.isBrace = true;
  4443. isGlob = token.isGlob = true;
  4444. finished = true;
  4445. if (scanToEnd === true) {
  4446. continue;
  4447. }
  4448. break;
  4449. }
  4450. if (code === CHAR_RIGHT_CURLY_BRACE) {
  4451. braces--;
  4452. if (braces === 0) {
  4453. braceEscaped = false;
  4454. isBrace = token.isBrace = true;
  4455. finished = true;
  4456. break;
  4457. }
  4458. }
  4459. }
  4460. if (scanToEnd === true) {
  4461. continue;
  4462. }
  4463. break;
  4464. }
  4465. if (code === CHAR_FORWARD_SLASH) {
  4466. slashes.push(index);
  4467. tokens.push(token);
  4468. token = { value: '', depth: 0, isGlob: false };
  4469. if (finished === true) continue;
  4470. if (prev === CHAR_DOT && index === (start + 1)) {
  4471. start += 2;
  4472. continue;
  4473. }
  4474. lastIndex = index + 1;
  4475. continue;
  4476. }
  4477. if (opts.noext !== true) {
  4478. const isExtglobChar = code === CHAR_PLUS
  4479. || code === CHAR_AT
  4480. || code === CHAR_ASTERISK
  4481. || code === CHAR_QUESTION_MARK
  4482. || code === CHAR_EXCLAMATION_MARK;
  4483. if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
  4484. isGlob = token.isGlob = true;
  4485. isExtglob = token.isExtglob = true;
  4486. finished = true;
  4487. if (code === CHAR_EXCLAMATION_MARK && index === start) {
  4488. negatedExtglob = true;
  4489. }
  4490. if (scanToEnd === true) {
  4491. while (eos() !== true && (code = advance())) {
  4492. if (code === CHAR_BACKWARD_SLASH) {
  4493. backslashes = token.backslashes = true;
  4494. code = advance();
  4495. continue;
  4496. }
  4497. if (code === CHAR_RIGHT_PARENTHESES) {
  4498. isGlob = token.isGlob = true;
  4499. finished = true;
  4500. break;
  4501. }
  4502. }
  4503. continue;
  4504. }
  4505. break;
  4506. }
  4507. }
  4508. if (code === CHAR_ASTERISK) {
  4509. if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
  4510. isGlob = token.isGlob = true;
  4511. finished = true;
  4512. if (scanToEnd === true) {
  4513. continue;
  4514. }
  4515. break;
  4516. }
  4517. if (code === CHAR_QUESTION_MARK) {
  4518. isGlob = token.isGlob = true;
  4519. finished = true;
  4520. if (scanToEnd === true) {
  4521. continue;
  4522. }
  4523. break;
  4524. }
  4525. if (code === CHAR_LEFT_SQUARE_BRACKET) {
  4526. while (eos() !== true && (next = advance())) {
  4527. if (next === CHAR_BACKWARD_SLASH) {
  4528. backslashes = token.backslashes = true;
  4529. advance();
  4530. continue;
  4531. }
  4532. if (next === CHAR_RIGHT_SQUARE_BRACKET) {
  4533. isBracket = token.isBracket = true;
  4534. isGlob = token.isGlob = true;
  4535. finished = true;
  4536. break;
  4537. }
  4538. }
  4539. if (scanToEnd === true) {
  4540. continue;
  4541. }
  4542. break;
  4543. }
  4544. if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
  4545. negated = token.negated = true;
  4546. start++;
  4547. continue;
  4548. }
  4549. if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
  4550. isGlob = token.isGlob = true;
  4551. if (scanToEnd === true) {
  4552. while (eos() !== true && (code = advance())) {
  4553. if (code === CHAR_LEFT_PARENTHESES) {
  4554. backslashes = token.backslashes = true;
  4555. code = advance();
  4556. continue;
  4557. }
  4558. if (code === CHAR_RIGHT_PARENTHESES) {
  4559. finished = true;
  4560. break;
  4561. }
  4562. }
  4563. continue;
  4564. }
  4565. break;
  4566. }
  4567. if (isGlob === true) {
  4568. finished = true;
  4569. if (scanToEnd === true) {
  4570. continue;
  4571. }
  4572. break;
  4573. }
  4574. }
  4575. if (opts.noext === true) {
  4576. isExtglob = false;
  4577. isGlob = false;
  4578. }
  4579. let base = str;
  4580. let prefix = '';
  4581. let glob = '';
  4582. if (start > 0) {
  4583. prefix = str.slice(0, start);
  4584. str = str.slice(start);
  4585. lastIndex -= start;
  4586. }
  4587. if (base && isGlob === true && lastIndex > 0) {
  4588. base = str.slice(0, lastIndex);
  4589. glob = str.slice(lastIndex);
  4590. } else if (isGlob === true) {
  4591. base = '';
  4592. glob = str;
  4593. } else {
  4594. base = str;
  4595. }
  4596. if (base && base !== '' && base !== '/' && base !== str) {
  4597. if (isPathSeparator(base.charCodeAt(base.length - 1))) {
  4598. base = base.slice(0, -1);
  4599. }
  4600. }
  4601. if (opts.unescape === true) {
  4602. if (glob) glob = utils$2.removeBackslashes(glob);
  4603. if (base && backslashes === true) {
  4604. base = utils$2.removeBackslashes(base);
  4605. }
  4606. }
  4607. const state = {
  4608. prefix,
  4609. input,
  4610. start,
  4611. base,
  4612. glob,
  4613. isBrace,
  4614. isBracket,
  4615. isGlob,
  4616. isExtglob,
  4617. isGlobstar,
  4618. negated,
  4619. negatedExtglob
  4620. };
  4621. if (opts.tokens === true) {
  4622. state.maxDepth = 0;
  4623. if (!isPathSeparator(code)) {
  4624. tokens.push(token);
  4625. }
  4626. state.tokens = tokens;
  4627. }
  4628. if (opts.parts === true || opts.tokens === true) {
  4629. let prevIndex;
  4630. for (let idx = 0; idx < slashes.length; idx++) {
  4631. const n = prevIndex ? prevIndex + 1 : start;
  4632. const i = slashes[idx];
  4633. const value = input.slice(n, i);
  4634. if (opts.tokens) {
  4635. if (idx === 0 && start !== 0) {
  4636. tokens[idx].isPrefix = true;
  4637. tokens[idx].value = prefix;
  4638. } else {
  4639. tokens[idx].value = value;
  4640. }
  4641. depth(tokens[idx]);
  4642. state.maxDepth += tokens[idx].depth;
  4643. }
  4644. if (idx !== 0 || value !== '') {
  4645. parts.push(value);
  4646. }
  4647. prevIndex = i;
  4648. }
  4649. if (prevIndex && prevIndex + 1 < input.length) {
  4650. const value = input.slice(prevIndex + 1);
  4651. parts.push(value);
  4652. if (opts.tokens) {
  4653. tokens[tokens.length - 1].value = value;
  4654. depth(tokens[tokens.length - 1]);
  4655. state.maxDepth += tokens[tokens.length - 1].depth;
  4656. }
  4657. }
  4658. state.slashes = slashes;
  4659. state.parts = parts;
  4660. }
  4661. return state;
  4662. };
  4663. var scan_1 = scan$1;
  4664. const constants$1 = constants$2;
  4665. const utils$1 = utils$3;
  4666. /**
  4667. * Constants
  4668. */
  4669. const {
  4670. MAX_LENGTH,
  4671. POSIX_REGEX_SOURCE,
  4672. REGEX_NON_SPECIAL_CHARS,
  4673. REGEX_SPECIAL_CHARS_BACKREF,
  4674. REPLACEMENTS
  4675. } = constants$1;
  4676. /**
  4677. * Helpers
  4678. */
  4679. const expandRange = (args, options) => {
  4680. if (typeof options.expandRange === 'function') {
  4681. return options.expandRange(...args, options);
  4682. }
  4683. args.sort();
  4684. const value = `[${args.join('-')}]`;
  4685. return value;
  4686. };
  4687. /**
  4688. * Create the message for a syntax error
  4689. */
  4690. const syntaxError = (type, char) => {
  4691. return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
  4692. };
  4693. /**
  4694. * Parse the given input string.
  4695. * @param {String} input
  4696. * @param {Object} options
  4697. * @return {Object}
  4698. */
  4699. const parse$2 = (input, options) => {
  4700. if (typeof input !== 'string') {
  4701. throw new TypeError('Expected a string');
  4702. }
  4703. input = REPLACEMENTS[input] || input;
  4704. const opts = { ...options };
  4705. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  4706. let len = input.length;
  4707. if (len > max) {
  4708. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  4709. }
  4710. const bos = { type: 'bos', value: '', output: opts.prepend || '' };
  4711. const tokens = [bos];
  4712. const capture = opts.capture ? '' : '?:';
  4713. const win32 = utils$1.isWindows(options);
  4714. // create constants based on platform, for windows or posix
  4715. const PLATFORM_CHARS = constants$1.globChars(win32);
  4716. const EXTGLOB_CHARS = constants$1.extglobChars(PLATFORM_CHARS);
  4717. const {
  4718. DOT_LITERAL,
  4719. PLUS_LITERAL,
  4720. SLASH_LITERAL,
  4721. ONE_CHAR,
  4722. DOTS_SLASH,
  4723. NO_DOT,
  4724. NO_DOT_SLASH,
  4725. NO_DOTS_SLASH,
  4726. QMARK,
  4727. QMARK_NO_DOT,
  4728. STAR,
  4729. START_ANCHOR
  4730. } = PLATFORM_CHARS;
  4731. const globstar = opts => {
  4732. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  4733. };
  4734. const nodot = opts.dot ? '' : NO_DOT;
  4735. const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
  4736. let star = opts.bash === true ? globstar(opts) : STAR;
  4737. if (opts.capture) {
  4738. star = `(${star})`;
  4739. }
  4740. // minimatch options support
  4741. if (typeof opts.noext === 'boolean') {
  4742. opts.noextglob = opts.noext;
  4743. }
  4744. const state = {
  4745. input,
  4746. index: -1,
  4747. start: 0,
  4748. dot: opts.dot === true,
  4749. consumed: '',
  4750. output: '',
  4751. prefix: '',
  4752. backtrack: false,
  4753. negated: false,
  4754. brackets: 0,
  4755. braces: 0,
  4756. parens: 0,
  4757. quotes: 0,
  4758. globstar: false,
  4759. tokens
  4760. };
  4761. input = utils$1.removePrefix(input, state);
  4762. len = input.length;
  4763. const extglobs = [];
  4764. const braces = [];
  4765. const stack = [];
  4766. let prev = bos;
  4767. let value;
  4768. /**
  4769. * Tokenizing helpers
  4770. */
  4771. const eos = () => state.index === len - 1;
  4772. const peek = state.peek = (n = 1) => input[state.index + n];
  4773. const advance = state.advance = () => input[++state.index] || '';
  4774. const remaining = () => input.slice(state.index + 1);
  4775. const consume = (value = '', num = 0) => {
  4776. state.consumed += value;
  4777. state.index += num;
  4778. };
  4779. const append = token => {
  4780. state.output += token.output != null ? token.output : token.value;
  4781. consume(token.value);
  4782. };
  4783. const negate = () => {
  4784. let count = 1;
  4785. while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
  4786. advance();
  4787. state.start++;
  4788. count++;
  4789. }
  4790. if (count % 2 === 0) {
  4791. return false;
  4792. }
  4793. state.negated = true;
  4794. state.start++;
  4795. return true;
  4796. };
  4797. const increment = type => {
  4798. state[type]++;
  4799. stack.push(type);
  4800. };
  4801. const decrement = type => {
  4802. state[type]--;
  4803. stack.pop();
  4804. };
  4805. /**
  4806. * Push tokens onto the tokens array. This helper speeds up
  4807. * tokenizing by 1) helping us avoid backtracking as much as possible,
  4808. * and 2) helping us avoid creating extra tokens when consecutive
  4809. * characters are plain text. This improves performance and simplifies
  4810. * lookbehinds.
  4811. */
  4812. const push = tok => {
  4813. if (prev.type === 'globstar') {
  4814. const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
  4815. const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));
  4816. if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
  4817. state.output = state.output.slice(0, -prev.output.length);
  4818. prev.type = 'star';
  4819. prev.value = '*';
  4820. prev.output = star;
  4821. state.output += prev.output;
  4822. }
  4823. }
  4824. if (extglobs.length && tok.type !== 'paren') {
  4825. extglobs[extglobs.length - 1].inner += tok.value;
  4826. }
  4827. if (tok.value || tok.output) append(tok);
  4828. if (prev && prev.type === 'text' && tok.type === 'text') {
  4829. prev.value += tok.value;
  4830. prev.output = (prev.output || '') + tok.value;
  4831. return;
  4832. }
  4833. tok.prev = prev;
  4834. tokens.push(tok);
  4835. prev = tok;
  4836. };
  4837. const extglobOpen = (type, value) => {
  4838. const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };
  4839. token.prev = prev;
  4840. token.parens = state.parens;
  4841. token.output = state.output;
  4842. const output = (opts.capture ? '(' : '') + token.open;
  4843. increment('parens');
  4844. push({ type, value, output: state.output ? '' : ONE_CHAR });
  4845. push({ type: 'paren', extglob: true, value: advance(), output });
  4846. extglobs.push(token);
  4847. };
  4848. const extglobClose = token => {
  4849. let output = token.close + (opts.capture ? ')' : '');
  4850. let rest;
  4851. if (token.type === 'negate') {
  4852. let extglobStar = star;
  4853. if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
  4854. extglobStar = globstar(opts);
  4855. }
  4856. if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
  4857. output = token.close = `)$))${extglobStar}`;
  4858. }
  4859. if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
  4860. // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis.
  4861. // In this case, we need to parse the string and use it in the output of the original pattern.
  4862. // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`.
  4863. //
  4864. // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`.
  4865. const expression = parse$2(rest, { ...options, fastpaths: false }).output;
  4866. output = token.close = `)${expression})${extglobStar})`;
  4867. }
  4868. if (token.prev.type === 'bos') {
  4869. state.negatedExtglob = true;
  4870. }
  4871. }
  4872. push({ type: 'paren', extglob: true, value, output });
  4873. decrement('parens');
  4874. };
  4875. /**
  4876. * Fast paths
  4877. */
  4878. if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
  4879. let backslashes = false;
  4880. let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
  4881. if (first === '\\') {
  4882. backslashes = true;
  4883. return m;
  4884. }
  4885. if (first === '?') {
  4886. if (esc) {
  4887. return esc + first + (rest ? QMARK.repeat(rest.length) : '');
  4888. }
  4889. if (index === 0) {
  4890. return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
  4891. }
  4892. return QMARK.repeat(chars.length);
  4893. }
  4894. if (first === '.') {
  4895. return DOT_LITERAL.repeat(chars.length);
  4896. }
  4897. if (first === '*') {
  4898. if (esc) {
  4899. return esc + first + (rest ? star : '');
  4900. }
  4901. return star;
  4902. }
  4903. return esc ? m : `\\${m}`;
  4904. });
  4905. if (backslashes === true) {
  4906. if (opts.unescape === true) {
  4907. output = output.replace(/\\/g, '');
  4908. } else {
  4909. output = output.replace(/\\+/g, m => {
  4910. return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
  4911. });
  4912. }
  4913. }
  4914. if (output === input && opts.contains === true) {
  4915. state.output = input;
  4916. return state;
  4917. }
  4918. state.output = utils$1.wrapOutput(output, state, options);
  4919. return state;
  4920. }
  4921. /**
  4922. * Tokenize input until we reach end-of-string
  4923. */
  4924. while (!eos()) {
  4925. value = advance();
  4926. if (value === '\u0000') {
  4927. continue;
  4928. }
  4929. /**
  4930. * Escaped characters
  4931. */
  4932. if (value === '\\') {
  4933. const next = peek();
  4934. if (next === '/' && opts.bash !== true) {
  4935. continue;
  4936. }
  4937. if (next === '.' || next === ';') {
  4938. continue;
  4939. }
  4940. if (!next) {
  4941. value += '\\';
  4942. push({ type: 'text', value });
  4943. continue;
  4944. }
  4945. // collapse slashes to reduce potential for exploits
  4946. const match = /^\\+/.exec(remaining());
  4947. let slashes = 0;
  4948. if (match && match[0].length > 2) {
  4949. slashes = match[0].length;
  4950. state.index += slashes;
  4951. if (slashes % 2 !== 0) {
  4952. value += '\\';
  4953. }
  4954. }
  4955. if (opts.unescape === true) {
  4956. value = advance();
  4957. } else {
  4958. value += advance();
  4959. }
  4960. if (state.brackets === 0) {
  4961. push({ type: 'text', value });
  4962. continue;
  4963. }
  4964. }
  4965. /**
  4966. * If we're inside a regex character class, continue
  4967. * until we reach the closing bracket.
  4968. */
  4969. if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
  4970. if (opts.posix !== false && value === ':') {
  4971. const inner = prev.value.slice(1);
  4972. if (inner.includes('[')) {
  4973. prev.posix = true;
  4974. if (inner.includes(':')) {
  4975. const idx = prev.value.lastIndexOf('[');
  4976. const pre = prev.value.slice(0, idx);
  4977. const rest = prev.value.slice(idx + 2);
  4978. const posix = POSIX_REGEX_SOURCE[rest];
  4979. if (posix) {
  4980. prev.value = pre + posix;
  4981. state.backtrack = true;
  4982. advance();
  4983. if (!bos.output && tokens.indexOf(prev) === 1) {
  4984. bos.output = ONE_CHAR;
  4985. }
  4986. continue;
  4987. }
  4988. }
  4989. }
  4990. }
  4991. if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
  4992. value = `\\${value}`;
  4993. }
  4994. if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
  4995. value = `\\${value}`;
  4996. }
  4997. if (opts.posix === true && value === '!' && prev.value === '[') {
  4998. value = '^';
  4999. }
  5000. prev.value += value;
  5001. append({ value });
  5002. continue;
  5003. }
  5004. /**
  5005. * If we're inside a quoted string, continue
  5006. * until we reach the closing double quote.
  5007. */
  5008. if (state.quotes === 1 && value !== '"') {
  5009. value = utils$1.escapeRegex(value);
  5010. prev.value += value;
  5011. append({ value });
  5012. continue;
  5013. }
  5014. /**
  5015. * Double quotes
  5016. */
  5017. if (value === '"') {
  5018. state.quotes = state.quotes === 1 ? 0 : 1;
  5019. if (opts.keepQuotes === true) {
  5020. push({ type: 'text', value });
  5021. }
  5022. continue;
  5023. }
  5024. /**
  5025. * Parentheses
  5026. */
  5027. if (value === '(') {
  5028. increment('parens');
  5029. push({ type: 'paren', value });
  5030. continue;
  5031. }
  5032. if (value === ')') {
  5033. if (state.parens === 0 && opts.strictBrackets === true) {
  5034. throw new SyntaxError(syntaxError('opening', '('));
  5035. }
  5036. const extglob = extglobs[extglobs.length - 1];
  5037. if (extglob && state.parens === extglob.parens + 1) {
  5038. extglobClose(extglobs.pop());
  5039. continue;
  5040. }
  5041. push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
  5042. decrement('parens');
  5043. continue;
  5044. }
  5045. /**
  5046. * Square brackets
  5047. */
  5048. if (value === '[') {
  5049. if (opts.nobracket === true || !remaining().includes(']')) {
  5050. if (opts.nobracket !== true && opts.strictBrackets === true) {
  5051. throw new SyntaxError(syntaxError('closing', ']'));
  5052. }
  5053. value = `\\${value}`;
  5054. } else {
  5055. increment('brackets');
  5056. }
  5057. push({ type: 'bracket', value });
  5058. continue;
  5059. }
  5060. if (value === ']') {
  5061. if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
  5062. push({ type: 'text', value, output: `\\${value}` });
  5063. continue;
  5064. }
  5065. if (state.brackets === 0) {
  5066. if (opts.strictBrackets === true) {
  5067. throw new SyntaxError(syntaxError('opening', '['));
  5068. }
  5069. push({ type: 'text', value, output: `\\${value}` });
  5070. continue;
  5071. }
  5072. decrement('brackets');
  5073. const prevValue = prev.value.slice(1);
  5074. if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
  5075. value = `/${value}`;
  5076. }
  5077. prev.value += value;
  5078. append({ value });
  5079. // when literal brackets are explicitly disabled
  5080. // assume we should match with a regex character class
  5081. if (opts.literalBrackets === false || utils$1.hasRegexChars(prevValue)) {
  5082. continue;
  5083. }
  5084. const escaped = utils$1.escapeRegex(prev.value);
  5085. state.output = state.output.slice(0, -prev.value.length);
  5086. // when literal brackets are explicitly enabled
  5087. // assume we should escape the brackets to match literal characters
  5088. if (opts.literalBrackets === true) {
  5089. state.output += escaped;
  5090. prev.value = escaped;
  5091. continue;
  5092. }
  5093. // when the user specifies nothing, try to match both
  5094. prev.value = `(${capture}${escaped}|${prev.value})`;
  5095. state.output += prev.value;
  5096. continue;
  5097. }
  5098. /**
  5099. * Braces
  5100. */
  5101. if (value === '{' && opts.nobrace !== true) {
  5102. increment('braces');
  5103. const open = {
  5104. type: 'brace',
  5105. value,
  5106. output: '(',
  5107. outputIndex: state.output.length,
  5108. tokensIndex: state.tokens.length
  5109. };
  5110. braces.push(open);
  5111. push(open);
  5112. continue;
  5113. }
  5114. if (value === '}') {
  5115. const brace = braces[braces.length - 1];
  5116. if (opts.nobrace === true || !brace) {
  5117. push({ type: 'text', value, output: value });
  5118. continue;
  5119. }
  5120. let output = ')';
  5121. if (brace.dots === true) {
  5122. const arr = tokens.slice();
  5123. const range = [];
  5124. for (let i = arr.length - 1; i >= 0; i--) {
  5125. tokens.pop();
  5126. if (arr[i].type === 'brace') {
  5127. break;
  5128. }
  5129. if (arr[i].type !== 'dots') {
  5130. range.unshift(arr[i].value);
  5131. }
  5132. }
  5133. output = expandRange(range, opts);
  5134. state.backtrack = true;
  5135. }
  5136. if (brace.comma !== true && brace.dots !== true) {
  5137. const out = state.output.slice(0, brace.outputIndex);
  5138. const toks = state.tokens.slice(brace.tokensIndex);
  5139. brace.value = brace.output = '\\{';
  5140. value = output = '\\}';
  5141. state.output = out;
  5142. for (const t of toks) {
  5143. state.output += (t.output || t.value);
  5144. }
  5145. }
  5146. push({ type: 'brace', value, output });
  5147. decrement('braces');
  5148. braces.pop();
  5149. continue;
  5150. }
  5151. /**
  5152. * Pipes
  5153. */
  5154. if (value === '|') {
  5155. if (extglobs.length > 0) {
  5156. extglobs[extglobs.length - 1].conditions++;
  5157. }
  5158. push({ type: 'text', value });
  5159. continue;
  5160. }
  5161. /**
  5162. * Commas
  5163. */
  5164. if (value === ',') {
  5165. let output = value;
  5166. const brace = braces[braces.length - 1];
  5167. if (brace && stack[stack.length - 1] === 'braces') {
  5168. brace.comma = true;
  5169. output = '|';
  5170. }
  5171. push({ type: 'comma', value, output });
  5172. continue;
  5173. }
  5174. /**
  5175. * Slashes
  5176. */
  5177. if (value === '/') {
  5178. // if the beginning of the glob is "./", advance the start
  5179. // to the current index, and don't add the "./" characters
  5180. // to the state. This greatly simplifies lookbehinds when
  5181. // checking for BOS characters like "!" and "." (not "./")
  5182. if (prev.type === 'dot' && state.index === state.start + 1) {
  5183. state.start = state.index + 1;
  5184. state.consumed = '';
  5185. state.output = '';
  5186. tokens.pop();
  5187. prev = bos; // reset "prev" to the first token
  5188. continue;
  5189. }
  5190. push({ type: 'slash', value, output: SLASH_LITERAL });
  5191. continue;
  5192. }
  5193. /**
  5194. * Dots
  5195. */
  5196. if (value === '.') {
  5197. if (state.braces > 0 && prev.type === 'dot') {
  5198. if (prev.value === '.') prev.output = DOT_LITERAL;
  5199. const brace = braces[braces.length - 1];
  5200. prev.type = 'dots';
  5201. prev.output += value;
  5202. prev.value += value;
  5203. brace.dots = true;
  5204. continue;
  5205. }
  5206. if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
  5207. push({ type: 'text', value, output: DOT_LITERAL });
  5208. continue;
  5209. }
  5210. push({ type: 'dot', value, output: DOT_LITERAL });
  5211. continue;
  5212. }
  5213. /**
  5214. * Question marks
  5215. */
  5216. if (value === '?') {
  5217. const isGroup = prev && prev.value === '(';
  5218. if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  5219. extglobOpen('qmark', value);
  5220. continue;
  5221. }
  5222. if (prev && prev.type === 'paren') {
  5223. const next = peek();
  5224. let output = value;
  5225. if (next === '<' && !utils$1.supportsLookbehinds()) {
  5226. throw new Error('Node.js v10 or higher is required for regex lookbehinds');
  5227. }
  5228. if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {
  5229. output = `\\${value}`;
  5230. }
  5231. push({ type: 'text', value, output });
  5232. continue;
  5233. }
  5234. if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
  5235. push({ type: 'qmark', value, output: QMARK_NO_DOT });
  5236. continue;
  5237. }
  5238. push({ type: 'qmark', value, output: QMARK });
  5239. continue;
  5240. }
  5241. /**
  5242. * Exclamation
  5243. */
  5244. if (value === '!') {
  5245. if (opts.noextglob !== true && peek() === '(') {
  5246. if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
  5247. extglobOpen('negate', value);
  5248. continue;
  5249. }
  5250. }
  5251. if (opts.nonegate !== true && state.index === 0) {
  5252. negate();
  5253. continue;
  5254. }
  5255. }
  5256. /**
  5257. * Plus
  5258. */
  5259. if (value === '+') {
  5260. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  5261. extglobOpen('plus', value);
  5262. continue;
  5263. }
  5264. if ((prev && prev.value === '(') || opts.regex === false) {
  5265. push({ type: 'plus', value, output: PLUS_LITERAL });
  5266. continue;
  5267. }
  5268. if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {
  5269. push({ type: 'plus', value });
  5270. continue;
  5271. }
  5272. push({ type: 'plus', value: PLUS_LITERAL });
  5273. continue;
  5274. }
  5275. /**
  5276. * Plain text
  5277. */
  5278. if (value === '@') {
  5279. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  5280. push({ type: 'at', extglob: true, value, output: '' });
  5281. continue;
  5282. }
  5283. push({ type: 'text', value });
  5284. continue;
  5285. }
  5286. /**
  5287. * Plain text
  5288. */
  5289. if (value !== '*') {
  5290. if (value === '$' || value === '^') {
  5291. value = `\\${value}`;
  5292. }
  5293. const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
  5294. if (match) {
  5295. value += match[0];
  5296. state.index += match[0].length;
  5297. }
  5298. push({ type: 'text', value });
  5299. continue;
  5300. }
  5301. /**
  5302. * Stars
  5303. */
  5304. if (prev && (prev.type === 'globstar' || prev.star === true)) {
  5305. prev.type = 'star';
  5306. prev.star = true;
  5307. prev.value += value;
  5308. prev.output = star;
  5309. state.backtrack = true;
  5310. state.globstar = true;
  5311. consume(value);
  5312. continue;
  5313. }
  5314. let rest = remaining();
  5315. if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
  5316. extglobOpen('star', value);
  5317. continue;
  5318. }
  5319. if (prev.type === 'star') {
  5320. if (opts.noglobstar === true) {
  5321. consume(value);
  5322. continue;
  5323. }
  5324. const prior = prev.prev;
  5325. const before = prior.prev;
  5326. const isStart = prior.type === 'slash' || prior.type === 'bos';
  5327. const afterStar = before && (before.type === 'star' || before.type === 'globstar');
  5328. if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {
  5329. push({ type: 'star', value, output: '' });
  5330. continue;
  5331. }
  5332. const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
  5333. const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
  5334. if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
  5335. push({ type: 'star', value, output: '' });
  5336. continue;
  5337. }
  5338. // strip consecutive `/**/`
  5339. while (rest.slice(0, 3) === '/**') {
  5340. const after = input[state.index + 4];
  5341. if (after && after !== '/') {
  5342. break;
  5343. }
  5344. rest = rest.slice(3);
  5345. consume('/**', 3);
  5346. }
  5347. if (prior.type === 'bos' && eos()) {
  5348. prev.type = 'globstar';
  5349. prev.value += value;
  5350. prev.output = globstar(opts);
  5351. state.output = prev.output;
  5352. state.globstar = true;
  5353. consume(value);
  5354. continue;
  5355. }
  5356. if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
  5357. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  5358. prior.output = `(?:${prior.output}`;
  5359. prev.type = 'globstar';
  5360. prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
  5361. prev.value += value;
  5362. state.globstar = true;
  5363. state.output += prior.output + prev.output;
  5364. consume(value);
  5365. continue;
  5366. }
  5367. if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
  5368. const end = rest[1] !== void 0 ? '|$' : '';
  5369. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  5370. prior.output = `(?:${prior.output}`;
  5371. prev.type = 'globstar';
  5372. prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
  5373. prev.value += value;
  5374. state.output += prior.output + prev.output;
  5375. state.globstar = true;
  5376. consume(value + advance());
  5377. push({ type: 'slash', value: '/', output: '' });
  5378. continue;
  5379. }
  5380. if (prior.type === 'bos' && rest[0] === '/') {
  5381. prev.type = 'globstar';
  5382. prev.value += value;
  5383. prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
  5384. state.output = prev.output;
  5385. state.globstar = true;
  5386. consume(value + advance());
  5387. push({ type: 'slash', value: '/', output: '' });
  5388. continue;
  5389. }
  5390. // remove single star from output
  5391. state.output = state.output.slice(0, -prev.output.length);
  5392. // reset previous token to globstar
  5393. prev.type = 'globstar';
  5394. prev.output = globstar(opts);
  5395. prev.value += value;
  5396. // reset output with globstar
  5397. state.output += prev.output;
  5398. state.globstar = true;
  5399. consume(value);
  5400. continue;
  5401. }
  5402. const token = { type: 'star', value, output: star };
  5403. if (opts.bash === true) {
  5404. token.output = '.*?';
  5405. if (prev.type === 'bos' || prev.type === 'slash') {
  5406. token.output = nodot + token.output;
  5407. }
  5408. push(token);
  5409. continue;
  5410. }
  5411. if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
  5412. token.output = value;
  5413. push(token);
  5414. continue;
  5415. }
  5416. if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
  5417. if (prev.type === 'dot') {
  5418. state.output += NO_DOT_SLASH;
  5419. prev.output += NO_DOT_SLASH;
  5420. } else if (opts.dot === true) {
  5421. state.output += NO_DOTS_SLASH;
  5422. prev.output += NO_DOTS_SLASH;
  5423. } else {
  5424. state.output += nodot;
  5425. prev.output += nodot;
  5426. }
  5427. if (peek() !== '*') {
  5428. state.output += ONE_CHAR;
  5429. prev.output += ONE_CHAR;
  5430. }
  5431. }
  5432. push(token);
  5433. }
  5434. while (state.brackets > 0) {
  5435. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
  5436. state.output = utils$1.escapeLast(state.output, '[');
  5437. decrement('brackets');
  5438. }
  5439. while (state.parens > 0) {
  5440. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
  5441. state.output = utils$1.escapeLast(state.output, '(');
  5442. decrement('parens');
  5443. }
  5444. while (state.braces > 0) {
  5445. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
  5446. state.output = utils$1.escapeLast(state.output, '{');
  5447. decrement('braces');
  5448. }
  5449. if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
  5450. push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
  5451. }
  5452. // rebuild the output if we had to backtrack at any point
  5453. if (state.backtrack === true) {
  5454. state.output = '';
  5455. for (const token of state.tokens) {
  5456. state.output += token.output != null ? token.output : token.value;
  5457. if (token.suffix) {
  5458. state.output += token.suffix;
  5459. }
  5460. }
  5461. }
  5462. return state;
  5463. };
  5464. /**
  5465. * Fast paths for creating regular expressions for common glob patterns.
  5466. * This can significantly speed up processing and has very little downside
  5467. * impact when none of the fast paths match.
  5468. */
  5469. parse$2.fastpaths = (input, options) => {
  5470. const opts = { ...options };
  5471. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  5472. const len = input.length;
  5473. if (len > max) {
  5474. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  5475. }
  5476. input = REPLACEMENTS[input] || input;
  5477. const win32 = utils$1.isWindows(options);
  5478. // create constants based on platform, for windows or posix
  5479. const {
  5480. DOT_LITERAL,
  5481. SLASH_LITERAL,
  5482. ONE_CHAR,
  5483. DOTS_SLASH,
  5484. NO_DOT,
  5485. NO_DOTS,
  5486. NO_DOTS_SLASH,
  5487. STAR,
  5488. START_ANCHOR
  5489. } = constants$1.globChars(win32);
  5490. const nodot = opts.dot ? NO_DOTS : NO_DOT;
  5491. const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
  5492. const capture = opts.capture ? '' : '?:';
  5493. const state = { negated: false, prefix: '' };
  5494. let star = opts.bash === true ? '.*?' : STAR;
  5495. if (opts.capture) {
  5496. star = `(${star})`;
  5497. }
  5498. const globstar = opts => {
  5499. if (opts.noglobstar === true) return star;
  5500. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  5501. };
  5502. const create = str => {
  5503. switch (str) {
  5504. case '*':
  5505. return `${nodot}${ONE_CHAR}${star}`;
  5506. case '.*':
  5507. return `${DOT_LITERAL}${ONE_CHAR}${star}`;
  5508. case '*.*':
  5509. return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  5510. case '*/*':
  5511. return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
  5512. case '**':
  5513. return nodot + globstar(opts);
  5514. case '**/*':
  5515. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
  5516. case '**/*.*':
  5517. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  5518. case '**/.*':
  5519. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
  5520. default: {
  5521. const match = /^(.*?)\.(\w+)$/.exec(str);
  5522. if (!match) return;
  5523. const source = create(match[1]);
  5524. if (!source) return;
  5525. return source + DOT_LITERAL + match[2];
  5526. }
  5527. }
  5528. };
  5529. const output = utils$1.removePrefix(input, state);
  5530. let source = create(output);
  5531. if (source && opts.strictSlashes !== true) {
  5532. source += `${SLASH_LITERAL}?`;
  5533. }
  5534. return source;
  5535. };
  5536. var parse_1 = parse$2;
  5537. const path = require$$0$1;
  5538. const scan = scan_1;
  5539. const parse$1 = parse_1;
  5540. const utils = utils$3;
  5541. const constants = constants$2;
  5542. const isObject = val => val && typeof val === 'object' && !Array.isArray(val);
  5543. /**
  5544. * Creates a matcher function from one or more glob patterns. The
  5545. * returned function takes a string to match as its first argument,
  5546. * and returns true if the string is a match. The returned matcher
  5547. * function also takes a boolean as the second argument that, when true,
  5548. * returns an object with additional information.
  5549. *
  5550. * ```js
  5551. * const picomatch = require('picomatch');
  5552. * // picomatch(glob[, options]);
  5553. *
  5554. * const isMatch = picomatch('*.!(*a)');
  5555. * console.log(isMatch('a.a')); //=> false
  5556. * console.log(isMatch('a.b')); //=> true
  5557. * ```
  5558. * @name picomatch
  5559. * @param {String|Array} `globs` One or more glob patterns.
  5560. * @param {Object=} `options`
  5561. * @return {Function=} Returns a matcher function.
  5562. * @api public
  5563. */
  5564. const picomatch$1 = (glob, options, returnState = false) => {
  5565. if (Array.isArray(glob)) {
  5566. const fns = glob.map(input => picomatch$1(input, options, returnState));
  5567. const arrayMatcher = str => {
  5568. for (const isMatch of fns) {
  5569. const state = isMatch(str);
  5570. if (state) return state;
  5571. }
  5572. return false;
  5573. };
  5574. return arrayMatcher;
  5575. }
  5576. const isState = isObject(glob) && glob.tokens && glob.input;
  5577. if (glob === '' || (typeof glob !== 'string' && !isState)) {
  5578. throw new TypeError('Expected pattern to be a non-empty string');
  5579. }
  5580. const opts = options || {};
  5581. const posix = utils.isWindows(options);
  5582. const regex = isState
  5583. ? picomatch$1.compileRe(glob, options)
  5584. : picomatch$1.makeRe(glob, options, false, true);
  5585. const state = regex.state;
  5586. delete regex.state;
  5587. let isIgnored = () => false;
  5588. if (opts.ignore) {
  5589. const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
  5590. isIgnored = picomatch$1(opts.ignore, ignoreOpts, returnState);
  5591. }
  5592. const matcher = (input, returnObject = false) => {
  5593. const { isMatch, match, output } = picomatch$1.test(input, regex, options, { glob, posix });
  5594. const result = { glob, state, regex, posix, input, output, match, isMatch };
  5595. if (typeof opts.onResult === 'function') {
  5596. opts.onResult(result);
  5597. }
  5598. if (isMatch === false) {
  5599. result.isMatch = false;
  5600. return returnObject ? result : false;
  5601. }
  5602. if (isIgnored(input)) {
  5603. if (typeof opts.onIgnore === 'function') {
  5604. opts.onIgnore(result);
  5605. }
  5606. result.isMatch = false;
  5607. return returnObject ? result : false;
  5608. }
  5609. if (typeof opts.onMatch === 'function') {
  5610. opts.onMatch(result);
  5611. }
  5612. return returnObject ? result : true;
  5613. };
  5614. if (returnState) {
  5615. matcher.state = state;
  5616. }
  5617. return matcher;
  5618. };
  5619. /**
  5620. * Test `input` with the given `regex`. This is used by the main
  5621. * `picomatch()` function to test the input string.
  5622. *
  5623. * ```js
  5624. * const picomatch = require('picomatch');
  5625. * // picomatch.test(input, regex[, options]);
  5626. *
  5627. * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
  5628. * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
  5629. * ```
  5630. * @param {String} `input` String to test.
  5631. * @param {RegExp} `regex`
  5632. * @return {Object} Returns an object with matching info.
  5633. * @api public
  5634. */
  5635. picomatch$1.test = (input, regex, options, { glob, posix } = {}) => {
  5636. if (typeof input !== 'string') {
  5637. throw new TypeError('Expected input to be a string');
  5638. }
  5639. if (input === '') {
  5640. return { isMatch: false, output: '' };
  5641. }
  5642. const opts = options || {};
  5643. const format = opts.format || (posix ? utils.toPosixSlashes : null);
  5644. let match = input === glob;
  5645. let output = (match && format) ? format(input) : input;
  5646. if (match === false) {
  5647. output = format ? format(input) : input;
  5648. match = output === glob;
  5649. }
  5650. if (match === false || opts.capture === true) {
  5651. if (opts.matchBase === true || opts.basename === true) {
  5652. match = picomatch$1.matchBase(input, regex, options, posix);
  5653. } else {
  5654. match = regex.exec(output);
  5655. }
  5656. }
  5657. return { isMatch: Boolean(match), match, output };
  5658. };
  5659. /**
  5660. * Match the basename of a filepath.
  5661. *
  5662. * ```js
  5663. * const picomatch = require('picomatch');
  5664. * // picomatch.matchBase(input, glob[, options]);
  5665. * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
  5666. * ```
  5667. * @param {String} `input` String to test.
  5668. * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
  5669. * @return {Boolean}
  5670. * @api public
  5671. */
  5672. picomatch$1.matchBase = (input, glob, options, posix = utils.isWindows(options)) => {
  5673. const regex = glob instanceof RegExp ? glob : picomatch$1.makeRe(glob, options);
  5674. return regex.test(path.basename(input));
  5675. };
  5676. /**
  5677. * Returns true if **any** of the given glob `patterns` match the specified `string`.
  5678. *
  5679. * ```js
  5680. * const picomatch = require('picomatch');
  5681. * // picomatch.isMatch(string, patterns[, options]);
  5682. *
  5683. * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
  5684. * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
  5685. * ```
  5686. * @param {String|Array} str The string to test.
  5687. * @param {String|Array} patterns One or more glob patterns to use for matching.
  5688. * @param {Object} [options] See available [options](#options).
  5689. * @return {Boolean} Returns true if any patterns match `str`
  5690. * @api public
  5691. */
  5692. picomatch$1.isMatch = (str, patterns, options) => picomatch$1(patterns, options)(str);
  5693. /**
  5694. * Parse a glob pattern to create the source string for a regular
  5695. * expression.
  5696. *
  5697. * ```js
  5698. * const picomatch = require('picomatch');
  5699. * const result = picomatch.parse(pattern[, options]);
  5700. * ```
  5701. * @param {String} `pattern`
  5702. * @param {Object} `options`
  5703. * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
  5704. * @api public
  5705. */
  5706. picomatch$1.parse = (pattern, options) => {
  5707. if (Array.isArray(pattern)) return pattern.map(p => picomatch$1.parse(p, options));
  5708. return parse$1(pattern, { ...options, fastpaths: false });
  5709. };
  5710. /**
  5711. * Scan a glob pattern to separate the pattern into segments.
  5712. *
  5713. * ```js
  5714. * const picomatch = require('picomatch');
  5715. * // picomatch.scan(input[, options]);
  5716. *
  5717. * const result = picomatch.scan('!./foo/*.js');
  5718. * console.log(result);
  5719. * { prefix: '!./',
  5720. * input: '!./foo/*.js',
  5721. * start: 3,
  5722. * base: 'foo',
  5723. * glob: '*.js',
  5724. * isBrace: false,
  5725. * isBracket: false,
  5726. * isGlob: true,
  5727. * isExtglob: false,
  5728. * isGlobstar: false,
  5729. * negated: true }
  5730. * ```
  5731. * @param {String} `input` Glob pattern to scan.
  5732. * @param {Object} `options`
  5733. * @return {Object} Returns an object with
  5734. * @api public
  5735. */
  5736. picomatch$1.scan = (input, options) => scan(input, options);
  5737. /**
  5738. * Compile a regular expression from the `state` object returned by the
  5739. * [parse()](#parse) method.
  5740. *
  5741. * @param {Object} `state`
  5742. * @param {Object} `options`
  5743. * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
  5744. * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
  5745. * @return {RegExp}
  5746. * @api public
  5747. */
  5748. picomatch$1.compileRe = (state, options, returnOutput = false, returnState = false) => {
  5749. if (returnOutput === true) {
  5750. return state.output;
  5751. }
  5752. const opts = options || {};
  5753. const prepend = opts.contains ? '' : '^';
  5754. const append = opts.contains ? '' : '$';
  5755. let source = `${prepend}(?:${state.output})${append}`;
  5756. if (state && state.negated === true) {
  5757. source = `^(?!${source}).*$`;
  5758. }
  5759. const regex = picomatch$1.toRegex(source, options);
  5760. if (returnState === true) {
  5761. regex.state = state;
  5762. }
  5763. return regex;
  5764. };
  5765. /**
  5766. * Create a regular expression from a parsed glob pattern.
  5767. *
  5768. * ```js
  5769. * const picomatch = require('picomatch');
  5770. * const state = picomatch.parse('*.js');
  5771. * // picomatch.compileRe(state[, options]);
  5772. *
  5773. * console.log(picomatch.compileRe(state));
  5774. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  5775. * ```
  5776. * @param {String} `state` The object returned from the `.parse` method.
  5777. * @param {Object} `options`
  5778. * @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result.
  5779. * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
  5780. * @return {RegExp} Returns a regex created from the given pattern.
  5781. * @api public
  5782. */
  5783. picomatch$1.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
  5784. if (!input || typeof input !== 'string') {
  5785. throw new TypeError('Expected a non-empty string');
  5786. }
  5787. let parsed = { negated: false, fastpaths: true };
  5788. if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
  5789. parsed.output = parse$1.fastpaths(input, options);
  5790. }
  5791. if (!parsed.output) {
  5792. parsed = parse$1(input, options);
  5793. }
  5794. return picomatch$1.compileRe(parsed, options, returnOutput, returnState);
  5795. };
  5796. /**
  5797. * Create a regular expression from the given regex source string.
  5798. *
  5799. * ```js
  5800. * const picomatch = require('picomatch');
  5801. * // picomatch.toRegex(source[, options]);
  5802. *
  5803. * const { output } = picomatch.parse('*.js');
  5804. * console.log(picomatch.toRegex(output));
  5805. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  5806. * ```
  5807. * @param {String} `source` Regular expression source string.
  5808. * @param {Object} `options`
  5809. * @return {RegExp}
  5810. * @api public
  5811. */
  5812. picomatch$1.toRegex = (source, options) => {
  5813. try {
  5814. const opts = options || {};
  5815. return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
  5816. } catch (err) {
  5817. if (options && options.debug === true) throw err;
  5818. return /$^/;
  5819. }
  5820. };
  5821. /**
  5822. * Picomatch constants.
  5823. * @return {Object}
  5824. */
  5825. picomatch$1.constants = constants;
  5826. /**
  5827. * Expose "picomatch"
  5828. */
  5829. var picomatch_1 = picomatch$1;
  5830. var picomatch = picomatch_1;
  5831. const pm = /*@__PURE__*/getDefaultExportFromCjs(picomatch);
  5832. const extractors = {
  5833. ArrayPattern(names, param) {
  5834. for (const element of param.elements) {
  5835. if (element)
  5836. extractors[element.type](names, element);
  5837. }
  5838. },
  5839. AssignmentPattern(names, param) {
  5840. extractors[param.left.type](names, param.left);
  5841. },
  5842. Identifier(names, param) {
  5843. names.push(param.name);
  5844. },
  5845. MemberExpression() { },
  5846. ObjectPattern(names, param) {
  5847. for (const prop of param.properties) {
  5848. // @ts-ignore Typescript reports that this is not a valid type
  5849. if (prop.type === 'RestElement') {
  5850. extractors.RestElement(names, prop);
  5851. }
  5852. else {
  5853. extractors[prop.value.type](names, prop.value);
  5854. }
  5855. }
  5856. },
  5857. RestElement(names, param) {
  5858. extractors[param.argument.type](names, param.argument);
  5859. }
  5860. };
  5861. const extractAssignedNames = function extractAssignedNames(param) {
  5862. const names = [];
  5863. extractors[param.type](names, param);
  5864. return names;
  5865. };
  5866. // Helper since Typescript can't detect readonly arrays with Array.isArray
  5867. function isArray$1(arg) {
  5868. return Array.isArray(arg);
  5869. }
  5870. function ensureArray(thing) {
  5871. if (isArray$1(thing))
  5872. return thing;
  5873. if (thing == null)
  5874. return [];
  5875. return [thing];
  5876. }
  5877. const normalizePath = function normalizePath(filename) {
  5878. return filename.split(require$$0$1.win32.sep).join(require$$0$1.posix.sep);
  5879. };
  5880. function getMatcherString(id, resolutionBase) {
  5881. if (resolutionBase === false || require$$0$1.isAbsolute(id) || id.startsWith('**')) {
  5882. return normalizePath(id);
  5883. }
  5884. // resolve('') is valid and will default to process.cwd()
  5885. const basePath = normalizePath(require$$0$1.resolve(resolutionBase || ''))
  5886. // escape all possible (posix + win) path characters that might interfere with regex
  5887. .replace(/[-^$*+?.()|[\]{}]/g, '\\$&');
  5888. // Note that we use posix.join because:
  5889. // 1. the basePath has been normalized to use /
  5890. // 2. the incoming glob (id) matcher, also uses /
  5891. // otherwise Node will force backslash (\) on windows
  5892. return require$$0$1.posix.join(basePath, normalizePath(id));
  5893. }
  5894. const createFilter = function createFilter(include, exclude, options) {
  5895. const resolutionBase = options && options.resolve;
  5896. const getMatcher = (id) => id instanceof RegExp
  5897. ? id
  5898. : {
  5899. test: (what) => {
  5900. // this refactor is a tad overly verbose but makes for easy debugging
  5901. const pattern = getMatcherString(id, resolutionBase);
  5902. const fn = pm(pattern, { dot: true });
  5903. const result = fn(what);
  5904. return result;
  5905. }
  5906. };
  5907. const includeMatchers = ensureArray(include).map(getMatcher);
  5908. const excludeMatchers = ensureArray(exclude).map(getMatcher);
  5909. return function result(id) {
  5910. if (typeof id !== 'string')
  5911. return false;
  5912. if (/\0/.test(id))
  5913. return false;
  5914. const pathId = normalizePath(id);
  5915. for (let i = 0; i < excludeMatchers.length; ++i) {
  5916. const matcher = excludeMatchers[i];
  5917. if (matcher.test(pathId))
  5918. return false;
  5919. }
  5920. for (let i = 0; i < includeMatchers.length; ++i) {
  5921. const matcher = includeMatchers[i];
  5922. if (matcher.test(pathId))
  5923. return true;
  5924. }
  5925. return !includeMatchers.length;
  5926. };
  5927. };
  5928. const reservedWords$1 = 'break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public';
  5929. const builtins = 'arguments Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl';
  5930. const forbiddenIdentifiers = new Set(`${reservedWords$1} ${builtins}`.split(' '));
  5931. forbiddenIdentifiers.add('');
  5932. function createInclusionContext() {
  5933. return {
  5934. brokenFlow: false,
  5935. hasBreak: false,
  5936. hasContinue: false,
  5937. includedCallArguments: new Set(),
  5938. includedLabels: new Set()
  5939. };
  5940. }
  5941. function createHasEffectsContext() {
  5942. return {
  5943. accessed: new PathTracker(),
  5944. assigned: new PathTracker(),
  5945. brokenFlow: false,
  5946. called: new DiscriminatedPathTracker(),
  5947. hasBreak: false,
  5948. hasContinue: false,
  5949. ignore: {
  5950. breaks: false,
  5951. continues: false,
  5952. labels: new Set(),
  5953. returnYield: false,
  5954. this: false
  5955. },
  5956. includedLabels: new Set(),
  5957. instantiated: new DiscriminatedPathTracker(),
  5958. replacedVariableInits: new Map()
  5959. };
  5960. }
  5961. function assembleMemberDescriptions(memberDescriptions, inheritedDescriptions = null) {
  5962. return Object.create(inheritedDescriptions, memberDescriptions);
  5963. }
  5964. const UNDEFINED_EXPRESSION = new (class UndefinedExpression extends ExpressionEntity {
  5965. getLiteralValueAtPath() {
  5966. return undefined;
  5967. }
  5968. })();
  5969. const returnsUnknown = {
  5970. value: {
  5971. hasEffectsWhenCalled: null,
  5972. returns: UNKNOWN_EXPRESSION
  5973. }
  5974. };
  5975. const UNKNOWN_LITERAL_BOOLEAN = new (class UnknownBoolean extends ExpressionEntity {
  5976. getReturnExpressionWhenCalledAtPath(path) {
  5977. if (path.length === 1) {
  5978. return getMemberReturnExpressionWhenCalled(literalBooleanMembers, path[0]);
  5979. }
  5980. return UNKNOWN_RETURN_EXPRESSION;
  5981. }
  5982. hasEffectsOnInteractionAtPath(path, interaction, context) {
  5983. if (interaction.type === INTERACTION_ACCESSED) {
  5984. return path.length > 1;
  5985. }
  5986. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  5987. return hasMemberEffectWhenCalled(literalBooleanMembers, path[0], interaction, context);
  5988. }
  5989. return true;
  5990. }
  5991. })();
  5992. const returnsBoolean = {
  5993. value: {
  5994. hasEffectsWhenCalled: null,
  5995. returns: UNKNOWN_LITERAL_BOOLEAN
  5996. }
  5997. };
  5998. const UNKNOWN_LITERAL_NUMBER = new (class UnknownNumber extends ExpressionEntity {
  5999. getReturnExpressionWhenCalledAtPath(path) {
  6000. if (path.length === 1) {
  6001. return getMemberReturnExpressionWhenCalled(literalNumberMembers, path[0]);
  6002. }
  6003. return UNKNOWN_RETURN_EXPRESSION;
  6004. }
  6005. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6006. if (interaction.type === INTERACTION_ACCESSED) {
  6007. return path.length > 1;
  6008. }
  6009. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  6010. return hasMemberEffectWhenCalled(literalNumberMembers, path[0], interaction, context);
  6011. }
  6012. return true;
  6013. }
  6014. })();
  6015. const returnsNumber = {
  6016. value: {
  6017. hasEffectsWhenCalled: null,
  6018. returns: UNKNOWN_LITERAL_NUMBER
  6019. }
  6020. };
  6021. const UNKNOWN_LITERAL_STRING = new (class UnknownString extends ExpressionEntity {
  6022. getReturnExpressionWhenCalledAtPath(path) {
  6023. if (path.length === 1) {
  6024. return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
  6025. }
  6026. return UNKNOWN_RETURN_EXPRESSION;
  6027. }
  6028. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6029. if (interaction.type === INTERACTION_ACCESSED) {
  6030. return path.length > 1;
  6031. }
  6032. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  6033. return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
  6034. }
  6035. return true;
  6036. }
  6037. })();
  6038. const returnsString = {
  6039. value: {
  6040. hasEffectsWhenCalled: null,
  6041. returns: UNKNOWN_LITERAL_STRING
  6042. }
  6043. };
  6044. const stringReplace = {
  6045. value: {
  6046. hasEffectsWhenCalled({ args }, context) {
  6047. const argument1 = args[2];
  6048. return (args.length < 3 ||
  6049. (typeof argument1.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, {
  6050. deoptimizeCache() { }
  6051. }) === 'symbol' &&
  6052. argument1.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)));
  6053. },
  6054. returns: UNKNOWN_LITERAL_STRING
  6055. }
  6056. };
  6057. const objectMembers = assembleMemberDescriptions({
  6058. hasOwnProperty: returnsBoolean,
  6059. isPrototypeOf: returnsBoolean,
  6060. propertyIsEnumerable: returnsBoolean,
  6061. toLocaleString: returnsString,
  6062. toString: returnsString,
  6063. valueOf: returnsUnknown
  6064. });
  6065. const literalBooleanMembers = assembleMemberDescriptions({
  6066. valueOf: returnsBoolean
  6067. }, objectMembers);
  6068. const literalNumberMembers = assembleMemberDescriptions({
  6069. toExponential: returnsString,
  6070. toFixed: returnsString,
  6071. toLocaleString: returnsString,
  6072. toPrecision: returnsString,
  6073. valueOf: returnsNumber
  6074. }, objectMembers);
  6075. /**
  6076. * RegExp are stateful when they have the global or sticky flags set.
  6077. * But if we actually don't use them, the side effect does not matter.
  6078. * the check logic in `hasEffectsOnInteractionAtPath`.
  6079. */
  6080. const literalRegExpMembers = assembleMemberDescriptions({
  6081. exec: returnsUnknown,
  6082. test: returnsBoolean
  6083. }, objectMembers);
  6084. const literalStringMembers = assembleMemberDescriptions({
  6085. anchor: returnsString,
  6086. at: returnsUnknown,
  6087. big: returnsString,
  6088. blink: returnsString,
  6089. bold: returnsString,
  6090. charAt: returnsString,
  6091. charCodeAt: returnsNumber,
  6092. codePointAt: returnsUnknown,
  6093. concat: returnsString,
  6094. endsWith: returnsBoolean,
  6095. fixed: returnsString,
  6096. fontcolor: returnsString,
  6097. fontsize: returnsString,
  6098. includes: returnsBoolean,
  6099. indexOf: returnsNumber,
  6100. italics: returnsString,
  6101. lastIndexOf: returnsNumber,
  6102. link: returnsString,
  6103. localeCompare: returnsNumber,
  6104. match: returnsUnknown,
  6105. matchAll: returnsUnknown,
  6106. normalize: returnsString,
  6107. padEnd: returnsString,
  6108. padStart: returnsString,
  6109. repeat: returnsString,
  6110. replace: stringReplace,
  6111. replaceAll: stringReplace,
  6112. search: returnsNumber,
  6113. slice: returnsString,
  6114. small: returnsString,
  6115. split: returnsUnknown,
  6116. startsWith: returnsBoolean,
  6117. strike: returnsString,
  6118. sub: returnsString,
  6119. substr: returnsString,
  6120. substring: returnsString,
  6121. sup: returnsString,
  6122. toLocaleLowerCase: returnsString,
  6123. toLocaleUpperCase: returnsString,
  6124. toLowerCase: returnsString,
  6125. toString: returnsString,
  6126. toUpperCase: returnsString,
  6127. trim: returnsString,
  6128. trimEnd: returnsString,
  6129. trimLeft: returnsString,
  6130. trimRight: returnsString,
  6131. trimStart: returnsString,
  6132. valueOf: returnsString
  6133. }, objectMembers);
  6134. function getLiteralMembersForValue(value) {
  6135. if (value instanceof RegExp) {
  6136. return literalRegExpMembers;
  6137. }
  6138. switch (typeof value) {
  6139. case 'boolean': {
  6140. return literalBooleanMembers;
  6141. }
  6142. case 'number': {
  6143. return literalNumberMembers;
  6144. }
  6145. case 'string': {
  6146. return literalStringMembers;
  6147. }
  6148. }
  6149. return Object.create(null);
  6150. }
  6151. function hasMemberEffectWhenCalled(members, memberName, interaction, context) {
  6152. if (typeof memberName !== 'string' || !members[memberName]) {
  6153. return true;
  6154. }
  6155. return members[memberName].hasEffectsWhenCalled?.(interaction, context) || false;
  6156. }
  6157. function getMemberReturnExpressionWhenCalled(members, memberName) {
  6158. if (typeof memberName !== 'string' || !members[memberName])
  6159. return UNKNOWN_RETURN_EXPRESSION;
  6160. return [members[memberName].returns, false];
  6161. }
  6162. // AST walker module for Mozilla Parser API compatible trees
  6163. function skipThrough(node, st, c) { c(node, st); }
  6164. function ignore(_node, _st, _c) {}
  6165. // Node walkers.
  6166. var base = {};
  6167. base.Program = base.BlockStatement = base.StaticBlock = function (node, st, c) {
  6168. for (var i = 0, list = node.body; i < list.length; i += 1)
  6169. {
  6170. var stmt = list[i];
  6171. c(stmt, st, "Statement");
  6172. }
  6173. };
  6174. base.Statement = skipThrough;
  6175. base.EmptyStatement = ignore;
  6176. base.ExpressionStatement = base.ParenthesizedExpression = base.ChainExpression =
  6177. function (node, st, c) { return c(node.expression, st, "Expression"); };
  6178. base.IfStatement = function (node, st, c) {
  6179. c(node.test, st, "Expression");
  6180. c(node.consequent, st, "Statement");
  6181. if (node.alternate) { c(node.alternate, st, "Statement"); }
  6182. };
  6183. base.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); };
  6184. base.BreakStatement = base.ContinueStatement = ignore;
  6185. base.WithStatement = function (node, st, c) {
  6186. c(node.object, st, "Expression");
  6187. c(node.body, st, "Statement");
  6188. };
  6189. base.SwitchStatement = function (node, st, c) {
  6190. c(node.discriminant, st, "Expression");
  6191. for (var i$1 = 0, list$1 = node.cases; i$1 < list$1.length; i$1 += 1) {
  6192. var cs = list$1[i$1];
  6193. if (cs.test) { c(cs.test, st, "Expression"); }
  6194. for (var i = 0, list = cs.consequent; i < list.length; i += 1)
  6195. {
  6196. var cons = list[i];
  6197. c(cons, st, "Statement");
  6198. }
  6199. }
  6200. };
  6201. base.SwitchCase = function (node, st, c) {
  6202. if (node.test) { c(node.test, st, "Expression"); }
  6203. for (var i = 0, list = node.consequent; i < list.length; i += 1)
  6204. {
  6205. var cons = list[i];
  6206. c(cons, st, "Statement");
  6207. }
  6208. };
  6209. base.ReturnStatement = base.YieldExpression = base.AwaitExpression = function (node, st, c) {
  6210. if (node.argument) { c(node.argument, st, "Expression"); }
  6211. };
  6212. base.ThrowStatement = base.SpreadElement =
  6213. function (node, st, c) { return c(node.argument, st, "Expression"); };
  6214. base.TryStatement = function (node, st, c) {
  6215. c(node.block, st, "Statement");
  6216. if (node.handler) { c(node.handler, st); }
  6217. if (node.finalizer) { c(node.finalizer, st, "Statement"); }
  6218. };
  6219. base.CatchClause = function (node, st, c) {
  6220. if (node.param) { c(node.param, st, "Pattern"); }
  6221. c(node.body, st, "Statement");
  6222. };
  6223. base.WhileStatement = base.DoWhileStatement = function (node, st, c) {
  6224. c(node.test, st, "Expression");
  6225. c(node.body, st, "Statement");
  6226. };
  6227. base.ForStatement = function (node, st, c) {
  6228. if (node.init) { c(node.init, st, "ForInit"); }
  6229. if (node.test) { c(node.test, st, "Expression"); }
  6230. if (node.update) { c(node.update, st, "Expression"); }
  6231. c(node.body, st, "Statement");
  6232. };
  6233. base.ForInStatement = base.ForOfStatement = function (node, st, c) {
  6234. c(node.left, st, "ForInit");
  6235. c(node.right, st, "Expression");
  6236. c(node.body, st, "Statement");
  6237. };
  6238. base.ForInit = function (node, st, c) {
  6239. if (node.type === "VariableDeclaration") { c(node, st); }
  6240. else { c(node, st, "Expression"); }
  6241. };
  6242. base.DebuggerStatement = ignore;
  6243. base.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); };
  6244. base.VariableDeclaration = function (node, st, c) {
  6245. for (var i = 0, list = node.declarations; i < list.length; i += 1)
  6246. {
  6247. var decl = list[i];
  6248. c(decl, st);
  6249. }
  6250. };
  6251. base.VariableDeclarator = function (node, st, c) {
  6252. c(node.id, st, "Pattern");
  6253. if (node.init) { c(node.init, st, "Expression"); }
  6254. };
  6255. base.Function = function (node, st, c) {
  6256. if (node.id) { c(node.id, st, "Pattern"); }
  6257. for (var i = 0, list = node.params; i < list.length; i += 1)
  6258. {
  6259. var param = list[i];
  6260. c(param, st, "Pattern");
  6261. }
  6262. c(node.body, st, node.expression ? "Expression" : "Statement");
  6263. };
  6264. base.Pattern = function (node, st, c) {
  6265. if (node.type === "Identifier")
  6266. { c(node, st, "VariablePattern"); }
  6267. else if (node.type === "MemberExpression")
  6268. { c(node, st, "MemberPattern"); }
  6269. else
  6270. { c(node, st); }
  6271. };
  6272. base.VariablePattern = ignore;
  6273. base.MemberPattern = skipThrough;
  6274. base.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); };
  6275. base.ArrayPattern = function (node, st, c) {
  6276. for (var i = 0, list = node.elements; i < list.length; i += 1) {
  6277. var elt = list[i];
  6278. if (elt) { c(elt, st, "Pattern"); }
  6279. }
  6280. };
  6281. base.ObjectPattern = function (node, st, c) {
  6282. for (var i = 0, list = node.properties; i < list.length; i += 1) {
  6283. var prop = list[i];
  6284. if (prop.type === "Property") {
  6285. if (prop.computed) { c(prop.key, st, "Expression"); }
  6286. c(prop.value, st, "Pattern");
  6287. } else if (prop.type === "RestElement") {
  6288. c(prop.argument, st, "Pattern");
  6289. }
  6290. }
  6291. };
  6292. base.Expression = skipThrough;
  6293. base.ThisExpression = base.Super = base.MetaProperty = ignore;
  6294. base.ArrayExpression = function (node, st, c) {
  6295. for (var i = 0, list = node.elements; i < list.length; i += 1) {
  6296. var elt = list[i];
  6297. if (elt) { c(elt, st, "Expression"); }
  6298. }
  6299. };
  6300. base.ObjectExpression = function (node, st, c) {
  6301. for (var i = 0, list = node.properties; i < list.length; i += 1)
  6302. {
  6303. var prop = list[i];
  6304. c(prop, st);
  6305. }
  6306. };
  6307. base.FunctionExpression = base.ArrowFunctionExpression = base.FunctionDeclaration;
  6308. base.SequenceExpression = function (node, st, c) {
  6309. for (var i = 0, list = node.expressions; i < list.length; i += 1)
  6310. {
  6311. var expr = list[i];
  6312. c(expr, st, "Expression");
  6313. }
  6314. };
  6315. base.TemplateLiteral = function (node, st, c) {
  6316. for (var i = 0, list = node.quasis; i < list.length; i += 1)
  6317. {
  6318. var quasi = list[i];
  6319. c(quasi, st);
  6320. }
  6321. for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1)
  6322. {
  6323. var expr = list$1[i$1];
  6324. c(expr, st, "Expression");
  6325. }
  6326. };
  6327. base.TemplateElement = ignore;
  6328. base.UnaryExpression = base.UpdateExpression = function (node, st, c) {
  6329. c(node.argument, st, "Expression");
  6330. };
  6331. base.BinaryExpression = base.LogicalExpression = function (node, st, c) {
  6332. c(node.left, st, "Expression");
  6333. c(node.right, st, "Expression");
  6334. };
  6335. base.AssignmentExpression = base.AssignmentPattern = function (node, st, c) {
  6336. c(node.left, st, "Pattern");
  6337. c(node.right, st, "Expression");
  6338. };
  6339. base.ConditionalExpression = function (node, st, c) {
  6340. c(node.test, st, "Expression");
  6341. c(node.consequent, st, "Expression");
  6342. c(node.alternate, st, "Expression");
  6343. };
  6344. base.NewExpression = base.CallExpression = function (node, st, c) {
  6345. c(node.callee, st, "Expression");
  6346. if (node.arguments)
  6347. { for (var i = 0, list = node.arguments; i < list.length; i += 1)
  6348. {
  6349. var arg = list[i];
  6350. c(arg, st, "Expression");
  6351. } }
  6352. };
  6353. base.MemberExpression = function (node, st, c) {
  6354. c(node.object, st, "Expression");
  6355. if (node.computed) { c(node.property, st, "Expression"); }
  6356. };
  6357. base.ExportNamedDeclaration = base.ExportDefaultDeclaration = function (node, st, c) {
  6358. if (node.declaration)
  6359. { c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); }
  6360. if (node.source) { c(node.source, st, "Expression"); }
  6361. };
  6362. base.ExportAllDeclaration = function (node, st, c) {
  6363. if (node.exported)
  6364. { c(node.exported, st); }
  6365. c(node.source, st, "Expression");
  6366. };
  6367. base.ImportDeclaration = function (node, st, c) {
  6368. for (var i = 0, list = node.specifiers; i < list.length; i += 1)
  6369. {
  6370. var spec = list[i];
  6371. c(spec, st);
  6372. }
  6373. c(node.source, st, "Expression");
  6374. };
  6375. base.ImportExpression = function (node, st, c) {
  6376. c(node.source, st, "Expression");
  6377. };
  6378. base.ImportSpecifier = base.ImportDefaultSpecifier = base.ImportNamespaceSpecifier = base.Identifier = base.PrivateIdentifier = base.Literal = ignore;
  6379. base.TaggedTemplateExpression = function (node, st, c) {
  6380. c(node.tag, st, "Expression");
  6381. c(node.quasi, st, "Expression");
  6382. };
  6383. base.ClassDeclaration = base.ClassExpression = function (node, st, c) { return c(node, st, "Class"); };
  6384. base.Class = function (node, st, c) {
  6385. if (node.id) { c(node.id, st, "Pattern"); }
  6386. if (node.superClass) { c(node.superClass, st, "Expression"); }
  6387. c(node.body, st);
  6388. };
  6389. base.ClassBody = function (node, st, c) {
  6390. for (var i = 0, list = node.body; i < list.length; i += 1)
  6391. {
  6392. var elt = list[i];
  6393. c(elt, st);
  6394. }
  6395. };
  6396. base.MethodDefinition = base.PropertyDefinition = base.Property = function (node, st, c) {
  6397. if (node.computed) { c(node.key, st, "Expression"); }
  6398. if (node.value) { c(node.value, st, "Expression"); }
  6399. };
  6400. const ArrowFunctionExpression$1 = 'ArrowFunctionExpression';
  6401. const BinaryExpression$1 = 'BinaryExpression';
  6402. const BlockStatement$1 = 'BlockStatement';
  6403. const CallExpression$1 = 'CallExpression';
  6404. const ChainExpression$1 = 'ChainExpression';
  6405. const ConditionalExpression$1 = 'ConditionalExpression';
  6406. const ExportDefaultDeclaration$1 = 'ExportDefaultDeclaration';
  6407. const ExportNamedDeclaration$1 = 'ExportNamedDeclaration';
  6408. const ExpressionStatement$1 = 'ExpressionStatement';
  6409. const FunctionDeclaration$1 = 'FunctionDeclaration';
  6410. const Identifier$1 = 'Identifier';
  6411. const LogicalExpression$1 = 'LogicalExpression';
  6412. const NewExpression$1 = 'NewExpression';
  6413. const Program$1 = 'Program';
  6414. const Property$1 = 'Property';
  6415. const ReturnStatement$1 = 'ReturnStatement';
  6416. const SequenceExpression$1 = 'SequenceExpression';
  6417. const VariableDeclarator$1 = 'VariableDeclarator';
  6418. const VariableDeclaration$1 = 'VariableDeclaration';
  6419. // this looks ridiculous, but it prevents sourcemap tooling from mistaking
  6420. // this for an actual sourceMappingURL
  6421. let SOURCEMAPPING_URL = 'sourceMa';
  6422. SOURCEMAPPING_URL += 'ppingURL';
  6423. const whiteSpaceNoNewline = '[ \\f\\r\\t\\v\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]';
  6424. const SOURCEMAPPING_URL_RE = new RegExp(`^#${whiteSpaceNoNewline}+${SOURCEMAPPING_URL}=.+`);
  6425. const ANNOTATION_KEY = '_rollupAnnotations';
  6426. const INVALID_COMMENT_KEY = '_rollupRemoved';
  6427. function handlePureAnnotationsOfNode(node, state, type = node.type) {
  6428. const { annotations, code } = state;
  6429. // eslint-disable-next-line unicorn/consistent-destructuring
  6430. let comment = annotations[state.annotationIndex];
  6431. while (comment && node.start >= comment.end) {
  6432. markPureNode(node, comment, code);
  6433. comment = annotations[++state.annotationIndex];
  6434. }
  6435. if (comment && comment.end <= node.end) {
  6436. base[type](node, state, handlePureAnnotationsOfNode);
  6437. // eslint-disable-next-line unicorn/consistent-destructuring
  6438. while ((comment = annotations[state.annotationIndex]) && comment.end <= node.end) {
  6439. ++state.annotationIndex;
  6440. annotateNode(node, comment, false);
  6441. }
  6442. }
  6443. }
  6444. const neitherWithespaceNorBrackets = /[^\s(]/g;
  6445. const noWhitespace = /\S/g;
  6446. function markPureNode(node, comment, code) {
  6447. const annotatedNodes = [];
  6448. let invalidAnnotation;
  6449. const codeInBetween = code.slice(comment.end, node.start);
  6450. if (doesNotMatchOutsideComment(codeInBetween, neitherWithespaceNorBrackets)) {
  6451. const parentStart = node.start;
  6452. while (true) {
  6453. annotatedNodes.push(node);
  6454. switch (node.type) {
  6455. case ExpressionStatement$1:
  6456. case ChainExpression$1: {
  6457. node = node.expression;
  6458. continue;
  6459. }
  6460. case SequenceExpression$1: {
  6461. // if there are parentheses, the annotation would apply to the entire expression
  6462. if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) {
  6463. node = node.expressions[0];
  6464. continue;
  6465. }
  6466. invalidAnnotation = true;
  6467. break;
  6468. }
  6469. case ConditionalExpression$1: {
  6470. // if there are parentheses, the annotation would apply to the entire expression
  6471. if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) {
  6472. node = node.test;
  6473. continue;
  6474. }
  6475. invalidAnnotation = true;
  6476. break;
  6477. }
  6478. case LogicalExpression$1:
  6479. case BinaryExpression$1: {
  6480. // if there are parentheses, the annotation would apply to the entire expression
  6481. if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) {
  6482. node = node.left;
  6483. continue;
  6484. }
  6485. invalidAnnotation = true;
  6486. break;
  6487. }
  6488. case ExportNamedDeclaration$1:
  6489. case ExportDefaultDeclaration$1: {
  6490. node = node.declaration;
  6491. continue;
  6492. }
  6493. case VariableDeclaration$1: {
  6494. const declaration = node;
  6495. if (declaration.kind === 'const') {
  6496. // jsdoc only applies to the first declaration
  6497. node = declaration.declarations[0].init;
  6498. continue;
  6499. }
  6500. invalidAnnotation = true;
  6501. break;
  6502. }
  6503. case VariableDeclarator$1: {
  6504. node = node.init;
  6505. continue;
  6506. }
  6507. case FunctionDeclaration$1:
  6508. case ArrowFunctionExpression$1:
  6509. case CallExpression$1:
  6510. case NewExpression$1: {
  6511. break;
  6512. }
  6513. default: {
  6514. invalidAnnotation = true;
  6515. }
  6516. }
  6517. break;
  6518. }
  6519. }
  6520. else {
  6521. invalidAnnotation = true;
  6522. }
  6523. if (invalidAnnotation) {
  6524. annotateNode(node, comment, false);
  6525. }
  6526. else {
  6527. for (const node of annotatedNodes) {
  6528. annotateNode(node, comment, true);
  6529. }
  6530. }
  6531. }
  6532. function doesNotMatchOutsideComment(code, forbiddenChars) {
  6533. let nextMatch;
  6534. while ((nextMatch = forbiddenChars.exec(code)) !== null) {
  6535. if (nextMatch[0] === '/') {
  6536. const charCodeAfterSlash = code.charCodeAt(forbiddenChars.lastIndex);
  6537. if (charCodeAfterSlash === 42 /*"*"*/) {
  6538. forbiddenChars.lastIndex = code.indexOf('*/', forbiddenChars.lastIndex + 1) + 2;
  6539. continue;
  6540. }
  6541. else if (charCodeAfterSlash === 47 /*"/"*/) {
  6542. forbiddenChars.lastIndex = code.indexOf('\n', forbiddenChars.lastIndex + 1) + 1;
  6543. continue;
  6544. }
  6545. }
  6546. forbiddenChars.lastIndex = 0;
  6547. return false;
  6548. }
  6549. return true;
  6550. }
  6551. const annotationsRegexes = [
  6552. ['pure', /[#@]__PURE__/],
  6553. ['noSideEffects', /[#@]__NO_SIDE_EFFECTS__/]
  6554. ];
  6555. function addAnnotations(comments, esTreeAst, code) {
  6556. const annotations = [];
  6557. const sourceMappingComments = [];
  6558. for (const comment of comments) {
  6559. for (const [annotationType, regex] of annotationsRegexes) {
  6560. if (regex.test(comment.value)) {
  6561. annotations.push({ ...comment, annotationType });
  6562. }
  6563. }
  6564. if (SOURCEMAPPING_URL_RE.test(comment.value)) {
  6565. sourceMappingComments.push(comment);
  6566. }
  6567. }
  6568. for (const comment of sourceMappingComments) {
  6569. annotateNode(esTreeAst, comment, false);
  6570. }
  6571. handlePureAnnotationsOfNode(esTreeAst, {
  6572. annotationIndex: 0,
  6573. annotations,
  6574. code
  6575. });
  6576. }
  6577. function annotateNode(node, comment, valid) {
  6578. const key = valid ? ANNOTATION_KEY : INVALID_COMMENT_KEY;
  6579. const property = node[key];
  6580. if (property) {
  6581. property.push(comment);
  6582. }
  6583. else {
  6584. node[key] = [comment];
  6585. }
  6586. }
  6587. const keys = {
  6588. // TODO this should be removed once ImportExpression follows official ESTree
  6589. // specs with "null" as default
  6590. ImportExpression: ['arguments'],
  6591. Literal: [],
  6592. Program: ['body']
  6593. };
  6594. function getAndCreateKeys(esTreeNode) {
  6595. keys[esTreeNode.type] = Object.keys(esTreeNode).filter(key => typeof esTreeNode[key] === 'object' && key.charCodeAt(0) !== 95 /* _ */);
  6596. return keys[esTreeNode.type];
  6597. }
  6598. const INCLUDE_PARAMETERS = 'variables';
  6599. class NodeBase extends ExpressionEntity {
  6600. constructor(esTreeNode, parent, parentScope, keepEsTreeNode = false) {
  6601. super();
  6602. /**
  6603. * Nodes can apply custom deoptimizations once they become part of the
  6604. * executed code. To do this, they must initialize this as false, implement
  6605. * applyDeoptimizations and call this from include and hasEffects if they have
  6606. * custom handlers
  6607. */
  6608. this.deoptimized = false;
  6609. // Nodes can opt-in to keep the AST if needed during the build pipeline.
  6610. // Avoid true when possible as large AST takes up memory.
  6611. this.esTreeNode = keepEsTreeNode ? esTreeNode : null;
  6612. this.keys = keys[esTreeNode.type] || getAndCreateKeys(esTreeNode);
  6613. this.parent = parent;
  6614. this.context = parent.context;
  6615. this.createScope(parentScope);
  6616. this.parseNode(esTreeNode);
  6617. this.initialise();
  6618. this.context.magicString.addSourcemapLocation(this.start);
  6619. this.context.magicString.addSourcemapLocation(this.end);
  6620. }
  6621. addExportedVariables(_variables, _exportNamesByVariable) { }
  6622. /**
  6623. * Override this to bind assignments to variables and do any initialisations
  6624. * that require the scopes to be populated with variables.
  6625. */
  6626. bind() {
  6627. for (const key of this.keys) {
  6628. const value = this[key];
  6629. if (Array.isArray(value)) {
  6630. for (const child of value) {
  6631. child?.bind();
  6632. }
  6633. }
  6634. else if (value) {
  6635. value.bind();
  6636. }
  6637. }
  6638. }
  6639. /**
  6640. * Override if this node should receive a different scope than the parent
  6641. * scope.
  6642. */
  6643. createScope(parentScope) {
  6644. this.scope = parentScope;
  6645. }
  6646. hasEffects(context) {
  6647. if (!this.deoptimized)
  6648. this.applyDeoptimizations();
  6649. for (const key of this.keys) {
  6650. const value = this[key];
  6651. if (value === null)
  6652. continue;
  6653. if (Array.isArray(value)) {
  6654. for (const child of value) {
  6655. if (child?.hasEffects(context))
  6656. return true;
  6657. }
  6658. }
  6659. else if (value.hasEffects(context))
  6660. return true;
  6661. }
  6662. return false;
  6663. }
  6664. hasEffectsAsAssignmentTarget(context, _checkAccess) {
  6665. return (this.hasEffects(context) ||
  6666. this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
  6667. }
  6668. include(context, includeChildrenRecursively, _options) {
  6669. if (!this.deoptimized)
  6670. this.applyDeoptimizations();
  6671. this.included = true;
  6672. for (const key of this.keys) {
  6673. const value = this[key];
  6674. if (value === null)
  6675. continue;
  6676. if (Array.isArray(value)) {
  6677. for (const child of value) {
  6678. child?.include(context, includeChildrenRecursively);
  6679. }
  6680. }
  6681. else {
  6682. value.include(context, includeChildrenRecursively);
  6683. }
  6684. }
  6685. }
  6686. includeAsAssignmentTarget(context, includeChildrenRecursively, _deoptimizeAccess) {
  6687. this.include(context, includeChildrenRecursively);
  6688. }
  6689. /**
  6690. * Override to perform special initialisation steps after the scope is
  6691. * initialised
  6692. */
  6693. initialise() { }
  6694. insertSemicolon(code) {
  6695. if (code.original[this.end - 1] !== ';') {
  6696. code.appendLeft(this.end, ';');
  6697. }
  6698. }
  6699. parseNode(esTreeNode, keepEsTreeNodeKeys) {
  6700. for (const [key, value] of Object.entries(esTreeNode)) {
  6701. // That way, we can override this function to add custom initialisation and then call super.parseNode
  6702. if (this.hasOwnProperty(key))
  6703. continue;
  6704. if (key.charCodeAt(0) === 95 /* _ */) {
  6705. if (key === ANNOTATION_KEY) {
  6706. const annotations = value;
  6707. this.annotations = annotations;
  6708. if (this.context.options.treeshake.annotations) {
  6709. this.annotationNoSideEffects = annotations.some(comment => comment.annotationType === 'noSideEffects');
  6710. this.annotationPure = annotations.some(comment => comment.annotationType === 'pure');
  6711. }
  6712. }
  6713. else if (key === INVALID_COMMENT_KEY) {
  6714. for (const { start, end } of value)
  6715. this.context.magicString.remove(start, end);
  6716. }
  6717. }
  6718. else if (typeof value !== 'object' || value === null) {
  6719. this[key] = value;
  6720. }
  6721. else if (Array.isArray(value)) {
  6722. this[key] = [];
  6723. for (const child of value) {
  6724. this[key].push(child === null
  6725. ? null
  6726. : new (this.context.getNodeConstructor(child.type))(child, this, this.scope, keepEsTreeNodeKeys?.includes(key)));
  6727. }
  6728. }
  6729. else {
  6730. this[key] = new (this.context.getNodeConstructor(value.type))(value, this, this.scope, keepEsTreeNodeKeys?.includes(key));
  6731. }
  6732. }
  6733. }
  6734. render(code, options) {
  6735. for (const key of this.keys) {
  6736. const value = this[key];
  6737. if (value === null)
  6738. continue;
  6739. if (Array.isArray(value)) {
  6740. for (const child of value) {
  6741. child?.render(code, options);
  6742. }
  6743. }
  6744. else {
  6745. value.render(code, options);
  6746. }
  6747. }
  6748. }
  6749. setAssignedValue(value) {
  6750. this.assignmentInteraction = { args: [null, value], type: INTERACTION_ASSIGNED };
  6751. }
  6752. shouldBeIncluded(context) {
  6753. return this.included || (!context.brokenFlow && this.hasEffects(createHasEffectsContext()));
  6754. }
  6755. /**
  6756. * Just deoptimize everything by default so that when e.g. we do not track
  6757. * something properly, it is deoptimized.
  6758. * @protected
  6759. */
  6760. applyDeoptimizations() {
  6761. this.deoptimized = true;
  6762. for (const key of this.keys) {
  6763. const value = this[key];
  6764. if (value === null)
  6765. continue;
  6766. if (Array.isArray(value)) {
  6767. for (const child of value) {
  6768. child?.deoptimizePath(UNKNOWN_PATH);
  6769. }
  6770. }
  6771. else {
  6772. value.deoptimizePath(UNKNOWN_PATH);
  6773. }
  6774. }
  6775. this.context.requestTreeshakingPass();
  6776. }
  6777. }
  6778. class SpreadElement extends NodeBase {
  6779. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  6780. if (path.length > 0) {
  6781. this.argument.deoptimizeArgumentsOnInteractionAtPath(interaction, [UnknownKey, ...path], recursionTracker);
  6782. }
  6783. }
  6784. hasEffects(context) {
  6785. if (!this.deoptimized)
  6786. this.applyDeoptimizations();
  6787. const { propertyReadSideEffects } = this.context.options
  6788. .treeshake;
  6789. return (this.argument.hasEffects(context) ||
  6790. (propertyReadSideEffects &&
  6791. (propertyReadSideEffects === 'always' ||
  6792. this.argument.hasEffectsOnInteractionAtPath(UNKNOWN_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context))));
  6793. }
  6794. applyDeoptimizations() {
  6795. this.deoptimized = true;
  6796. // Only properties of properties of the argument could become subject to reassignment
  6797. // This will also reassign the return values of iterators
  6798. this.argument.deoptimizePath([UnknownKey, UnknownKey]);
  6799. this.context.requestTreeshakingPass();
  6800. }
  6801. }
  6802. class Method extends ExpressionEntity {
  6803. constructor(description) {
  6804. super();
  6805. this.description = description;
  6806. }
  6807. deoptimizeArgumentsOnInteractionAtPath({ args, type }, path) {
  6808. if (type === INTERACTION_CALLED && path.length === 0 && this.description.mutatesSelfAsArray) {
  6809. args[0]?.deoptimizePath(UNKNOWN_INTEGER_PATH);
  6810. }
  6811. }
  6812. getReturnExpressionWhenCalledAtPath(path, { args }) {
  6813. if (path.length > 0) {
  6814. return UNKNOWN_RETURN_EXPRESSION;
  6815. }
  6816. return [
  6817. this.description.returnsPrimitive ||
  6818. (this.description.returns === 'self'
  6819. ? args[0] || UNKNOWN_EXPRESSION
  6820. : this.description.returns()),
  6821. false
  6822. ];
  6823. }
  6824. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6825. const { type } = interaction;
  6826. if (path.length > (type === INTERACTION_ACCESSED ? 1 : 0)) {
  6827. return true;
  6828. }
  6829. if (type === INTERACTION_CALLED) {
  6830. const { args } = interaction;
  6831. if (this.description.mutatesSelfAsArray === true &&
  6832. args[0]?.hasEffectsOnInteractionAtPath(UNKNOWN_INTEGER_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context)) {
  6833. return true;
  6834. }
  6835. if (this.description.callsArgs) {
  6836. for (const argumentIndex of this.description.callsArgs) {
  6837. if (args[argumentIndex + 1]?.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)) {
  6838. return true;
  6839. }
  6840. }
  6841. }
  6842. }
  6843. return false;
  6844. }
  6845. }
  6846. const METHOD_RETURNS_BOOLEAN = [
  6847. new Method({
  6848. callsArgs: null,
  6849. mutatesSelfAsArray: false,
  6850. returns: null,
  6851. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  6852. })
  6853. ];
  6854. const METHOD_RETURNS_STRING = [
  6855. new Method({
  6856. callsArgs: null,
  6857. mutatesSelfAsArray: false,
  6858. returns: null,
  6859. returnsPrimitive: UNKNOWN_LITERAL_STRING
  6860. })
  6861. ];
  6862. const METHOD_RETURNS_NUMBER = [
  6863. new Method({
  6864. callsArgs: null,
  6865. mutatesSelfAsArray: false,
  6866. returns: null,
  6867. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  6868. })
  6869. ];
  6870. const METHOD_RETURNS_UNKNOWN = [
  6871. new Method({
  6872. callsArgs: null,
  6873. mutatesSelfAsArray: false,
  6874. returns: null,
  6875. returnsPrimitive: UNKNOWN_EXPRESSION
  6876. })
  6877. ];
  6878. const INTEGER_REG_EXP = /^\d+$/;
  6879. class ObjectEntity extends ExpressionEntity {
  6880. // If a PropertyMap is used, this will be taken as propertiesAndGettersByKey
  6881. // and we assume there are no setters or getters
  6882. constructor(properties, prototypeExpression, immutable = false) {
  6883. super();
  6884. this.prototypeExpression = prototypeExpression;
  6885. this.immutable = immutable;
  6886. this.additionalExpressionsToBeDeoptimized = new Set();
  6887. this.allProperties = [];
  6888. this.deoptimizedPaths = Object.create(null);
  6889. this.expressionsToBeDeoptimizedByKey = Object.create(null);
  6890. this.gettersByKey = Object.create(null);
  6891. this.hasLostTrack = false;
  6892. this.hasUnknownDeoptimizedInteger = false;
  6893. this.hasUnknownDeoptimizedProperty = false;
  6894. this.propertiesAndGettersByKey = Object.create(null);
  6895. this.propertiesAndSettersByKey = Object.create(null);
  6896. this.settersByKey = Object.create(null);
  6897. this.unknownIntegerProps = [];
  6898. this.unmatchableGetters = [];
  6899. this.unmatchablePropertiesAndGetters = [];
  6900. this.unmatchableSetters = [];
  6901. if (Array.isArray(properties)) {
  6902. this.buildPropertyMaps(properties);
  6903. }
  6904. else {
  6905. this.propertiesAndGettersByKey = this.propertiesAndSettersByKey = properties;
  6906. for (const propertiesForKey of Object.values(properties)) {
  6907. this.allProperties.push(...propertiesForKey);
  6908. }
  6909. }
  6910. }
  6911. deoptimizeAllProperties(noAccessors) {
  6912. const isDeoptimized = this.hasLostTrack || this.hasUnknownDeoptimizedProperty;
  6913. if (noAccessors) {
  6914. this.hasUnknownDeoptimizedProperty = true;
  6915. }
  6916. else {
  6917. this.hasLostTrack = true;
  6918. }
  6919. if (isDeoptimized) {
  6920. return;
  6921. }
  6922. for (const properties of [
  6923. ...Object.values(this.propertiesAndGettersByKey),
  6924. ...Object.values(this.settersByKey)
  6925. ]) {
  6926. for (const property of properties) {
  6927. property.deoptimizePath(UNKNOWN_PATH);
  6928. }
  6929. }
  6930. // While the prototype itself cannot be mutated, each property can
  6931. this.prototypeExpression?.deoptimizePath([UnknownKey, UnknownKey]);
  6932. this.deoptimizeCachedEntities();
  6933. }
  6934. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  6935. const [key, ...subPath] = path;
  6936. const { args, type } = interaction;
  6937. if (this.hasLostTrack ||
  6938. // single paths that are deoptimized will not become getters or setters
  6939. ((type === INTERACTION_CALLED || path.length > 1) &&
  6940. (this.hasUnknownDeoptimizedProperty ||
  6941. (typeof key === 'string' && this.deoptimizedPaths[key])))) {
  6942. deoptimizeInteraction(interaction);
  6943. return;
  6944. }
  6945. const [propertiesForExactMatchByKey, relevantPropertiesByKey, relevantUnmatchableProperties] = type === INTERACTION_CALLED || path.length > 1
  6946. ? [
  6947. this.propertiesAndGettersByKey,
  6948. this.propertiesAndGettersByKey,
  6949. this.unmatchablePropertiesAndGetters
  6950. ]
  6951. : type === INTERACTION_ACCESSED
  6952. ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters]
  6953. : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters];
  6954. if (typeof key === 'string') {
  6955. if (propertiesForExactMatchByKey[key]) {
  6956. const properties = relevantPropertiesByKey[key];
  6957. if (properties) {
  6958. for (const property of properties) {
  6959. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  6960. }
  6961. }
  6962. if (!this.immutable) {
  6963. for (const argument of args) {
  6964. if (argument) {
  6965. this.additionalExpressionsToBeDeoptimized.add(argument);
  6966. }
  6967. }
  6968. }
  6969. return;
  6970. }
  6971. for (const property of relevantUnmatchableProperties) {
  6972. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  6973. }
  6974. if (INTEGER_REG_EXP.test(key)) {
  6975. for (const property of this.unknownIntegerProps) {
  6976. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  6977. }
  6978. }
  6979. }
  6980. else {
  6981. for (const properties of [
  6982. ...Object.values(relevantPropertiesByKey),
  6983. relevantUnmatchableProperties
  6984. ]) {
  6985. for (const property of properties) {
  6986. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  6987. }
  6988. }
  6989. for (const property of this.unknownIntegerProps) {
  6990. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  6991. }
  6992. }
  6993. if (!this.immutable) {
  6994. for (const argument of args) {
  6995. if (argument) {
  6996. this.additionalExpressionsToBeDeoptimized.add(argument);
  6997. }
  6998. }
  6999. }
  7000. this.prototypeExpression?.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  7001. }
  7002. deoptimizeIntegerProperties() {
  7003. if (this.hasLostTrack ||
  7004. this.hasUnknownDeoptimizedProperty ||
  7005. this.hasUnknownDeoptimizedInteger) {
  7006. return;
  7007. }
  7008. this.hasUnknownDeoptimizedInteger = true;
  7009. for (const [key, propertiesAndGetters] of Object.entries(this.propertiesAndGettersByKey)) {
  7010. if (INTEGER_REG_EXP.test(key)) {
  7011. for (const property of propertiesAndGetters) {
  7012. property.deoptimizePath(UNKNOWN_PATH);
  7013. }
  7014. }
  7015. }
  7016. this.deoptimizeCachedIntegerEntities();
  7017. }
  7018. // Assumption: If only a specific path is deoptimized, no accessors are created
  7019. deoptimizePath(path) {
  7020. if (this.hasLostTrack || this.immutable) {
  7021. return;
  7022. }
  7023. const key = path[0];
  7024. if (path.length === 1) {
  7025. if (typeof key !== 'string') {
  7026. if (key === UnknownInteger) {
  7027. return this.deoptimizeIntegerProperties();
  7028. }
  7029. return this.deoptimizeAllProperties(key === UnknownNonAccessorKey);
  7030. }
  7031. if (!this.deoptimizedPaths[key]) {
  7032. this.deoptimizedPaths[key] = true;
  7033. // we only deoptimizeCache exact matches as in all other cases,
  7034. // we do not return a literal value or return expression
  7035. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimizedByKey[key];
  7036. if (expressionsToBeDeoptimized) {
  7037. for (const expression of expressionsToBeDeoptimized) {
  7038. expression.deoptimizeCache();
  7039. }
  7040. }
  7041. }
  7042. }
  7043. const subPath = path.length === 1 ? UNKNOWN_PATH : path.slice(1);
  7044. for (const property of typeof key === 'string'
  7045. ? [
  7046. ...(this.propertiesAndGettersByKey[key] || this.unmatchablePropertiesAndGetters),
  7047. ...(this.settersByKey[key] || this.unmatchableSetters)
  7048. ]
  7049. : this.allProperties) {
  7050. property.deoptimizePath(subPath);
  7051. }
  7052. this.prototypeExpression?.deoptimizePath(path.length === 1 ? [...path, UnknownKey] : path);
  7053. }
  7054. getLiteralValueAtPath(path, recursionTracker, origin) {
  7055. if (path.length === 0) {
  7056. return UnknownTruthyValue;
  7057. }
  7058. const key = path[0];
  7059. const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
  7060. if (expressionAtPath) {
  7061. return expressionAtPath.getLiteralValueAtPath(path.slice(1), recursionTracker, origin);
  7062. }
  7063. if (this.prototypeExpression) {
  7064. return this.prototypeExpression.getLiteralValueAtPath(path, recursionTracker, origin);
  7065. }
  7066. if (path.length === 1) {
  7067. return undefined;
  7068. }
  7069. return UnknownValue;
  7070. }
  7071. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  7072. if (path.length === 0) {
  7073. return UNKNOWN_RETURN_EXPRESSION;
  7074. }
  7075. const [key, ...subPath] = path;
  7076. const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
  7077. if (expressionAtPath) {
  7078. return expressionAtPath.getReturnExpressionWhenCalledAtPath(subPath, interaction, recursionTracker, origin);
  7079. }
  7080. if (this.prototypeExpression) {
  7081. return this.prototypeExpression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  7082. }
  7083. return UNKNOWN_RETURN_EXPRESSION;
  7084. }
  7085. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7086. const [key, ...subPath] = path;
  7087. if (subPath.length > 0 || interaction.type === INTERACTION_CALLED) {
  7088. const expressionAtPath = this.getMemberExpression(key);
  7089. if (expressionAtPath) {
  7090. return expressionAtPath.hasEffectsOnInteractionAtPath(subPath, interaction, context);
  7091. }
  7092. if (this.prototypeExpression) {
  7093. return this.prototypeExpression.hasEffectsOnInteractionAtPath(path, interaction, context);
  7094. }
  7095. return true;
  7096. }
  7097. if (key === UnknownNonAccessorKey)
  7098. return false;
  7099. if (this.hasLostTrack)
  7100. return true;
  7101. const [propertiesAndAccessorsByKey, accessorsByKey, unmatchableAccessors] = interaction.type === INTERACTION_ACCESSED
  7102. ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters]
  7103. : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters];
  7104. if (typeof key === 'string') {
  7105. if (propertiesAndAccessorsByKey[key]) {
  7106. const accessors = accessorsByKey[key];
  7107. if (accessors) {
  7108. for (const accessor of accessors) {
  7109. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context))
  7110. return true;
  7111. }
  7112. }
  7113. return false;
  7114. }
  7115. for (const accessor of unmatchableAccessors) {
  7116. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context)) {
  7117. return true;
  7118. }
  7119. }
  7120. }
  7121. else {
  7122. for (const accessors of [...Object.values(accessorsByKey), unmatchableAccessors]) {
  7123. for (const accessor of accessors) {
  7124. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context))
  7125. return true;
  7126. }
  7127. }
  7128. }
  7129. if (this.prototypeExpression) {
  7130. return this.prototypeExpression.hasEffectsOnInteractionAtPath(path, interaction, context);
  7131. }
  7132. return false;
  7133. }
  7134. buildPropertyMaps(properties) {
  7135. const { allProperties, propertiesAndGettersByKey, propertiesAndSettersByKey, settersByKey, gettersByKey, unknownIntegerProps, unmatchablePropertiesAndGetters, unmatchableGetters, unmatchableSetters } = this;
  7136. const unmatchablePropertiesAndSetters = [];
  7137. for (let index = properties.length - 1; index >= 0; index--) {
  7138. const { key, kind, property } = properties[index];
  7139. allProperties.push(property);
  7140. if (typeof key === 'string') {
  7141. if (kind === 'set') {
  7142. if (!propertiesAndSettersByKey[key]) {
  7143. propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters];
  7144. settersByKey[key] = [property, ...unmatchableSetters];
  7145. }
  7146. }
  7147. else if (kind === 'get') {
  7148. if (!propertiesAndGettersByKey[key]) {
  7149. propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters];
  7150. gettersByKey[key] = [property, ...unmatchableGetters];
  7151. }
  7152. }
  7153. else {
  7154. if (!propertiesAndSettersByKey[key]) {
  7155. propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters];
  7156. }
  7157. if (!propertiesAndGettersByKey[key]) {
  7158. propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters];
  7159. }
  7160. }
  7161. }
  7162. else {
  7163. if (key === UnknownInteger) {
  7164. unknownIntegerProps.push(property);
  7165. continue;
  7166. }
  7167. if (kind === 'set')
  7168. unmatchableSetters.push(property);
  7169. if (kind === 'get')
  7170. unmatchableGetters.push(property);
  7171. if (kind !== 'get')
  7172. unmatchablePropertiesAndSetters.push(property);
  7173. if (kind !== 'set')
  7174. unmatchablePropertiesAndGetters.push(property);
  7175. }
  7176. }
  7177. }
  7178. deoptimizeCachedEntities() {
  7179. for (const expressionsToBeDeoptimized of Object.values(this.expressionsToBeDeoptimizedByKey)) {
  7180. for (const expression of expressionsToBeDeoptimized) {
  7181. expression.deoptimizeCache();
  7182. }
  7183. }
  7184. for (const expression of this.additionalExpressionsToBeDeoptimized) {
  7185. expression.deoptimizePath(UNKNOWN_PATH);
  7186. }
  7187. }
  7188. deoptimizeCachedIntegerEntities() {
  7189. for (const [key, expressionsToBeDeoptimized] of Object.entries(this.expressionsToBeDeoptimizedByKey)) {
  7190. if (INTEGER_REG_EXP.test(key)) {
  7191. for (const expression of expressionsToBeDeoptimized) {
  7192. expression.deoptimizeCache();
  7193. }
  7194. }
  7195. }
  7196. for (const expression of this.additionalExpressionsToBeDeoptimized) {
  7197. expression.deoptimizePath(UNKNOWN_INTEGER_PATH);
  7198. }
  7199. }
  7200. getMemberExpression(key) {
  7201. if (this.hasLostTrack ||
  7202. this.hasUnknownDeoptimizedProperty ||
  7203. typeof key !== 'string' ||
  7204. (this.hasUnknownDeoptimizedInteger && INTEGER_REG_EXP.test(key)) ||
  7205. this.deoptimizedPaths[key]) {
  7206. return UNKNOWN_EXPRESSION;
  7207. }
  7208. const properties = this.propertiesAndGettersByKey[key];
  7209. if (properties?.length === 1) {
  7210. return properties[0];
  7211. }
  7212. if (properties ||
  7213. this.unmatchablePropertiesAndGetters.length > 0 ||
  7214. (this.unknownIntegerProps.length > 0 && INTEGER_REG_EXP.test(key))) {
  7215. return UNKNOWN_EXPRESSION;
  7216. }
  7217. return null;
  7218. }
  7219. getMemberExpressionAndTrackDeopt(key, origin) {
  7220. if (typeof key !== 'string') {
  7221. return UNKNOWN_EXPRESSION;
  7222. }
  7223. const expression = this.getMemberExpression(key);
  7224. if (!(expression === UNKNOWN_EXPRESSION || this.immutable)) {
  7225. const expressionsToBeDeoptimized = (this.expressionsToBeDeoptimizedByKey[key] =
  7226. this.expressionsToBeDeoptimizedByKey[key] || []);
  7227. expressionsToBeDeoptimized.push(origin);
  7228. }
  7229. return expression;
  7230. }
  7231. }
  7232. const isInteger = (property) => typeof property === 'string' && /^\d+$/.test(property);
  7233. // This makes sure unknown properties are not handled as "undefined" but as
  7234. // "unknown" but without access side effects. An exception is done for numeric
  7235. // properties as we do not expect new builtin properties to be numbers, this
  7236. // will improve tree-shaking for out-of-bounds array properties
  7237. const OBJECT_PROTOTYPE_FALLBACK = new (class ObjectPrototypeFallbackExpression extends ExpressionEntity {
  7238. deoptimizeArgumentsOnInteractionAtPath(interaction, path) {
  7239. if (interaction.type === INTERACTION_CALLED && path.length === 1 && !isInteger(path[0])) {
  7240. deoptimizeInteraction(interaction);
  7241. }
  7242. }
  7243. getLiteralValueAtPath(path) {
  7244. // We ignore number properties as we do not expect new properties to be
  7245. // numbers and also want to keep handling out-of-bound array elements as
  7246. // "undefined"
  7247. return path.length === 1 && isInteger(path[0]) ? undefined : UnknownValue;
  7248. }
  7249. hasEffectsOnInteractionAtPath(path, { type }) {
  7250. return path.length > 1 || type === INTERACTION_CALLED;
  7251. }
  7252. })();
  7253. const OBJECT_PROTOTYPE = new ObjectEntity({
  7254. __proto__: null,
  7255. hasOwnProperty: METHOD_RETURNS_BOOLEAN,
  7256. isPrototypeOf: METHOD_RETURNS_BOOLEAN,
  7257. propertyIsEnumerable: METHOD_RETURNS_BOOLEAN,
  7258. toLocaleString: METHOD_RETURNS_STRING,
  7259. toString: METHOD_RETURNS_STRING,
  7260. valueOf: METHOD_RETURNS_UNKNOWN
  7261. }, OBJECT_PROTOTYPE_FALLBACK, true);
  7262. const NEW_ARRAY_PROPERTIES = [
  7263. { key: UnknownInteger, kind: 'init', property: UNKNOWN_EXPRESSION },
  7264. { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
  7265. ];
  7266. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN = [
  7267. new Method({
  7268. callsArgs: [0],
  7269. mutatesSelfAsArray: 'deopt-only',
  7270. returns: null,
  7271. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  7272. })
  7273. ];
  7274. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER = [
  7275. new Method({
  7276. callsArgs: [0],
  7277. mutatesSelfAsArray: 'deopt-only',
  7278. returns: null,
  7279. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  7280. })
  7281. ];
  7282. const METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY = [
  7283. new Method({
  7284. callsArgs: null,
  7285. mutatesSelfAsArray: true,
  7286. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  7287. returnsPrimitive: null
  7288. })
  7289. ];
  7290. const METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
  7291. new Method({
  7292. callsArgs: null,
  7293. mutatesSelfAsArray: 'deopt-only',
  7294. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  7295. returnsPrimitive: null
  7296. })
  7297. ];
  7298. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
  7299. new Method({
  7300. callsArgs: [0],
  7301. mutatesSelfAsArray: 'deopt-only',
  7302. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  7303. returnsPrimitive: null
  7304. })
  7305. ];
  7306. const METHOD_MUTATES_SELF_RETURNS_NUMBER = [
  7307. new Method({
  7308. callsArgs: null,
  7309. mutatesSelfAsArray: true,
  7310. returns: null,
  7311. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  7312. })
  7313. ];
  7314. const METHOD_MUTATES_SELF_RETURNS_UNKNOWN = [
  7315. new Method({
  7316. callsArgs: null,
  7317. mutatesSelfAsArray: true,
  7318. returns: null,
  7319. returnsPrimitive: UNKNOWN_EXPRESSION
  7320. })
  7321. ];
  7322. const METHOD_DEOPTS_SELF_RETURNS_UNKNOWN = [
  7323. new Method({
  7324. callsArgs: null,
  7325. mutatesSelfAsArray: 'deopt-only',
  7326. returns: null,
  7327. returnsPrimitive: UNKNOWN_EXPRESSION
  7328. })
  7329. ];
  7330. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN = [
  7331. new Method({
  7332. callsArgs: [0],
  7333. mutatesSelfAsArray: 'deopt-only',
  7334. returns: null,
  7335. returnsPrimitive: UNKNOWN_EXPRESSION
  7336. })
  7337. ];
  7338. const METHOD_MUTATES_SELF_RETURNS_SELF = [
  7339. new Method({
  7340. callsArgs: null,
  7341. mutatesSelfAsArray: true,
  7342. returns: 'self',
  7343. returnsPrimitive: null
  7344. })
  7345. ];
  7346. const METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF = [
  7347. new Method({
  7348. callsArgs: [0],
  7349. mutatesSelfAsArray: true,
  7350. returns: 'self',
  7351. returnsPrimitive: null
  7352. })
  7353. ];
  7354. const ARRAY_PROTOTYPE = new ObjectEntity({
  7355. __proto__: null,
  7356. // We assume that accessors have effects as we do not track the accessed value afterwards
  7357. at: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN,
  7358. concat: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  7359. copyWithin: METHOD_MUTATES_SELF_RETURNS_SELF,
  7360. entries: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  7361. every: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN,
  7362. fill: METHOD_MUTATES_SELF_RETURNS_SELF,
  7363. filter: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  7364. find: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  7365. findIndex: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER,
  7366. findLast: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  7367. findLastIndex: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER,
  7368. flat: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  7369. flatMap: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  7370. forEach: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  7371. includes: METHOD_RETURNS_BOOLEAN,
  7372. indexOf: METHOD_RETURNS_NUMBER,
  7373. join: METHOD_RETURNS_STRING,
  7374. keys: METHOD_RETURNS_UNKNOWN,
  7375. lastIndexOf: METHOD_RETURNS_NUMBER,
  7376. map: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  7377. pop: METHOD_MUTATES_SELF_RETURNS_UNKNOWN,
  7378. push: METHOD_MUTATES_SELF_RETURNS_NUMBER,
  7379. reduce: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  7380. reduceRight: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  7381. reverse: METHOD_MUTATES_SELF_RETURNS_SELF,
  7382. shift: METHOD_MUTATES_SELF_RETURNS_UNKNOWN,
  7383. slice: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  7384. some: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN,
  7385. sort: METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF,
  7386. splice: METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY,
  7387. toLocaleString: METHOD_RETURNS_STRING,
  7388. toString: METHOD_RETURNS_STRING,
  7389. unshift: METHOD_MUTATES_SELF_RETURNS_NUMBER,
  7390. values: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN
  7391. }, OBJECT_PROTOTYPE, true);
  7392. class ArrayExpression extends NodeBase {
  7393. constructor() {
  7394. super(...arguments);
  7395. this.objectEntity = null;
  7396. }
  7397. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  7398. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  7399. }
  7400. deoptimizePath(path) {
  7401. this.getObjectEntity().deoptimizePath(path);
  7402. }
  7403. getLiteralValueAtPath(path, recursionTracker, origin) {
  7404. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  7405. }
  7406. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  7407. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  7408. }
  7409. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7410. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  7411. }
  7412. applyDeoptimizations() {
  7413. this.deoptimized = true;
  7414. let hasSpread = false;
  7415. for (let index = 0; index < this.elements.length; index++) {
  7416. const element = this.elements[index];
  7417. if (element && (hasSpread || element instanceof SpreadElement)) {
  7418. hasSpread = true;
  7419. element.deoptimizePath(UNKNOWN_PATH);
  7420. }
  7421. }
  7422. this.context.requestTreeshakingPass();
  7423. }
  7424. getObjectEntity() {
  7425. if (this.objectEntity !== null) {
  7426. return this.objectEntity;
  7427. }
  7428. const properties = [
  7429. { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
  7430. ];
  7431. let hasSpread = false;
  7432. for (let index = 0; index < this.elements.length; index++) {
  7433. const element = this.elements[index];
  7434. if (hasSpread || element instanceof SpreadElement) {
  7435. if (element) {
  7436. hasSpread = true;
  7437. properties.unshift({ key: UnknownInteger, kind: 'init', property: element });
  7438. }
  7439. }
  7440. else if (element) {
  7441. properties.push({ key: String(index), kind: 'init', property: element });
  7442. }
  7443. else {
  7444. properties.push({ key: String(index), kind: 'init', property: UNDEFINED_EXPRESSION });
  7445. }
  7446. }
  7447. return (this.objectEntity = new ObjectEntity(properties, ARRAY_PROTOTYPE));
  7448. }
  7449. }
  7450. class ArrayPattern extends NodeBase {
  7451. addExportedVariables(variables, exportNamesByVariable) {
  7452. for (const element of this.elements) {
  7453. element?.addExportedVariables(variables, exportNamesByVariable);
  7454. }
  7455. }
  7456. declare(kind) {
  7457. const variables = [];
  7458. for (const element of this.elements) {
  7459. if (element !== null) {
  7460. variables.push(...element.declare(kind, UNKNOWN_EXPRESSION));
  7461. }
  7462. }
  7463. return variables;
  7464. }
  7465. // Patterns can only be deoptimized at the empty path at the moment
  7466. deoptimizePath() {
  7467. for (const element of this.elements) {
  7468. element?.deoptimizePath(EMPTY_PATH);
  7469. }
  7470. }
  7471. // Patterns are only checked at the emtpy path at the moment
  7472. hasEffectsOnInteractionAtPath(_path, interaction, context) {
  7473. for (const element of this.elements) {
  7474. if (element?.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context))
  7475. return true;
  7476. }
  7477. return false;
  7478. }
  7479. markDeclarationReached() {
  7480. for (const element of this.elements) {
  7481. element?.markDeclarationReached();
  7482. }
  7483. }
  7484. }
  7485. class LocalVariable extends Variable {
  7486. constructor(name, declarator, init, context) {
  7487. super(name);
  7488. this.init = init;
  7489. this.calledFromTryStatement = false;
  7490. this.additionalInitializers = null;
  7491. this.expressionsToBeDeoptimized = [];
  7492. this.declarations = declarator ? [declarator] : [];
  7493. this.deoptimizationTracker = context.deoptimizationTracker;
  7494. this.module = context.module;
  7495. }
  7496. addDeclaration(identifier, init) {
  7497. this.declarations.push(identifier);
  7498. this.markInitializersForDeoptimization().push(init);
  7499. }
  7500. consolidateInitializers() {
  7501. if (this.additionalInitializers) {
  7502. for (const initializer of this.additionalInitializers) {
  7503. initializer.deoptimizePath(UNKNOWN_PATH);
  7504. }
  7505. this.additionalInitializers = null;
  7506. }
  7507. }
  7508. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  7509. if (this.isReassigned) {
  7510. deoptimizeInteraction(interaction);
  7511. return;
  7512. }
  7513. recursionTracker.withTrackedEntityAtPath(path, this.init, () => this.init.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker), undefined);
  7514. }
  7515. deoptimizePath(path) {
  7516. if (this.isReassigned ||
  7517. this.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  7518. return;
  7519. }
  7520. if (path.length === 0) {
  7521. if (!this.isReassigned) {
  7522. this.isReassigned = true;
  7523. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
  7524. this.expressionsToBeDeoptimized = EMPTY_ARRAY;
  7525. for (const expression of expressionsToBeDeoptimized) {
  7526. expression.deoptimizeCache();
  7527. }
  7528. this.init.deoptimizePath(UNKNOWN_PATH);
  7529. }
  7530. }
  7531. else {
  7532. this.init.deoptimizePath(path);
  7533. }
  7534. }
  7535. getLiteralValueAtPath(path, recursionTracker, origin) {
  7536. if (this.isReassigned) {
  7537. return UnknownValue;
  7538. }
  7539. return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  7540. this.expressionsToBeDeoptimized.push(origin);
  7541. return this.init.getLiteralValueAtPath(path, recursionTracker, origin);
  7542. }, UnknownValue);
  7543. }
  7544. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  7545. if (this.isReassigned) {
  7546. return UNKNOWN_RETURN_EXPRESSION;
  7547. }
  7548. return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  7549. this.expressionsToBeDeoptimized.push(origin);
  7550. return this.init.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  7551. }, UNKNOWN_RETURN_EXPRESSION);
  7552. }
  7553. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7554. switch (interaction.type) {
  7555. case INTERACTION_ACCESSED: {
  7556. if (this.isReassigned)
  7557. return true;
  7558. return (!context.accessed.trackEntityAtPathAndGetIfTracked(path, this) &&
  7559. this.init.hasEffectsOnInteractionAtPath(path, interaction, context));
  7560. }
  7561. case INTERACTION_ASSIGNED: {
  7562. if (this.included)
  7563. return true;
  7564. if (path.length === 0)
  7565. return false;
  7566. if (this.isReassigned)
  7567. return true;
  7568. return (!context.assigned.trackEntityAtPathAndGetIfTracked(path, this) &&
  7569. this.init.hasEffectsOnInteractionAtPath(path, interaction, context));
  7570. }
  7571. case INTERACTION_CALLED: {
  7572. if (this.isReassigned)
  7573. return true;
  7574. return (!(interaction.withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, interaction.args, this) &&
  7575. this.init.hasEffectsOnInteractionAtPath(path, interaction, context));
  7576. }
  7577. }
  7578. }
  7579. include() {
  7580. if (!this.included) {
  7581. this.included = true;
  7582. for (const declaration of this.declarations) {
  7583. // If node is a default export, it can save a tree-shaking run to include the full declaration now
  7584. if (!declaration.included)
  7585. declaration.include(createInclusionContext(), false);
  7586. let node = declaration.parent;
  7587. while (!node.included) {
  7588. // We do not want to properly include parents in case they are part of a dead branch
  7589. // in which case .include() might pull in more dead code
  7590. node.included = true;
  7591. if (node.type === Program$1)
  7592. break;
  7593. node = node.parent;
  7594. }
  7595. }
  7596. }
  7597. }
  7598. includeCallArguments(context, parameters) {
  7599. if (this.isReassigned || context.includedCallArguments.has(this.init)) {
  7600. for (const argument of parameters) {
  7601. argument.include(context, false);
  7602. }
  7603. }
  7604. else {
  7605. context.includedCallArguments.add(this.init);
  7606. this.init.includeCallArguments(context, parameters);
  7607. context.includedCallArguments.delete(this.init);
  7608. }
  7609. }
  7610. markCalledFromTryStatement() {
  7611. this.calledFromTryStatement = true;
  7612. }
  7613. markInitializersForDeoptimization() {
  7614. if (this.additionalInitializers === null) {
  7615. this.additionalInitializers = [this.init];
  7616. this.init = UNKNOWN_EXPRESSION;
  7617. this.isReassigned = true;
  7618. }
  7619. return this.additionalInitializers;
  7620. }
  7621. mergeDeclarations(variable) {
  7622. const { declarations } = this;
  7623. for (const declaration of variable.declarations) {
  7624. declarations.push(declaration);
  7625. }
  7626. const additionalInitializers = this.markInitializersForDeoptimization();
  7627. additionalInitializers.push(variable.init);
  7628. if (variable.additionalInitializers) {
  7629. for (const initializer of variable.additionalInitializers) {
  7630. additionalInitializers.push(initializer);
  7631. }
  7632. }
  7633. }
  7634. }
  7635. const MAX_TRACKED_INTERACTIONS = 20;
  7636. const NO_INTERACTIONS = EMPTY_ARRAY;
  7637. const UNKNOWN_DEOPTIMIZED_FIELD = new Set([UnknownKey]);
  7638. const EMPTY_PATH_TRACKER = new PathTracker();
  7639. const UNKNOWN_DEOPTIMIZED_ENTITY = new Set([UNKNOWN_EXPRESSION]);
  7640. class ParameterVariable extends LocalVariable {
  7641. constructor(name, declarator, context) {
  7642. super(name, declarator, UNKNOWN_EXPRESSION, context);
  7643. this.deoptimizationInteractions = [];
  7644. this.deoptimizations = new PathTracker();
  7645. this.deoptimizedFields = new Set();
  7646. this.entitiesToBeDeoptimized = new Set();
  7647. }
  7648. addEntityToBeDeoptimized(entity) {
  7649. if (entity === UNKNOWN_EXPRESSION) {
  7650. // As unknown expressions fully deoptimize all interactions, we can clear
  7651. // the interaction cache at this point provided we keep this optimization
  7652. // in mind when adding new interactions
  7653. if (!this.entitiesToBeDeoptimized.has(UNKNOWN_EXPRESSION)) {
  7654. this.entitiesToBeDeoptimized.add(UNKNOWN_EXPRESSION);
  7655. for (const { interaction } of this.deoptimizationInteractions) {
  7656. deoptimizeInteraction(interaction);
  7657. }
  7658. this.deoptimizationInteractions = NO_INTERACTIONS;
  7659. }
  7660. }
  7661. else if (this.deoptimizedFields.has(UnknownKey)) {
  7662. // This means that we already deoptimized all interactions and no longer
  7663. // track them
  7664. entity.deoptimizePath(UNKNOWN_PATH);
  7665. }
  7666. else if (!this.entitiesToBeDeoptimized.has(entity)) {
  7667. this.entitiesToBeDeoptimized.add(entity);
  7668. for (const field of this.deoptimizedFields) {
  7669. entity.deoptimizePath([field]);
  7670. }
  7671. for (const { interaction, path } of this.deoptimizationInteractions) {
  7672. entity.deoptimizeArgumentsOnInteractionAtPath(interaction, path, SHARED_RECURSION_TRACKER);
  7673. }
  7674. }
  7675. }
  7676. deoptimizeArgumentsOnInteractionAtPath(interaction, path) {
  7677. // For performance reasons, we fully deoptimize all deeper interactions
  7678. if (path.length >= 2 ||
  7679. this.entitiesToBeDeoptimized.has(UNKNOWN_EXPRESSION) ||
  7680. this.deoptimizationInteractions.length >= MAX_TRACKED_INTERACTIONS ||
  7681. (path.length === 1 &&
  7682. (this.deoptimizedFields.has(UnknownKey) ||
  7683. (interaction.type === INTERACTION_CALLED && this.deoptimizedFields.has(path[0]))))) {
  7684. deoptimizeInteraction(interaction);
  7685. return;
  7686. }
  7687. if (!this.deoptimizations.trackEntityAtPathAndGetIfTracked(path, interaction.args)) {
  7688. for (const entity of this.entitiesToBeDeoptimized) {
  7689. entity.deoptimizeArgumentsOnInteractionAtPath(interaction, path, SHARED_RECURSION_TRACKER);
  7690. }
  7691. if (!this.entitiesToBeDeoptimized.has(UNKNOWN_EXPRESSION)) {
  7692. this.deoptimizationInteractions.push({
  7693. interaction,
  7694. path
  7695. });
  7696. }
  7697. }
  7698. }
  7699. deoptimizePath(path) {
  7700. if (path.length === 0 || this.deoptimizedFields.has(UnknownKey)) {
  7701. return;
  7702. }
  7703. const key = path[0];
  7704. if (this.deoptimizedFields.has(key)) {
  7705. return;
  7706. }
  7707. this.deoptimizedFields.add(key);
  7708. for (const entity of this.entitiesToBeDeoptimized) {
  7709. // We do not need a recursion tracker here as we already track whether
  7710. // this field is deoptimized
  7711. entity.deoptimizePath([key]);
  7712. }
  7713. if (key === UnknownKey) {
  7714. // save some memory
  7715. this.deoptimizationInteractions = NO_INTERACTIONS;
  7716. this.deoptimizations = EMPTY_PATH_TRACKER;
  7717. this.deoptimizedFields = UNKNOWN_DEOPTIMIZED_FIELD;
  7718. this.entitiesToBeDeoptimized = UNKNOWN_DEOPTIMIZED_ENTITY;
  7719. }
  7720. }
  7721. getReturnExpressionWhenCalledAtPath(path) {
  7722. // We deoptimize everything that is called as that will trivially deoptimize
  7723. // the corresponding return expressions as well and avoid badly performing
  7724. // and complicated alternatives
  7725. if (path.length === 0) {
  7726. this.deoptimizePath(UNKNOWN_PATH);
  7727. }
  7728. else if (!this.deoptimizedFields.has(path[0])) {
  7729. this.deoptimizePath([path[0]]);
  7730. }
  7731. return UNKNOWN_RETURN_EXPRESSION;
  7732. }
  7733. }
  7734. function getSafeName(baseName, usedNames, forbiddenNames) {
  7735. let safeName = baseName;
  7736. let count = 1;
  7737. while (usedNames.has(safeName) || RESERVED_NAMES$1.has(safeName) || forbiddenNames?.has(safeName)) {
  7738. safeName = `${baseName}$${toBase64(count++)}`;
  7739. }
  7740. usedNames.add(safeName);
  7741. return safeName;
  7742. }
  7743. let Scope$1 = class Scope {
  7744. constructor() {
  7745. this.children = [];
  7746. this.variables = new Map();
  7747. }
  7748. addDeclaration(identifier, context, init, _isHoisted) {
  7749. const name = identifier.name;
  7750. let variable = this.variables.get(name);
  7751. if (variable) {
  7752. variable.addDeclaration(identifier, init);
  7753. }
  7754. else {
  7755. variable = new LocalVariable(identifier.name, identifier, init || UNDEFINED_EXPRESSION, context);
  7756. this.variables.set(name, variable);
  7757. }
  7758. return variable;
  7759. }
  7760. contains(name) {
  7761. return this.variables.has(name);
  7762. }
  7763. findVariable(_name) {
  7764. throw new Error('Internal Error: findVariable needs to be implemented by a subclass');
  7765. }
  7766. };
  7767. class ChildScope extends Scope$1 {
  7768. constructor(parent) {
  7769. super();
  7770. this.accessedOutsideVariables = new Map();
  7771. this.parent = parent;
  7772. parent.children.push(this);
  7773. }
  7774. addAccessedDynamicImport(importExpression) {
  7775. (this.accessedDynamicImports || (this.accessedDynamicImports = new Set())).add(importExpression);
  7776. if (this.parent instanceof ChildScope) {
  7777. this.parent.addAccessedDynamicImport(importExpression);
  7778. }
  7779. }
  7780. addAccessedGlobals(globals, accessedGlobalsByScope) {
  7781. const accessedGlobals = accessedGlobalsByScope.get(this) || new Set();
  7782. for (const name of globals) {
  7783. accessedGlobals.add(name);
  7784. }
  7785. accessedGlobalsByScope.set(this, accessedGlobals);
  7786. if (this.parent instanceof ChildScope) {
  7787. this.parent.addAccessedGlobals(globals, accessedGlobalsByScope);
  7788. }
  7789. }
  7790. addNamespaceMemberAccess(name, variable) {
  7791. this.accessedOutsideVariables.set(name, variable);
  7792. this.parent.addNamespaceMemberAccess(name, variable);
  7793. }
  7794. addReturnExpression(expression) {
  7795. this.parent instanceof ChildScope && this.parent.addReturnExpression(expression);
  7796. }
  7797. addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope) {
  7798. for (const variable of this.accessedOutsideVariables.values()) {
  7799. if (variable.included) {
  7800. usedNames.add(variable.getBaseVariableName());
  7801. if (format === 'system' && exportNamesByVariable.has(variable)) {
  7802. usedNames.add('exports');
  7803. }
  7804. }
  7805. }
  7806. const accessedGlobals = accessedGlobalsByScope.get(this);
  7807. if (accessedGlobals) {
  7808. for (const name of accessedGlobals) {
  7809. usedNames.add(name);
  7810. }
  7811. }
  7812. }
  7813. contains(name) {
  7814. return this.variables.has(name) || this.parent.contains(name);
  7815. }
  7816. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  7817. const usedNames = new Set();
  7818. this.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
  7819. if (this.accessedDynamicImports) {
  7820. for (const importExpression of this.accessedDynamicImports) {
  7821. if (importExpression.inlineNamespace) {
  7822. usedNames.add(importExpression.inlineNamespace.getBaseVariableName());
  7823. }
  7824. }
  7825. }
  7826. for (const [name, variable] of this.variables) {
  7827. if (variable.included || variable.alwaysRendered) {
  7828. variable.setRenderNames(null, getSafeName(name, usedNames, variable.forbiddenNames));
  7829. }
  7830. }
  7831. for (const scope of this.children) {
  7832. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  7833. }
  7834. }
  7835. findLexicalBoundary() {
  7836. return this.parent.findLexicalBoundary();
  7837. }
  7838. findVariable(name) {
  7839. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  7840. if (knownVariable) {
  7841. return knownVariable;
  7842. }
  7843. const variable = this.parent.findVariable(name);
  7844. this.accessedOutsideVariables.set(name, variable);
  7845. return variable;
  7846. }
  7847. }
  7848. class ParameterScope extends ChildScope {
  7849. constructor(parent, context) {
  7850. super(parent);
  7851. this.parameters = [];
  7852. this.hasRest = false;
  7853. this.context = context;
  7854. this.hoistedBodyVarScope = new ChildScope(this);
  7855. }
  7856. /**
  7857. * Adds a parameter to this scope. Parameters must be added in the correct
  7858. * order, i.e. from left to right.
  7859. */
  7860. addParameterDeclaration(identifier) {
  7861. const { name } = identifier;
  7862. const variable = new ParameterVariable(name, identifier, this.context);
  7863. const localVariable = this.hoistedBodyVarScope.variables.get(name);
  7864. if (localVariable) {
  7865. this.hoistedBodyVarScope.variables.set(name, variable);
  7866. variable.mergeDeclarations(localVariable);
  7867. }
  7868. this.variables.set(name, variable);
  7869. return variable;
  7870. }
  7871. addParameterVariables(parameters, hasRest) {
  7872. this.parameters = parameters;
  7873. for (const parameterList of parameters) {
  7874. for (const parameter of parameterList) {
  7875. parameter.alwaysRendered = true;
  7876. }
  7877. }
  7878. this.hasRest = hasRest;
  7879. }
  7880. includeCallArguments(context, parameters) {
  7881. let calledFromTryStatement = false;
  7882. let argumentIncluded = false;
  7883. const restParameter = this.hasRest && this.parameters[this.parameters.length - 1];
  7884. for (const checkedArgument of parameters) {
  7885. if (checkedArgument instanceof SpreadElement) {
  7886. for (const argument of parameters) {
  7887. argument.include(context, false);
  7888. }
  7889. break;
  7890. }
  7891. }
  7892. for (let index = parameters.length - 1; index >= 0; index--) {
  7893. const parameterVariables = this.parameters[index] || restParameter;
  7894. const argument = parameters[index];
  7895. if (parameterVariables) {
  7896. calledFromTryStatement = false;
  7897. if (parameterVariables.length === 0) {
  7898. // handle empty destructuring
  7899. argumentIncluded = true;
  7900. }
  7901. else {
  7902. for (const variable of parameterVariables) {
  7903. if (variable.included) {
  7904. argumentIncluded = true;
  7905. }
  7906. if (variable.calledFromTryStatement) {
  7907. calledFromTryStatement = true;
  7908. }
  7909. }
  7910. }
  7911. }
  7912. if (!argumentIncluded && argument.shouldBeIncluded(context)) {
  7913. argumentIncluded = true;
  7914. }
  7915. if (argumentIncluded) {
  7916. argument.include(context, calledFromTryStatement);
  7917. }
  7918. }
  7919. }
  7920. }
  7921. class ReturnValueScope extends ParameterScope {
  7922. constructor() {
  7923. super(...arguments);
  7924. this.returnExpression = null;
  7925. this.returnExpressions = [];
  7926. }
  7927. addReturnExpression(expression) {
  7928. this.returnExpressions.push(expression);
  7929. }
  7930. getReturnExpression() {
  7931. if (this.returnExpression === null)
  7932. this.updateReturnExpression();
  7933. return this.returnExpression;
  7934. }
  7935. updateReturnExpression() {
  7936. if (this.returnExpressions.length === 1) {
  7937. this.returnExpression = this.returnExpressions[0];
  7938. }
  7939. else {
  7940. this.returnExpression = UNKNOWN_EXPRESSION;
  7941. for (const expression of this.returnExpressions) {
  7942. expression.deoptimizePath(UNKNOWN_PATH);
  7943. }
  7944. }
  7945. }
  7946. }
  7947. /** @typedef { import('estree').Node} Node */
  7948. /** @typedef {Node | {
  7949. * type: 'PropertyDefinition';
  7950. * computed: boolean;
  7951. * value: Node
  7952. * }} NodeWithPropertyDefinition */
  7953. /**
  7954. *
  7955. * @param {NodeWithPropertyDefinition} node
  7956. * @param {NodeWithPropertyDefinition} parent
  7957. * @returns {boolean}
  7958. */
  7959. function is_reference (node, parent) {
  7960. if (node.type === 'MemberExpression') {
  7961. return !node.computed && is_reference(node.object, node);
  7962. }
  7963. if (node.type === 'Identifier') {
  7964. if (!parent) return true;
  7965. switch (parent.type) {
  7966. // disregard `bar` in `foo.bar`
  7967. case 'MemberExpression': return parent.computed || node === parent.object;
  7968. // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}`
  7969. case 'MethodDefinition': return parent.computed;
  7970. // disregard the `foo` in `class {foo=bar}` but keep it in `class {[foo]=bar}` and `class {bar=foo}`
  7971. case 'PropertyDefinition': return parent.computed || node === parent.value;
  7972. // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
  7973. case 'Property': return parent.computed || node === parent.value;
  7974. // disregard the `bar` in `export { foo as bar }` or
  7975. // the foo in `import { foo as bar }`
  7976. case 'ExportSpecifier':
  7977. case 'ImportSpecifier': return node === parent.local;
  7978. // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}`
  7979. case 'LabeledStatement':
  7980. case 'BreakStatement':
  7981. case 'ContinueStatement': return false;
  7982. default: return true;
  7983. }
  7984. }
  7985. return false;
  7986. }
  7987. const PureFunctionKey = Symbol('PureFunction');
  7988. const getPureFunctions = ({ treeshake }) => {
  7989. const pureFunctions = Object.create(null);
  7990. for (const functionName of treeshake ? treeshake.manualPureFunctions : []) {
  7991. let currentFunctions = pureFunctions;
  7992. for (const pathSegment of functionName.split('.')) {
  7993. currentFunctions = currentFunctions[pathSegment] || (currentFunctions[pathSegment] = Object.create(null));
  7994. }
  7995. currentFunctions[PureFunctionKey] = true;
  7996. }
  7997. return pureFunctions;
  7998. };
  7999. /* eslint sort-keys: "off" */
  8000. const ValueProperties = Symbol('Value Properties');
  8001. const getTruthyLiteralValue = () => UnknownTruthyValue;
  8002. const returnFalse = () => false;
  8003. const returnTrue = () => true;
  8004. const PURE = {
  8005. deoptimizeArgumentsOnCall: doNothing,
  8006. getLiteralValue: getTruthyLiteralValue,
  8007. hasEffectsWhenCalled: returnFalse
  8008. };
  8009. const IMPURE = {
  8010. deoptimizeArgumentsOnCall: doNothing,
  8011. getLiteralValue: getTruthyLiteralValue,
  8012. hasEffectsWhenCalled: returnTrue
  8013. };
  8014. const PURE_WITH_ARRAY = {
  8015. deoptimizeArgumentsOnCall: doNothing,
  8016. getLiteralValue: getTruthyLiteralValue,
  8017. hasEffectsWhenCalled({ args }) {
  8018. return args.length > 1 && !(args[1] instanceof ArrayExpression);
  8019. }
  8020. };
  8021. const GETTER_ACCESS = {
  8022. deoptimizeArgumentsOnCall: doNothing,
  8023. getLiteralValue: getTruthyLiteralValue,
  8024. hasEffectsWhenCalled({ args }, context) {
  8025. const [_thisArgument, firstArgument] = args;
  8026. return (!(firstArgument instanceof ExpressionEntity) ||
  8027. firstArgument.hasEffectsOnInteractionAtPath(UNKNOWN_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context));
  8028. }
  8029. };
  8030. // We use shortened variables to reduce file size here
  8031. /* OBJECT */
  8032. const O = {
  8033. __proto__: null,
  8034. [ValueProperties]: IMPURE
  8035. };
  8036. /* PURE FUNCTION */
  8037. const PF = {
  8038. __proto__: null,
  8039. [ValueProperties]: PURE
  8040. };
  8041. /* PURE FUNCTION IF FIRST ARG DOES NOT CONTAIN A GETTER */
  8042. const PF_NO_GETTER = {
  8043. __proto__: null,
  8044. [ValueProperties]: GETTER_ACCESS
  8045. };
  8046. /* FUNCTION THAT MUTATES FIRST ARG WITHOUT TRIGGERING ACCESSORS */
  8047. const MUTATES_ARG_WITHOUT_ACCESSOR = {
  8048. __proto__: null,
  8049. [ValueProperties]: {
  8050. deoptimizeArgumentsOnCall({ args: [, firstArgument] }) {
  8051. firstArgument?.deoptimizePath(UNKNOWN_PATH);
  8052. },
  8053. getLiteralValue: getTruthyLiteralValue,
  8054. hasEffectsWhenCalled({ args }, context) {
  8055. return (args.length <= 1 ||
  8056. args[1].hasEffectsOnInteractionAtPath(UNKNOWN_NON_ACCESSOR_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context));
  8057. }
  8058. }
  8059. };
  8060. /* CONSTRUCTOR */
  8061. const C = {
  8062. __proto__: null,
  8063. [ValueProperties]: IMPURE,
  8064. prototype: O
  8065. };
  8066. /* PURE CONSTRUCTOR */
  8067. const PC = {
  8068. __proto__: null,
  8069. [ValueProperties]: PURE,
  8070. prototype: O
  8071. };
  8072. const PC_WITH_ARRAY = {
  8073. __proto__: null,
  8074. [ValueProperties]: PURE_WITH_ARRAY,
  8075. prototype: O
  8076. };
  8077. const ARRAY_TYPE = {
  8078. __proto__: null,
  8079. [ValueProperties]: PURE,
  8080. from: O,
  8081. of: PF,
  8082. prototype: O
  8083. };
  8084. const INTL_MEMBER = {
  8085. __proto__: null,
  8086. [ValueProperties]: PURE,
  8087. supportedLocalesOf: PC
  8088. };
  8089. const knownGlobals = {
  8090. // Placeholders for global objects to avoid shape mutations
  8091. global: O,
  8092. globalThis: O,
  8093. self: O,
  8094. window: O,
  8095. // Common globals
  8096. __proto__: null,
  8097. [ValueProperties]: IMPURE,
  8098. Array: {
  8099. __proto__: null,
  8100. [ValueProperties]: IMPURE,
  8101. from: O,
  8102. isArray: PF,
  8103. of: PF,
  8104. prototype: O
  8105. },
  8106. ArrayBuffer: {
  8107. __proto__: null,
  8108. [ValueProperties]: PURE,
  8109. isView: PF,
  8110. prototype: O
  8111. },
  8112. Atomics: O,
  8113. BigInt: C,
  8114. BigInt64Array: C,
  8115. BigUint64Array: C,
  8116. Boolean: PC,
  8117. constructor: C,
  8118. DataView: PC,
  8119. Date: {
  8120. __proto__: null,
  8121. [ValueProperties]: PURE,
  8122. now: PF,
  8123. parse: PF,
  8124. prototype: O,
  8125. UTC: PF
  8126. },
  8127. decodeURI: PF,
  8128. decodeURIComponent: PF,
  8129. encodeURI: PF,
  8130. encodeURIComponent: PF,
  8131. Error: PC,
  8132. escape: PF,
  8133. eval: O,
  8134. EvalError: PC,
  8135. Float32Array: ARRAY_TYPE,
  8136. Float64Array: ARRAY_TYPE,
  8137. Function: C,
  8138. hasOwnProperty: O,
  8139. Infinity: O,
  8140. Int16Array: ARRAY_TYPE,
  8141. Int32Array: ARRAY_TYPE,
  8142. Int8Array: ARRAY_TYPE,
  8143. isFinite: PF,
  8144. isNaN: PF,
  8145. isPrototypeOf: O,
  8146. JSON: O,
  8147. Map: PC_WITH_ARRAY,
  8148. Math: {
  8149. __proto__: null,
  8150. [ValueProperties]: IMPURE,
  8151. abs: PF,
  8152. acos: PF,
  8153. acosh: PF,
  8154. asin: PF,
  8155. asinh: PF,
  8156. atan: PF,
  8157. atan2: PF,
  8158. atanh: PF,
  8159. cbrt: PF,
  8160. ceil: PF,
  8161. clz32: PF,
  8162. cos: PF,
  8163. cosh: PF,
  8164. exp: PF,
  8165. expm1: PF,
  8166. floor: PF,
  8167. fround: PF,
  8168. hypot: PF,
  8169. imul: PF,
  8170. log: PF,
  8171. log10: PF,
  8172. log1p: PF,
  8173. log2: PF,
  8174. max: PF,
  8175. min: PF,
  8176. pow: PF,
  8177. random: PF,
  8178. round: PF,
  8179. sign: PF,
  8180. sin: PF,
  8181. sinh: PF,
  8182. sqrt: PF,
  8183. tan: PF,
  8184. tanh: PF,
  8185. trunc: PF
  8186. },
  8187. NaN: O,
  8188. Number: {
  8189. __proto__: null,
  8190. [ValueProperties]: PURE,
  8191. isFinite: PF,
  8192. isInteger: PF,
  8193. isNaN: PF,
  8194. isSafeInteger: PF,
  8195. parseFloat: PF,
  8196. parseInt: PF,
  8197. prototype: O
  8198. },
  8199. Object: {
  8200. __proto__: null,
  8201. [ValueProperties]: PURE,
  8202. create: PF,
  8203. // Technically those can throw in certain situations, but we ignore this as
  8204. // code that relies on this will hopefully wrap this in a try-catch, which
  8205. // deoptimizes everything anyway
  8206. defineProperty: MUTATES_ARG_WITHOUT_ACCESSOR,
  8207. defineProperties: MUTATES_ARG_WITHOUT_ACCESSOR,
  8208. freeze: MUTATES_ARG_WITHOUT_ACCESSOR,
  8209. getOwnPropertyDescriptor: PF,
  8210. getOwnPropertyDescriptors: PF,
  8211. getOwnPropertyNames: PF,
  8212. getOwnPropertySymbols: PF,
  8213. getPrototypeOf: PF,
  8214. hasOwn: PF,
  8215. is: PF,
  8216. isExtensible: PF,
  8217. isFrozen: PF,
  8218. isSealed: PF,
  8219. keys: PF,
  8220. fromEntries: O,
  8221. entries: PF_NO_GETTER,
  8222. values: PF_NO_GETTER,
  8223. prototype: O
  8224. },
  8225. parseFloat: PF,
  8226. parseInt: PF,
  8227. Promise: {
  8228. __proto__: null,
  8229. [ValueProperties]: IMPURE,
  8230. all: O,
  8231. allSettled: O,
  8232. any: O,
  8233. prototype: O,
  8234. race: O,
  8235. reject: O,
  8236. resolve: O
  8237. },
  8238. propertyIsEnumerable: O,
  8239. Proxy: O,
  8240. RangeError: PC,
  8241. ReferenceError: PC,
  8242. Reflect: O,
  8243. RegExp: PC,
  8244. Set: PC_WITH_ARRAY,
  8245. SharedArrayBuffer: C,
  8246. String: {
  8247. __proto__: null,
  8248. [ValueProperties]: PURE,
  8249. fromCharCode: PF,
  8250. fromCodePoint: PF,
  8251. prototype: O,
  8252. raw: PF
  8253. },
  8254. Symbol: {
  8255. __proto__: null,
  8256. [ValueProperties]: PURE,
  8257. for: PF,
  8258. keyFor: PF,
  8259. prototype: O,
  8260. toStringTag: {
  8261. __proto__: null,
  8262. [ValueProperties]: {
  8263. deoptimizeArgumentsOnCall: doNothing,
  8264. getLiteralValue() {
  8265. return SymbolToStringTag;
  8266. },
  8267. hasEffectsWhenCalled: returnTrue
  8268. }
  8269. }
  8270. },
  8271. SyntaxError: PC,
  8272. toLocaleString: O,
  8273. toString: O,
  8274. TypeError: PC,
  8275. Uint16Array: ARRAY_TYPE,
  8276. Uint32Array: ARRAY_TYPE,
  8277. Uint8Array: ARRAY_TYPE,
  8278. Uint8ClampedArray: ARRAY_TYPE,
  8279. // Technically, this is a global, but it needs special handling
  8280. // undefined: ?,
  8281. unescape: PF,
  8282. URIError: PC,
  8283. valueOf: O,
  8284. WeakMap: PC_WITH_ARRAY,
  8285. WeakSet: PC_WITH_ARRAY,
  8286. // Additional globals shared by Node and Browser that are not strictly part of the language
  8287. clearInterval: C,
  8288. clearTimeout: C,
  8289. console: {
  8290. __proto__: null,
  8291. [ValueProperties]: IMPURE,
  8292. assert: C,
  8293. clear: C,
  8294. count: C,
  8295. countReset: C,
  8296. debug: C,
  8297. dir: C,
  8298. dirxml: C,
  8299. error: C,
  8300. exception: C,
  8301. group: C,
  8302. groupCollapsed: C,
  8303. groupEnd: C,
  8304. info: C,
  8305. log: C,
  8306. table: C,
  8307. time: C,
  8308. timeEnd: C,
  8309. timeLog: C,
  8310. trace: C,
  8311. warn: C
  8312. },
  8313. Intl: {
  8314. __proto__: null,
  8315. [ValueProperties]: IMPURE,
  8316. Collator: INTL_MEMBER,
  8317. DateTimeFormat: INTL_MEMBER,
  8318. DisplayNames: INTL_MEMBER,
  8319. ListFormat: INTL_MEMBER,
  8320. Locale: INTL_MEMBER,
  8321. NumberFormat: INTL_MEMBER,
  8322. PluralRules: INTL_MEMBER,
  8323. RelativeTimeFormat: INTL_MEMBER,
  8324. Segmenter: INTL_MEMBER
  8325. },
  8326. setInterval: C,
  8327. setTimeout: C,
  8328. TextDecoder: C,
  8329. TextEncoder: C,
  8330. URL: {
  8331. __proto__: null,
  8332. [ValueProperties]: IMPURE,
  8333. prototype: O,
  8334. canParse: PF
  8335. },
  8336. URLSearchParams: C,
  8337. // Browser specific globals
  8338. AbortController: C,
  8339. AbortSignal: C,
  8340. addEventListener: O,
  8341. alert: O,
  8342. AnalyserNode: C,
  8343. Animation: C,
  8344. AnimationEvent: C,
  8345. applicationCache: O,
  8346. ApplicationCache: C,
  8347. ApplicationCacheErrorEvent: C,
  8348. atob: O,
  8349. Attr: C,
  8350. Audio: C,
  8351. AudioBuffer: C,
  8352. AudioBufferSourceNode: C,
  8353. AudioContext: C,
  8354. AudioDestinationNode: C,
  8355. AudioListener: C,
  8356. AudioNode: C,
  8357. AudioParam: C,
  8358. AudioProcessingEvent: C,
  8359. AudioScheduledSourceNode: C,
  8360. AudioWorkletNode: C,
  8361. BarProp: C,
  8362. BaseAudioContext: C,
  8363. BatteryManager: C,
  8364. BeforeUnloadEvent: C,
  8365. BiquadFilterNode: C,
  8366. Blob: C,
  8367. BlobEvent: C,
  8368. blur: O,
  8369. BroadcastChannel: C,
  8370. btoa: O,
  8371. ByteLengthQueuingStrategy: C,
  8372. Cache: C,
  8373. caches: O,
  8374. CacheStorage: C,
  8375. cancelAnimationFrame: O,
  8376. cancelIdleCallback: O,
  8377. CanvasCaptureMediaStreamTrack: C,
  8378. CanvasGradient: C,
  8379. CanvasPattern: C,
  8380. CanvasRenderingContext2D: C,
  8381. ChannelMergerNode: C,
  8382. ChannelSplitterNode: C,
  8383. CharacterData: C,
  8384. clientInformation: O,
  8385. ClipboardEvent: C,
  8386. close: O,
  8387. closed: O,
  8388. CloseEvent: C,
  8389. Comment: C,
  8390. CompositionEvent: C,
  8391. confirm: O,
  8392. ConstantSourceNode: C,
  8393. ConvolverNode: C,
  8394. CountQueuingStrategy: C,
  8395. createImageBitmap: O,
  8396. Credential: C,
  8397. CredentialsContainer: C,
  8398. crypto: O,
  8399. Crypto: C,
  8400. CryptoKey: C,
  8401. CSS: C,
  8402. CSSConditionRule: C,
  8403. CSSFontFaceRule: C,
  8404. CSSGroupingRule: C,
  8405. CSSImportRule: C,
  8406. CSSKeyframeRule: C,
  8407. CSSKeyframesRule: C,
  8408. CSSMediaRule: C,
  8409. CSSNamespaceRule: C,
  8410. CSSPageRule: C,
  8411. CSSRule: C,
  8412. CSSRuleList: C,
  8413. CSSStyleDeclaration: C,
  8414. CSSStyleRule: C,
  8415. CSSStyleSheet: C,
  8416. CSSSupportsRule: C,
  8417. CustomElementRegistry: C,
  8418. customElements: O,
  8419. CustomEvent: {
  8420. __proto__: null,
  8421. [ValueProperties]: {
  8422. deoptimizeArgumentsOnCall({ args }) {
  8423. args[2]?.deoptimizePath(['detail']);
  8424. },
  8425. getLiteralValue: getTruthyLiteralValue,
  8426. hasEffectsWhenCalled: returnFalse
  8427. },
  8428. prototype: O
  8429. },
  8430. DataTransfer: C,
  8431. DataTransferItem: C,
  8432. DataTransferItemList: C,
  8433. defaultstatus: O,
  8434. defaultStatus: O,
  8435. DelayNode: C,
  8436. DeviceMotionEvent: C,
  8437. DeviceOrientationEvent: C,
  8438. devicePixelRatio: O,
  8439. dispatchEvent: O,
  8440. document: O,
  8441. Document: C,
  8442. DocumentFragment: C,
  8443. DocumentType: C,
  8444. DOMError: C,
  8445. DOMException: C,
  8446. DOMImplementation: C,
  8447. DOMMatrix: C,
  8448. DOMMatrixReadOnly: C,
  8449. DOMParser: C,
  8450. DOMPoint: C,
  8451. DOMPointReadOnly: C,
  8452. DOMQuad: C,
  8453. DOMRect: C,
  8454. DOMRectReadOnly: C,
  8455. DOMStringList: C,
  8456. DOMStringMap: C,
  8457. DOMTokenList: C,
  8458. DragEvent: C,
  8459. DynamicsCompressorNode: C,
  8460. Element: C,
  8461. ErrorEvent: C,
  8462. Event: C,
  8463. EventSource: C,
  8464. EventTarget: C,
  8465. external: O,
  8466. fetch: O,
  8467. File: C,
  8468. FileList: C,
  8469. FileReader: C,
  8470. find: O,
  8471. focus: O,
  8472. FocusEvent: C,
  8473. FontFace: C,
  8474. FontFaceSetLoadEvent: C,
  8475. FormData: C,
  8476. frames: O,
  8477. GainNode: C,
  8478. Gamepad: C,
  8479. GamepadButton: C,
  8480. GamepadEvent: C,
  8481. getComputedStyle: O,
  8482. getSelection: O,
  8483. HashChangeEvent: C,
  8484. Headers: C,
  8485. history: O,
  8486. History: C,
  8487. HTMLAllCollection: C,
  8488. HTMLAnchorElement: C,
  8489. HTMLAreaElement: C,
  8490. HTMLAudioElement: C,
  8491. HTMLBaseElement: C,
  8492. HTMLBodyElement: C,
  8493. HTMLBRElement: C,
  8494. HTMLButtonElement: C,
  8495. HTMLCanvasElement: C,
  8496. HTMLCollection: C,
  8497. HTMLContentElement: C,
  8498. HTMLDataElement: C,
  8499. HTMLDataListElement: C,
  8500. HTMLDetailsElement: C,
  8501. HTMLDialogElement: C,
  8502. HTMLDirectoryElement: C,
  8503. HTMLDivElement: C,
  8504. HTMLDListElement: C,
  8505. HTMLDocument: C,
  8506. HTMLElement: C,
  8507. HTMLEmbedElement: C,
  8508. HTMLFieldSetElement: C,
  8509. HTMLFontElement: C,
  8510. HTMLFormControlsCollection: C,
  8511. HTMLFormElement: C,
  8512. HTMLFrameElement: C,
  8513. HTMLFrameSetElement: C,
  8514. HTMLHeadElement: C,
  8515. HTMLHeadingElement: C,
  8516. HTMLHRElement: C,
  8517. HTMLHtmlElement: C,
  8518. HTMLIFrameElement: C,
  8519. HTMLImageElement: C,
  8520. HTMLInputElement: C,
  8521. HTMLLabelElement: C,
  8522. HTMLLegendElement: C,
  8523. HTMLLIElement: C,
  8524. HTMLLinkElement: C,
  8525. HTMLMapElement: C,
  8526. HTMLMarqueeElement: C,
  8527. HTMLMediaElement: C,
  8528. HTMLMenuElement: C,
  8529. HTMLMetaElement: C,
  8530. HTMLMeterElement: C,
  8531. HTMLModElement: C,
  8532. HTMLObjectElement: C,
  8533. HTMLOListElement: C,
  8534. HTMLOptGroupElement: C,
  8535. HTMLOptionElement: C,
  8536. HTMLOptionsCollection: C,
  8537. HTMLOutputElement: C,
  8538. HTMLParagraphElement: C,
  8539. HTMLParamElement: C,
  8540. HTMLPictureElement: C,
  8541. HTMLPreElement: C,
  8542. HTMLProgressElement: C,
  8543. HTMLQuoteElement: C,
  8544. HTMLScriptElement: C,
  8545. HTMLSelectElement: C,
  8546. HTMLShadowElement: C,
  8547. HTMLSlotElement: C,
  8548. HTMLSourceElement: C,
  8549. HTMLSpanElement: C,
  8550. HTMLStyleElement: C,
  8551. HTMLTableCaptionElement: C,
  8552. HTMLTableCellElement: C,
  8553. HTMLTableColElement: C,
  8554. HTMLTableElement: C,
  8555. HTMLTableRowElement: C,
  8556. HTMLTableSectionElement: C,
  8557. HTMLTemplateElement: C,
  8558. HTMLTextAreaElement: C,
  8559. HTMLTimeElement: C,
  8560. HTMLTitleElement: C,
  8561. HTMLTrackElement: C,
  8562. HTMLUListElement: C,
  8563. HTMLUnknownElement: C,
  8564. HTMLVideoElement: C,
  8565. IDBCursor: C,
  8566. IDBCursorWithValue: C,
  8567. IDBDatabase: C,
  8568. IDBFactory: C,
  8569. IDBIndex: C,
  8570. IDBKeyRange: C,
  8571. IDBObjectStore: C,
  8572. IDBOpenDBRequest: C,
  8573. IDBRequest: C,
  8574. IDBTransaction: C,
  8575. IDBVersionChangeEvent: C,
  8576. IdleDeadline: C,
  8577. IIRFilterNode: C,
  8578. Image: C,
  8579. ImageBitmap: C,
  8580. ImageBitmapRenderingContext: C,
  8581. ImageCapture: C,
  8582. ImageData: C,
  8583. indexedDB: O,
  8584. innerHeight: O,
  8585. innerWidth: O,
  8586. InputEvent: C,
  8587. IntersectionObserver: C,
  8588. IntersectionObserverEntry: C,
  8589. isSecureContext: O,
  8590. KeyboardEvent: C,
  8591. KeyframeEffect: C,
  8592. length: O,
  8593. localStorage: O,
  8594. location: O,
  8595. Location: C,
  8596. locationbar: O,
  8597. matchMedia: O,
  8598. MediaDeviceInfo: C,
  8599. MediaDevices: C,
  8600. MediaElementAudioSourceNode: C,
  8601. MediaEncryptedEvent: C,
  8602. MediaError: C,
  8603. MediaKeyMessageEvent: C,
  8604. MediaKeySession: C,
  8605. MediaKeyStatusMap: C,
  8606. MediaKeySystemAccess: C,
  8607. MediaList: C,
  8608. MediaQueryList: C,
  8609. MediaQueryListEvent: C,
  8610. MediaRecorder: C,
  8611. MediaSettingsRange: C,
  8612. MediaSource: C,
  8613. MediaStream: C,
  8614. MediaStreamAudioDestinationNode: C,
  8615. MediaStreamAudioSourceNode: C,
  8616. MediaStreamEvent: C,
  8617. MediaStreamTrack: C,
  8618. MediaStreamTrackEvent: C,
  8619. menubar: O,
  8620. MessageChannel: C,
  8621. MessageEvent: C,
  8622. MessagePort: C,
  8623. MIDIAccess: C,
  8624. MIDIConnectionEvent: C,
  8625. MIDIInput: C,
  8626. MIDIInputMap: C,
  8627. MIDIMessageEvent: C,
  8628. MIDIOutput: C,
  8629. MIDIOutputMap: C,
  8630. MIDIPort: C,
  8631. MimeType: C,
  8632. MimeTypeArray: C,
  8633. MouseEvent: C,
  8634. moveBy: O,
  8635. moveTo: O,
  8636. MutationEvent: C,
  8637. MutationObserver: C,
  8638. MutationRecord: C,
  8639. name: O,
  8640. NamedNodeMap: C,
  8641. NavigationPreloadManager: C,
  8642. navigator: O,
  8643. Navigator: C,
  8644. NetworkInformation: C,
  8645. Node: C,
  8646. NodeFilter: O,
  8647. NodeIterator: C,
  8648. NodeList: C,
  8649. Notification: C,
  8650. OfflineAudioCompletionEvent: C,
  8651. OfflineAudioContext: C,
  8652. offscreenBuffering: O,
  8653. OffscreenCanvas: C,
  8654. open: O,
  8655. openDatabase: O,
  8656. Option: C,
  8657. origin: O,
  8658. OscillatorNode: C,
  8659. outerHeight: O,
  8660. outerWidth: O,
  8661. PageTransitionEvent: C,
  8662. pageXOffset: O,
  8663. pageYOffset: O,
  8664. PannerNode: C,
  8665. parent: O,
  8666. Path2D: C,
  8667. PaymentAddress: C,
  8668. PaymentRequest: C,
  8669. PaymentRequestUpdateEvent: C,
  8670. PaymentResponse: C,
  8671. performance: O,
  8672. Performance: C,
  8673. PerformanceEntry: C,
  8674. PerformanceLongTaskTiming: C,
  8675. PerformanceMark: C,
  8676. PerformanceMeasure: C,
  8677. PerformanceNavigation: C,
  8678. PerformanceNavigationTiming: C,
  8679. PerformanceObserver: C,
  8680. PerformanceObserverEntryList: C,
  8681. PerformancePaintTiming: C,
  8682. PerformanceResourceTiming: C,
  8683. PerformanceTiming: C,
  8684. PeriodicWave: C,
  8685. Permissions: C,
  8686. PermissionStatus: C,
  8687. personalbar: O,
  8688. PhotoCapabilities: C,
  8689. Plugin: C,
  8690. PluginArray: C,
  8691. PointerEvent: C,
  8692. PopStateEvent: C,
  8693. postMessage: O,
  8694. Presentation: C,
  8695. PresentationAvailability: C,
  8696. PresentationConnection: C,
  8697. PresentationConnectionAvailableEvent: C,
  8698. PresentationConnectionCloseEvent: C,
  8699. PresentationConnectionList: C,
  8700. PresentationReceiver: C,
  8701. PresentationRequest: C,
  8702. print: O,
  8703. ProcessingInstruction: C,
  8704. ProgressEvent: C,
  8705. PromiseRejectionEvent: C,
  8706. prompt: O,
  8707. PushManager: C,
  8708. PushSubscription: C,
  8709. PushSubscriptionOptions: C,
  8710. queueMicrotask: O,
  8711. RadioNodeList: C,
  8712. Range: C,
  8713. ReadableStream: C,
  8714. RemotePlayback: C,
  8715. removeEventListener: O,
  8716. Request: C,
  8717. requestAnimationFrame: O,
  8718. requestIdleCallback: O,
  8719. resizeBy: O,
  8720. ResizeObserver: C,
  8721. ResizeObserverEntry: C,
  8722. resizeTo: O,
  8723. Response: C,
  8724. RTCCertificate: C,
  8725. RTCDataChannel: C,
  8726. RTCDataChannelEvent: C,
  8727. RTCDtlsTransport: C,
  8728. RTCIceCandidate: C,
  8729. RTCIceTransport: C,
  8730. RTCPeerConnection: C,
  8731. RTCPeerConnectionIceEvent: C,
  8732. RTCRtpReceiver: C,
  8733. RTCRtpSender: C,
  8734. RTCSctpTransport: C,
  8735. RTCSessionDescription: C,
  8736. RTCStatsReport: C,
  8737. RTCTrackEvent: C,
  8738. screen: O,
  8739. Screen: C,
  8740. screenLeft: O,
  8741. ScreenOrientation: C,
  8742. screenTop: O,
  8743. screenX: O,
  8744. screenY: O,
  8745. ScriptProcessorNode: C,
  8746. scroll: O,
  8747. scrollbars: O,
  8748. scrollBy: O,
  8749. scrollTo: O,
  8750. scrollX: O,
  8751. scrollY: O,
  8752. SecurityPolicyViolationEvent: C,
  8753. Selection: C,
  8754. ServiceWorker: C,
  8755. ServiceWorkerContainer: C,
  8756. ServiceWorkerRegistration: C,
  8757. sessionStorage: O,
  8758. ShadowRoot: C,
  8759. SharedWorker: C,
  8760. SourceBuffer: C,
  8761. SourceBufferList: C,
  8762. speechSynthesis: O,
  8763. SpeechSynthesisEvent: C,
  8764. SpeechSynthesisUtterance: C,
  8765. StaticRange: C,
  8766. status: O,
  8767. statusbar: O,
  8768. StereoPannerNode: C,
  8769. stop: O,
  8770. Storage: C,
  8771. StorageEvent: C,
  8772. StorageManager: C,
  8773. styleMedia: O,
  8774. StyleSheet: C,
  8775. StyleSheetList: C,
  8776. SubtleCrypto: C,
  8777. SVGAElement: C,
  8778. SVGAngle: C,
  8779. SVGAnimatedAngle: C,
  8780. SVGAnimatedBoolean: C,
  8781. SVGAnimatedEnumeration: C,
  8782. SVGAnimatedInteger: C,
  8783. SVGAnimatedLength: C,
  8784. SVGAnimatedLengthList: C,
  8785. SVGAnimatedNumber: C,
  8786. SVGAnimatedNumberList: C,
  8787. SVGAnimatedPreserveAspectRatio: C,
  8788. SVGAnimatedRect: C,
  8789. SVGAnimatedString: C,
  8790. SVGAnimatedTransformList: C,
  8791. SVGAnimateElement: C,
  8792. SVGAnimateMotionElement: C,
  8793. SVGAnimateTransformElement: C,
  8794. SVGAnimationElement: C,
  8795. SVGCircleElement: C,
  8796. SVGClipPathElement: C,
  8797. SVGComponentTransferFunctionElement: C,
  8798. SVGDefsElement: C,
  8799. SVGDescElement: C,
  8800. SVGDiscardElement: C,
  8801. SVGElement: C,
  8802. SVGEllipseElement: C,
  8803. SVGFEBlendElement: C,
  8804. SVGFEColorMatrixElement: C,
  8805. SVGFEComponentTransferElement: C,
  8806. SVGFECompositeElement: C,
  8807. SVGFEConvolveMatrixElement: C,
  8808. SVGFEDiffuseLightingElement: C,
  8809. SVGFEDisplacementMapElement: C,
  8810. SVGFEDistantLightElement: C,
  8811. SVGFEDropShadowElement: C,
  8812. SVGFEFloodElement: C,
  8813. SVGFEFuncAElement: C,
  8814. SVGFEFuncBElement: C,
  8815. SVGFEFuncGElement: C,
  8816. SVGFEFuncRElement: C,
  8817. SVGFEGaussianBlurElement: C,
  8818. SVGFEImageElement: C,
  8819. SVGFEMergeElement: C,
  8820. SVGFEMergeNodeElement: C,
  8821. SVGFEMorphologyElement: C,
  8822. SVGFEOffsetElement: C,
  8823. SVGFEPointLightElement: C,
  8824. SVGFESpecularLightingElement: C,
  8825. SVGFESpotLightElement: C,
  8826. SVGFETileElement: C,
  8827. SVGFETurbulenceElement: C,
  8828. SVGFilterElement: C,
  8829. SVGForeignObjectElement: C,
  8830. SVGGElement: C,
  8831. SVGGeometryElement: C,
  8832. SVGGradientElement: C,
  8833. SVGGraphicsElement: C,
  8834. SVGImageElement: C,
  8835. SVGLength: C,
  8836. SVGLengthList: C,
  8837. SVGLinearGradientElement: C,
  8838. SVGLineElement: C,
  8839. SVGMarkerElement: C,
  8840. SVGMaskElement: C,
  8841. SVGMatrix: C,
  8842. SVGMetadataElement: C,
  8843. SVGMPathElement: C,
  8844. SVGNumber: C,
  8845. SVGNumberList: C,
  8846. SVGPathElement: C,
  8847. SVGPatternElement: C,
  8848. SVGPoint: C,
  8849. SVGPointList: C,
  8850. SVGPolygonElement: C,
  8851. SVGPolylineElement: C,
  8852. SVGPreserveAspectRatio: C,
  8853. SVGRadialGradientElement: C,
  8854. SVGRect: C,
  8855. SVGRectElement: C,
  8856. SVGScriptElement: C,
  8857. SVGSetElement: C,
  8858. SVGStopElement: C,
  8859. SVGStringList: C,
  8860. SVGStyleElement: C,
  8861. SVGSVGElement: C,
  8862. SVGSwitchElement: C,
  8863. SVGSymbolElement: C,
  8864. SVGTextContentElement: C,
  8865. SVGTextElement: C,
  8866. SVGTextPathElement: C,
  8867. SVGTextPositioningElement: C,
  8868. SVGTitleElement: C,
  8869. SVGTransform: C,
  8870. SVGTransformList: C,
  8871. SVGTSpanElement: C,
  8872. SVGUnitTypes: C,
  8873. SVGUseElement: C,
  8874. SVGViewElement: C,
  8875. TaskAttributionTiming: C,
  8876. Text: C,
  8877. TextEvent: C,
  8878. TextMetrics: C,
  8879. TextTrack: C,
  8880. TextTrackCue: C,
  8881. TextTrackCueList: C,
  8882. TextTrackList: C,
  8883. TimeRanges: C,
  8884. toolbar: O,
  8885. top: O,
  8886. Touch: C,
  8887. TouchEvent: C,
  8888. TouchList: C,
  8889. TrackEvent: C,
  8890. TransitionEvent: C,
  8891. TreeWalker: C,
  8892. UIEvent: C,
  8893. ValidityState: C,
  8894. visualViewport: O,
  8895. VisualViewport: C,
  8896. VTTCue: C,
  8897. WaveShaperNode: C,
  8898. WebAssembly: O,
  8899. WebGL2RenderingContext: C,
  8900. WebGLActiveInfo: C,
  8901. WebGLBuffer: C,
  8902. WebGLContextEvent: C,
  8903. WebGLFramebuffer: C,
  8904. WebGLProgram: C,
  8905. WebGLQuery: C,
  8906. WebGLRenderbuffer: C,
  8907. WebGLRenderingContext: C,
  8908. WebGLSampler: C,
  8909. WebGLShader: C,
  8910. WebGLShaderPrecisionFormat: C,
  8911. WebGLSync: C,
  8912. WebGLTexture: C,
  8913. WebGLTransformFeedback: C,
  8914. WebGLUniformLocation: C,
  8915. WebGLVertexArrayObject: C,
  8916. WebSocket: C,
  8917. WheelEvent: C,
  8918. Window: C,
  8919. Worker: C,
  8920. WritableStream: C,
  8921. XMLDocument: C,
  8922. XMLHttpRequest: C,
  8923. XMLHttpRequestEventTarget: C,
  8924. XMLHttpRequestUpload: C,
  8925. XMLSerializer: C,
  8926. XPathEvaluator: C,
  8927. XPathExpression: C,
  8928. XPathResult: C,
  8929. XSLTProcessor: C
  8930. };
  8931. for (const global of ['window', 'global', 'self', 'globalThis']) {
  8932. knownGlobals[global] = knownGlobals;
  8933. }
  8934. function getGlobalAtPath(path) {
  8935. let currentGlobal = knownGlobals;
  8936. for (const pathSegment of path) {
  8937. if (typeof pathSegment !== 'string') {
  8938. return null;
  8939. }
  8940. currentGlobal = currentGlobal[pathSegment];
  8941. if (!currentGlobal) {
  8942. return null;
  8943. }
  8944. }
  8945. return currentGlobal[ValueProperties];
  8946. }
  8947. class GlobalVariable extends Variable {
  8948. constructor() {
  8949. super(...arguments);
  8950. // Ensure we use live-bindings for globals as we do not know if they have
  8951. // been reassigned
  8952. this.isReassigned = true;
  8953. }
  8954. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  8955. switch (interaction.type) {
  8956. // While there is no point in testing these cases as at the moment, they
  8957. // are also covered via other means, we keep them for completeness
  8958. case INTERACTION_ACCESSED:
  8959. case INTERACTION_ASSIGNED: {
  8960. if (!getGlobalAtPath([this.name, ...path].slice(0, -1))) {
  8961. super.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  8962. }
  8963. return;
  8964. }
  8965. case INTERACTION_CALLED: {
  8966. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  8967. if (globalAtPath) {
  8968. globalAtPath.deoptimizeArgumentsOnCall(interaction);
  8969. }
  8970. else {
  8971. super.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  8972. }
  8973. return;
  8974. }
  8975. }
  8976. }
  8977. getLiteralValueAtPath(path, _recursionTracker, _origin) {
  8978. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  8979. return globalAtPath ? globalAtPath.getLiteralValue() : UnknownValue;
  8980. }
  8981. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8982. switch (interaction.type) {
  8983. case INTERACTION_ACCESSED: {
  8984. if (path.length === 0) {
  8985. // Technically, "undefined" is a global variable of sorts
  8986. return this.name !== 'undefined' && !getGlobalAtPath([this.name]);
  8987. }
  8988. return !getGlobalAtPath([this.name, ...path].slice(0, -1));
  8989. }
  8990. case INTERACTION_ASSIGNED: {
  8991. return true;
  8992. }
  8993. case INTERACTION_CALLED: {
  8994. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  8995. return !globalAtPath || globalAtPath.hasEffectsWhenCalled(interaction, context);
  8996. }
  8997. }
  8998. }
  8999. }
  9000. const tdzVariableKinds = {
  9001. __proto__: null,
  9002. class: true,
  9003. const: true,
  9004. let: true,
  9005. var: true
  9006. };
  9007. class Identifier extends NodeBase {
  9008. constructor() {
  9009. super(...arguments);
  9010. this.variable = null;
  9011. this.isTDZAccess = null;
  9012. }
  9013. addExportedVariables(variables, exportNamesByVariable) {
  9014. if (exportNamesByVariable.has(this.variable)) {
  9015. variables.push(this.variable);
  9016. }
  9017. }
  9018. bind() {
  9019. if (!this.variable && is_reference(this, this.parent)) {
  9020. this.variable = this.scope.findVariable(this.name);
  9021. this.variable.addReference(this);
  9022. }
  9023. }
  9024. declare(kind, init) {
  9025. let variable;
  9026. const { treeshake } = this.context.options;
  9027. switch (kind) {
  9028. case 'var': {
  9029. variable = this.scope.addDeclaration(this, this.context, init, true);
  9030. if (treeshake && treeshake.correctVarValueBeforeDeclaration) {
  9031. // Necessary to make sure the init is deoptimized. We cannot call deoptimizePath here.
  9032. variable.markInitializersForDeoptimization();
  9033. }
  9034. break;
  9035. }
  9036. case 'function': {
  9037. // in strict mode, functions are only hoisted within a scope but not across block scopes
  9038. variable = this.scope.addDeclaration(this, this.context, init, false);
  9039. break;
  9040. }
  9041. case 'let':
  9042. case 'const':
  9043. case 'class': {
  9044. variable = this.scope.addDeclaration(this, this.context, init, false);
  9045. break;
  9046. }
  9047. case 'parameter': {
  9048. variable = this.scope.addParameterDeclaration(this);
  9049. break;
  9050. }
  9051. /* istanbul ignore next */
  9052. default: {
  9053. /* istanbul ignore next */
  9054. throw new Error(`Internal Error: Unexpected identifier kind ${kind}.`);
  9055. }
  9056. }
  9057. variable.kind = kind;
  9058. return [(this.variable = variable)];
  9059. }
  9060. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  9061. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  9062. }
  9063. deoptimizePath(path) {
  9064. if (path.length === 0 && !this.scope.contains(this.name)) {
  9065. this.disallowImportReassignment();
  9066. }
  9067. // We keep conditional chaining because an unknown Node could have an
  9068. // Identifier as property that might be deoptimized by default
  9069. this.variable?.deoptimizePath(path);
  9070. }
  9071. getLiteralValueAtPath(path, recursionTracker, origin) {
  9072. return this.getVariableRespectingTDZ().getLiteralValueAtPath(path, recursionTracker, origin);
  9073. }
  9074. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  9075. const [expression, isPure] = this.getVariableRespectingTDZ().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  9076. return [expression, isPure || this.isPureFunction(path)];
  9077. }
  9078. hasEffects(context) {
  9079. if (!this.deoptimized)
  9080. this.applyDeoptimizations();
  9081. if (this.isPossibleTDZ() && this.variable.kind !== 'var') {
  9082. return true;
  9083. }
  9084. return (this.context.options.treeshake.unknownGlobalSideEffects &&
  9085. this.variable instanceof GlobalVariable &&
  9086. !this.isPureFunction(EMPTY_PATH) &&
  9087. this.variable.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context));
  9088. }
  9089. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9090. switch (interaction.type) {
  9091. case INTERACTION_ACCESSED: {
  9092. return (this.variable !== null &&
  9093. !this.isPureFunction(path) &&
  9094. this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context));
  9095. }
  9096. case INTERACTION_ASSIGNED: {
  9097. return (path.length > 0 ? this.getVariableRespectingTDZ() : this.variable).hasEffectsOnInteractionAtPath(path, interaction, context);
  9098. }
  9099. case INTERACTION_CALLED: {
  9100. return (!this.isPureFunction(path) &&
  9101. this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context));
  9102. }
  9103. }
  9104. }
  9105. include() {
  9106. if (!this.deoptimized)
  9107. this.applyDeoptimizations();
  9108. if (!this.included) {
  9109. this.included = true;
  9110. if (this.variable !== null) {
  9111. this.context.includeVariableInModule(this.variable);
  9112. }
  9113. }
  9114. }
  9115. includeCallArguments(context, parameters) {
  9116. this.variable.includeCallArguments(context, parameters);
  9117. }
  9118. isPossibleTDZ() {
  9119. // return cached value to avoid issues with the next tree-shaking pass
  9120. if (this.isTDZAccess !== null)
  9121. return this.isTDZAccess;
  9122. if (!(this.variable instanceof LocalVariable &&
  9123. this.variable.kind &&
  9124. this.variable.kind in tdzVariableKinds &&
  9125. // we ignore possible TDZs due to circular module dependencies as
  9126. // otherwise we get many false positives
  9127. this.variable.module === this.context.module)) {
  9128. return (this.isTDZAccess = false);
  9129. }
  9130. let decl_id;
  9131. if (this.variable.declarations &&
  9132. this.variable.declarations.length === 1 &&
  9133. (decl_id = this.variable.declarations[0]) &&
  9134. this.start < decl_id.start &&
  9135. closestParentFunctionOrProgram(this) === closestParentFunctionOrProgram(decl_id)) {
  9136. // a variable accessed before its declaration
  9137. // in the same function or at top level of module
  9138. return (this.isTDZAccess = true);
  9139. }
  9140. if (!this.variable.initReached) {
  9141. // Either a const/let TDZ violation or
  9142. // var use before declaration was encountered.
  9143. return (this.isTDZAccess = true);
  9144. }
  9145. return (this.isTDZAccess = false);
  9146. }
  9147. markDeclarationReached() {
  9148. this.variable.initReached = true;
  9149. }
  9150. render(code, { snippets: { getPropertyAccess }, useOriginalName }, { renderedParentType, isCalleeOfRenderedParent, isShorthandProperty } = BLANK) {
  9151. if (this.variable) {
  9152. const name = this.variable.getName(getPropertyAccess, useOriginalName);
  9153. if (name !== this.name) {
  9154. code.overwrite(this.start, this.end, name, {
  9155. contentOnly: true,
  9156. storeName: true
  9157. });
  9158. if (isShorthandProperty) {
  9159. code.prependRight(this.start, `${this.name}: `);
  9160. }
  9161. }
  9162. // In strict mode, any variable named "eval" must be the actual "eval" function
  9163. if (name === 'eval' &&
  9164. renderedParentType === CallExpression$1 &&
  9165. isCalleeOfRenderedParent) {
  9166. code.appendRight(this.start, '0, ');
  9167. }
  9168. }
  9169. }
  9170. applyDeoptimizations() {
  9171. this.deoptimized = true;
  9172. if (this.variable instanceof LocalVariable) {
  9173. this.variable.consolidateInitializers();
  9174. this.context.requestTreeshakingPass();
  9175. }
  9176. }
  9177. disallowImportReassignment() {
  9178. return this.context.error(logIllegalImportReassignment(this.name, this.context.module.id), this.start);
  9179. }
  9180. getVariableRespectingTDZ() {
  9181. if (this.isPossibleTDZ()) {
  9182. return UNKNOWN_EXPRESSION;
  9183. }
  9184. return this.variable;
  9185. }
  9186. isPureFunction(path) {
  9187. let currentPureFunction = this.context.manualPureFunctions[this.name];
  9188. for (const segment of path) {
  9189. if (currentPureFunction) {
  9190. if (currentPureFunction[PureFunctionKey]) {
  9191. return true;
  9192. }
  9193. currentPureFunction = currentPureFunction[segment];
  9194. }
  9195. else {
  9196. return false;
  9197. }
  9198. }
  9199. return currentPureFunction?.[PureFunctionKey];
  9200. }
  9201. }
  9202. function closestParentFunctionOrProgram(node) {
  9203. while (node && !/^Program|Function/.test(node.type)) {
  9204. node = node.parent;
  9205. }
  9206. // one of: ArrowFunctionExpression, FunctionDeclaration, FunctionExpression or Program
  9207. return node;
  9208. }
  9209. function treeshakeNode(node, code, start, end) {
  9210. code.remove(start, end);
  9211. if (node.annotations) {
  9212. for (const annotation of node.annotations) {
  9213. if (annotation.start < start) {
  9214. code.remove(annotation.start, annotation.end);
  9215. }
  9216. else {
  9217. return;
  9218. }
  9219. }
  9220. }
  9221. }
  9222. function removeAnnotations(node, code) {
  9223. if (!node.annotations && node.parent.type === ExpressionStatement$1) {
  9224. node = node.parent;
  9225. }
  9226. if (node.annotations) {
  9227. for (const annotation of node.annotations) {
  9228. code.remove(annotation.start, annotation.end);
  9229. }
  9230. }
  9231. }
  9232. const NO_SEMICOLON = { isNoStatement: true };
  9233. // This assumes there are only white-space and comments between start and the string we are looking for
  9234. function findFirstOccurrenceOutsideComment(code, searchString, start = 0) {
  9235. let searchPos, charCodeAfterSlash;
  9236. searchPos = code.indexOf(searchString, start);
  9237. while (true) {
  9238. start = code.indexOf('/', start);
  9239. if (start === -1 || start >= searchPos)
  9240. return searchPos;
  9241. charCodeAfterSlash = code.charCodeAt(++start);
  9242. ++start;
  9243. // With our assumption, '/' always starts a comment. Determine comment type:
  9244. start =
  9245. charCodeAfterSlash === 47 /*"/"*/
  9246. ? code.indexOf('\n', start) + 1
  9247. : code.indexOf('*/', start) + 2;
  9248. if (start > searchPos) {
  9249. searchPos = code.indexOf(searchString, start);
  9250. }
  9251. }
  9252. }
  9253. const NON_WHITESPACE = /\S/g;
  9254. function findNonWhiteSpace(code, index) {
  9255. NON_WHITESPACE.lastIndex = index;
  9256. const result = NON_WHITESPACE.exec(code);
  9257. return result.index;
  9258. }
  9259. // This assumes "code" only contains white-space and comments
  9260. // Returns position of line-comment if applicable
  9261. function findFirstLineBreakOutsideComment(code) {
  9262. let lineBreakPos, charCodeAfterSlash, start = 0;
  9263. lineBreakPos = code.indexOf('\n', start);
  9264. while (true) {
  9265. start = code.indexOf('/', start);
  9266. if (start === -1 || start > lineBreakPos)
  9267. return [lineBreakPos, lineBreakPos + 1];
  9268. // With our assumption, '/' always starts a comment. Determine comment type:
  9269. charCodeAfterSlash = code.charCodeAt(start + 1);
  9270. if (charCodeAfterSlash === 47 /*"/"*/)
  9271. return [start, lineBreakPos + 1];
  9272. start = code.indexOf('*/', start + 3) + 2;
  9273. if (start > lineBreakPos) {
  9274. lineBreakPos = code.indexOf('\n', start);
  9275. }
  9276. }
  9277. }
  9278. function renderStatementList(statements, code, start, end, options) {
  9279. let currentNode, currentNodeStart, currentNodeNeedsBoundaries, nextNodeStart;
  9280. let nextNode = statements[0];
  9281. let nextNodeNeedsBoundaries = !nextNode.included || nextNode.needsBoundaries;
  9282. if (nextNodeNeedsBoundaries) {
  9283. nextNodeStart =
  9284. start + findFirstLineBreakOutsideComment(code.original.slice(start, nextNode.start))[1];
  9285. }
  9286. for (let nextIndex = 1; nextIndex <= statements.length; nextIndex++) {
  9287. currentNode = nextNode;
  9288. currentNodeStart = nextNodeStart;
  9289. currentNodeNeedsBoundaries = nextNodeNeedsBoundaries;
  9290. nextNode = statements[nextIndex];
  9291. nextNodeNeedsBoundaries =
  9292. nextNode === undefined ? false : !nextNode.included || nextNode.needsBoundaries;
  9293. if (currentNodeNeedsBoundaries || nextNodeNeedsBoundaries) {
  9294. nextNodeStart =
  9295. currentNode.end +
  9296. findFirstLineBreakOutsideComment(code.original.slice(currentNode.end, nextNode === undefined ? end : nextNode.start))[1];
  9297. if (currentNode.included) {
  9298. currentNodeNeedsBoundaries
  9299. ? currentNode.render(code, options, {
  9300. end: nextNodeStart,
  9301. start: currentNodeStart
  9302. })
  9303. : currentNode.render(code, options);
  9304. }
  9305. else {
  9306. treeshakeNode(currentNode, code, currentNodeStart, nextNodeStart);
  9307. }
  9308. }
  9309. else {
  9310. currentNode.render(code, options);
  9311. }
  9312. }
  9313. }
  9314. // This assumes that the first character is not part of the first node
  9315. function getCommaSeparatedNodesWithBoundaries(nodes, code, start, end) {
  9316. const splitUpNodes = [];
  9317. let node, nextNodeStart, contentEnd, char;
  9318. let separator = start - 1;
  9319. for (const nextNode of nodes) {
  9320. if (node !== undefined) {
  9321. separator =
  9322. node.end +
  9323. findFirstOccurrenceOutsideComment(code.original.slice(node.end, nextNode.start), ',');
  9324. }
  9325. nextNodeStart = contentEnd =
  9326. separator +
  9327. 1 +
  9328. findFirstLineBreakOutsideComment(code.original.slice(separator + 1, nextNode.start))[1];
  9329. while (((char = code.original.charCodeAt(nextNodeStart)),
  9330. char === 32 /*" "*/ || char === 9 /*"\t"*/ || char === 10 /*"\n"*/ || char === 13) /*"\r"*/)
  9331. nextNodeStart++;
  9332. if (node !== undefined) {
  9333. splitUpNodes.push({
  9334. contentEnd,
  9335. end: nextNodeStart,
  9336. node,
  9337. separator,
  9338. start
  9339. });
  9340. }
  9341. node = nextNode;
  9342. start = nextNodeStart;
  9343. }
  9344. splitUpNodes.push({
  9345. contentEnd: end,
  9346. end,
  9347. node: node,
  9348. separator: null,
  9349. start
  9350. });
  9351. return splitUpNodes;
  9352. }
  9353. // This assumes there are only white-space and comments between start and end
  9354. function removeLineBreaks(code, start, end) {
  9355. while (true) {
  9356. const [removeStart, removeEnd] = findFirstLineBreakOutsideComment(code.original.slice(start, end));
  9357. if (removeStart === -1) {
  9358. break;
  9359. }
  9360. code.remove(start + removeStart, (start += removeEnd));
  9361. }
  9362. }
  9363. class BlockScope extends ChildScope {
  9364. addDeclaration(identifier, context, init, isHoisted) {
  9365. if (isHoisted) {
  9366. const variable = this.parent.addDeclaration(identifier, context, init, isHoisted);
  9367. // Necessary to make sure the init is deoptimized for conditional declarations.
  9368. // We cannot call deoptimizePath here.
  9369. variable.markInitializersForDeoptimization();
  9370. return variable;
  9371. }
  9372. else {
  9373. return super.addDeclaration(identifier, context, init, false);
  9374. }
  9375. }
  9376. }
  9377. class ExpressionStatement extends NodeBase {
  9378. initialise() {
  9379. if (this.directive &&
  9380. this.directive !== 'use strict' &&
  9381. this.parent.type === Program$1) {
  9382. this.context.log(LOGLEVEL_WARN,
  9383. // This is necessary, because either way (deleting or not) can lead to errors.
  9384. logModuleLevelDirective(this.directive, this.context.module.id), this.start);
  9385. }
  9386. }
  9387. render(code, options) {
  9388. super.render(code, options);
  9389. if (this.included)
  9390. this.insertSemicolon(code);
  9391. }
  9392. shouldBeIncluded(context) {
  9393. if (this.directive && this.directive !== 'use strict')
  9394. return this.parent.type !== Program$1;
  9395. return super.shouldBeIncluded(context);
  9396. }
  9397. applyDeoptimizations() { }
  9398. }
  9399. class BlockStatement extends NodeBase {
  9400. constructor() {
  9401. super(...arguments);
  9402. this.directlyIncluded = false;
  9403. }
  9404. addImplicitReturnExpressionToScope() {
  9405. const lastStatement = this.body[this.body.length - 1];
  9406. if (!lastStatement || lastStatement.type !== ReturnStatement$1) {
  9407. this.scope.addReturnExpression(UNKNOWN_EXPRESSION);
  9408. }
  9409. }
  9410. createScope(parentScope) {
  9411. this.scope = this.parent.preventChildBlockScope
  9412. ? parentScope
  9413. : new BlockScope(parentScope);
  9414. }
  9415. hasEffects(context) {
  9416. if (this.deoptimizeBody)
  9417. return true;
  9418. for (const node of this.body) {
  9419. if (context.brokenFlow)
  9420. break;
  9421. if (node.hasEffects(context))
  9422. return true;
  9423. }
  9424. return false;
  9425. }
  9426. include(context, includeChildrenRecursively) {
  9427. if (!(this.deoptimizeBody && this.directlyIncluded)) {
  9428. this.included = true;
  9429. this.directlyIncluded = true;
  9430. if (this.deoptimizeBody)
  9431. includeChildrenRecursively = true;
  9432. for (const node of this.body) {
  9433. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  9434. node.include(context, includeChildrenRecursively);
  9435. }
  9436. }
  9437. }
  9438. initialise() {
  9439. const firstBodyStatement = this.body[0];
  9440. this.deoptimizeBody =
  9441. firstBodyStatement instanceof ExpressionStatement &&
  9442. firstBodyStatement.directive === 'use asm';
  9443. }
  9444. render(code, options) {
  9445. if (this.body.length > 0) {
  9446. renderStatementList(this.body, code, this.start + 1, this.end - 1, options);
  9447. }
  9448. else {
  9449. super.render(code, options);
  9450. }
  9451. }
  9452. }
  9453. class RestElement extends NodeBase {
  9454. constructor() {
  9455. super(...arguments);
  9456. this.declarationInit = null;
  9457. }
  9458. addExportedVariables(variables, exportNamesByVariable) {
  9459. this.argument.addExportedVariables(variables, exportNamesByVariable);
  9460. }
  9461. declare(kind, init) {
  9462. this.declarationInit = init;
  9463. return this.argument.declare(kind, UNKNOWN_EXPRESSION);
  9464. }
  9465. deoptimizePath(path) {
  9466. path.length === 0 && this.argument.deoptimizePath(EMPTY_PATH);
  9467. }
  9468. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9469. return (path.length > 0 ||
  9470. this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context));
  9471. }
  9472. markDeclarationReached() {
  9473. this.argument.markDeclarationReached();
  9474. }
  9475. applyDeoptimizations() {
  9476. this.deoptimized = true;
  9477. if (this.declarationInit !== null) {
  9478. this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
  9479. this.context.requestTreeshakingPass();
  9480. }
  9481. }
  9482. }
  9483. class FunctionBase extends NodeBase {
  9484. constructor() {
  9485. super(...arguments);
  9486. this.objectEntity = null;
  9487. this.deoptimizedReturn = false;
  9488. }
  9489. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  9490. if (interaction.type === INTERACTION_CALLED) {
  9491. const { parameters } = this.scope;
  9492. const { args } = interaction;
  9493. let hasRest = false;
  9494. for (let position = 0; position < args.length - 1; position++) {
  9495. const parameter = this.params[position];
  9496. // Only the "this" argument arg[0] can be null
  9497. const argument = args[position + 1];
  9498. if (hasRest || parameter instanceof RestElement) {
  9499. hasRest = true;
  9500. argument.deoptimizePath(UNKNOWN_PATH);
  9501. }
  9502. else if (parameter instanceof Identifier) {
  9503. parameters[position][0].addEntityToBeDeoptimized(argument);
  9504. this.addArgumentToBeDeoptimized(argument);
  9505. }
  9506. else if (parameter) {
  9507. argument.deoptimizePath(UNKNOWN_PATH);
  9508. }
  9509. else {
  9510. this.addArgumentToBeDeoptimized(argument);
  9511. }
  9512. }
  9513. }
  9514. else {
  9515. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  9516. }
  9517. }
  9518. deoptimizePath(path) {
  9519. this.getObjectEntity().deoptimizePath(path);
  9520. if (path.length === 1 && path[0] === UnknownKey) {
  9521. // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
  9522. // which means the return expression and parameters need to be reassigned
  9523. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  9524. for (const parameterList of this.scope.parameters) {
  9525. for (const parameter of parameterList) {
  9526. parameter.deoptimizePath(UNKNOWN_PATH);
  9527. }
  9528. }
  9529. }
  9530. }
  9531. getLiteralValueAtPath(path, recursionTracker, origin) {
  9532. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  9533. }
  9534. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  9535. if (path.length > 0) {
  9536. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  9537. }
  9538. if (this.async) {
  9539. if (!this.deoptimizedReturn) {
  9540. this.deoptimizedReturn = true;
  9541. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  9542. this.context.requestTreeshakingPass();
  9543. }
  9544. return UNKNOWN_RETURN_EXPRESSION;
  9545. }
  9546. return [this.scope.getReturnExpression(), false];
  9547. }
  9548. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9549. if (path.length > 0 || interaction.type !== INTERACTION_CALLED) {
  9550. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  9551. }
  9552. if (this.annotationNoSideEffects) {
  9553. return false;
  9554. }
  9555. if (this.async) {
  9556. const { propertyReadSideEffects } = this.context.options
  9557. .treeshake;
  9558. const returnExpression = this.scope.getReturnExpression();
  9559. if (returnExpression.hasEffectsOnInteractionAtPath(['then'], NODE_INTERACTION_UNKNOWN_CALL, context) ||
  9560. (propertyReadSideEffects &&
  9561. (propertyReadSideEffects === 'always' ||
  9562. returnExpression.hasEffectsOnInteractionAtPath(['then'], NODE_INTERACTION_UNKNOWN_ACCESS, context)))) {
  9563. return true;
  9564. }
  9565. }
  9566. for (const parameter of this.params) {
  9567. if (parameter.hasEffects(context))
  9568. return true;
  9569. }
  9570. return false;
  9571. }
  9572. include(context, includeChildrenRecursively) {
  9573. if (!this.deoptimized)
  9574. this.applyDeoptimizations();
  9575. this.included = true;
  9576. const { brokenFlow } = context;
  9577. context.brokenFlow = false;
  9578. this.body.include(context, includeChildrenRecursively);
  9579. context.brokenFlow = brokenFlow;
  9580. }
  9581. includeCallArguments(context, parameters) {
  9582. this.scope.includeCallArguments(context, parameters);
  9583. }
  9584. initialise() {
  9585. this.scope.addParameterVariables(this.params.map(parameter => parameter.declare('parameter', UNKNOWN_EXPRESSION)), this.params[this.params.length - 1] instanceof RestElement);
  9586. if (this.body instanceof BlockStatement) {
  9587. this.body.addImplicitReturnExpressionToScope();
  9588. }
  9589. else {
  9590. this.scope.addReturnExpression(this.body);
  9591. }
  9592. }
  9593. parseNode(esTreeNode) {
  9594. if (esTreeNode.body.type === BlockStatement$1) {
  9595. this.body = new BlockStatement(esTreeNode.body, this, this.scope.hoistedBodyVarScope);
  9596. }
  9597. super.parseNode(esTreeNode);
  9598. }
  9599. addArgumentToBeDeoptimized(_argument) { }
  9600. applyDeoptimizations() { }
  9601. }
  9602. FunctionBase.prototype.preventChildBlockScope = true;
  9603. class ArrowFunctionExpression extends FunctionBase {
  9604. constructor() {
  9605. super(...arguments);
  9606. this.objectEntity = null;
  9607. }
  9608. createScope(parentScope) {
  9609. this.scope = new ReturnValueScope(parentScope, this.context);
  9610. }
  9611. hasEffects() {
  9612. if (!this.deoptimized)
  9613. this.applyDeoptimizations();
  9614. return false;
  9615. }
  9616. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9617. if (super.hasEffectsOnInteractionAtPath(path, interaction, context)) {
  9618. return true;
  9619. }
  9620. if (this.annotationNoSideEffects) {
  9621. return false;
  9622. }
  9623. if (interaction.type === INTERACTION_CALLED) {
  9624. const { ignore, brokenFlow } = context;
  9625. context.ignore = {
  9626. breaks: false,
  9627. continues: false,
  9628. labels: new Set(),
  9629. returnYield: true,
  9630. this: false
  9631. };
  9632. if (this.body.hasEffects(context))
  9633. return true;
  9634. context.ignore = ignore;
  9635. context.brokenFlow = brokenFlow;
  9636. }
  9637. return false;
  9638. }
  9639. include(context, includeChildrenRecursively) {
  9640. super.include(context, includeChildrenRecursively);
  9641. for (const parameter of this.params) {
  9642. if (!(parameter instanceof Identifier)) {
  9643. parameter.include(context, includeChildrenRecursively);
  9644. }
  9645. }
  9646. }
  9647. getObjectEntity() {
  9648. if (this.objectEntity !== null) {
  9649. return this.objectEntity;
  9650. }
  9651. return (this.objectEntity = new ObjectEntity([], OBJECT_PROTOTYPE));
  9652. }
  9653. }
  9654. function getSystemExportStatement(exportedVariables, { exportNamesByVariable, snippets: { _, getObject, getPropertyAccess } }, modifier = '') {
  9655. if (exportedVariables.length === 1 &&
  9656. exportNamesByVariable.get(exportedVariables[0]).length === 1) {
  9657. const variable = exportedVariables[0];
  9658. return `exports('${exportNamesByVariable.get(variable)}',${_}${variable.getName(getPropertyAccess)}${modifier})`;
  9659. }
  9660. else {
  9661. const fields = [];
  9662. for (const variable of exportedVariables) {
  9663. for (const exportName of exportNamesByVariable.get(variable)) {
  9664. fields.push([exportName, variable.getName(getPropertyAccess) + modifier]);
  9665. }
  9666. }
  9667. return `exports(${getObject(fields, { lineBreakIndent: null })})`;
  9668. }
  9669. }
  9670. function renderSystemExportExpression(exportedVariable, expressionStart, expressionEnd, code, { exportNamesByVariable, snippets: { _ } }) {
  9671. code.prependRight(expressionStart, `exports('${exportNamesByVariable.get(exportedVariable)}',${_}`);
  9672. code.appendLeft(expressionEnd, ')');
  9673. }
  9674. function renderSystemExportFunction(exportedVariables, expressionStart, expressionEnd, needsParens, code, options) {
  9675. const { _, getDirectReturnIifeLeft } = options.snippets;
  9676. code.prependRight(expressionStart, getDirectReturnIifeLeft(['v'], `${getSystemExportStatement(exportedVariables, options)},${_}v`, { needsArrowReturnParens: true, needsWrappedFunction: needsParens }));
  9677. code.appendLeft(expressionEnd, ')');
  9678. }
  9679. function renderSystemExportSequenceAfterExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options) {
  9680. const { _, getPropertyAccess } = options.snippets;
  9681. code.appendLeft(expressionEnd, `,${_}${getSystemExportStatement([exportedVariable], options)},${_}${exportedVariable.getName(getPropertyAccess)}`);
  9682. if (needsParens) {
  9683. code.prependRight(expressionStart, '(');
  9684. code.appendLeft(expressionEnd, ')');
  9685. }
  9686. }
  9687. function renderSystemExportSequenceBeforeExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options, modifier) {
  9688. const { _ } = options.snippets;
  9689. code.prependRight(expressionStart, `${getSystemExportStatement([exportedVariable], options, modifier)},${_}`);
  9690. if (needsParens) {
  9691. code.prependRight(expressionStart, '(');
  9692. code.appendLeft(expressionEnd, ')');
  9693. }
  9694. }
  9695. class ObjectPattern extends NodeBase {
  9696. addExportedVariables(variables, exportNamesByVariable) {
  9697. for (const property of this.properties) {
  9698. if (property.type === Property$1) {
  9699. property.value.addExportedVariables(variables, exportNamesByVariable);
  9700. }
  9701. else {
  9702. property.argument.addExportedVariables(variables, exportNamesByVariable);
  9703. }
  9704. }
  9705. }
  9706. declare(kind, init) {
  9707. const variables = [];
  9708. for (const property of this.properties) {
  9709. variables.push(...property.declare(kind, init));
  9710. }
  9711. return variables;
  9712. }
  9713. deoptimizePath(path) {
  9714. if (path.length === 0) {
  9715. for (const property of this.properties) {
  9716. property.deoptimizePath(path);
  9717. }
  9718. }
  9719. }
  9720. hasEffectsOnInteractionAtPath(
  9721. // At the moment, this is only triggered for assignment left-hand sides,
  9722. // where the path is empty
  9723. _path, interaction, context) {
  9724. for (const property of this.properties) {
  9725. if (property.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context))
  9726. return true;
  9727. }
  9728. return false;
  9729. }
  9730. markDeclarationReached() {
  9731. for (const property of this.properties) {
  9732. property.markDeclarationReached();
  9733. }
  9734. }
  9735. }
  9736. class AssignmentExpression extends NodeBase {
  9737. hasEffects(context) {
  9738. const { deoptimized, left, operator, right } = this;
  9739. if (!deoptimized)
  9740. this.applyDeoptimizations();
  9741. // MemberExpressions do not access the property before assignments if the
  9742. // operator is '='.
  9743. return (right.hasEffects(context) || left.hasEffectsAsAssignmentTarget(context, operator !== '='));
  9744. }
  9745. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9746. return this.right.hasEffectsOnInteractionAtPath(path, interaction, context);
  9747. }
  9748. include(context, includeChildrenRecursively) {
  9749. const { deoptimized, left, right, operator } = this;
  9750. if (!deoptimized)
  9751. this.applyDeoptimizations();
  9752. this.included = true;
  9753. if (includeChildrenRecursively ||
  9754. operator !== '=' ||
  9755. left.included ||
  9756. left.hasEffectsAsAssignmentTarget(createHasEffectsContext(), false)) {
  9757. left.includeAsAssignmentTarget(context, includeChildrenRecursively, operator !== '=');
  9758. }
  9759. right.include(context, includeChildrenRecursively);
  9760. }
  9761. initialise() {
  9762. this.left.setAssignedValue(this.right);
  9763. }
  9764. render(code, options, { preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  9765. const { left, right, start, end, parent } = this;
  9766. if (left.included) {
  9767. left.render(code, options);
  9768. right.render(code, options);
  9769. }
  9770. else {
  9771. const inclusionStart = findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, '=', left.end) + 1);
  9772. code.remove(start, inclusionStart);
  9773. if (preventASI) {
  9774. removeLineBreaks(code, inclusionStart, right.start);
  9775. }
  9776. right.render(code, options, {
  9777. renderedParentType: renderedParentType || parent.type,
  9778. renderedSurroundingElement: renderedSurroundingElement || parent.type
  9779. });
  9780. }
  9781. if (options.format === 'system') {
  9782. if (left instanceof Identifier) {
  9783. const variable = left.variable;
  9784. const exportNames = options.exportNamesByVariable.get(variable);
  9785. if (exportNames) {
  9786. if (exportNames.length === 1) {
  9787. renderSystemExportExpression(variable, start, end, code, options);
  9788. }
  9789. else {
  9790. renderSystemExportSequenceAfterExpression(variable, start, end, parent.type !== ExpressionStatement$1, code, options);
  9791. }
  9792. return;
  9793. }
  9794. }
  9795. else {
  9796. const systemPatternExports = [];
  9797. left.addExportedVariables(systemPatternExports, options.exportNamesByVariable);
  9798. if (systemPatternExports.length > 0) {
  9799. renderSystemExportFunction(systemPatternExports, start, end, renderedSurroundingElement === ExpressionStatement$1, code, options);
  9800. return;
  9801. }
  9802. }
  9803. }
  9804. if (left.included &&
  9805. left instanceof ObjectPattern &&
  9806. (renderedSurroundingElement === ExpressionStatement$1 ||
  9807. renderedSurroundingElement === ArrowFunctionExpression$1)) {
  9808. code.appendRight(start, '(');
  9809. code.prependLeft(end, ')');
  9810. }
  9811. }
  9812. applyDeoptimizations() {
  9813. this.deoptimized = true;
  9814. this.left.deoptimizePath(EMPTY_PATH);
  9815. this.right.deoptimizePath(UNKNOWN_PATH);
  9816. this.context.requestTreeshakingPass();
  9817. }
  9818. }
  9819. class AssignmentPattern extends NodeBase {
  9820. addExportedVariables(variables, exportNamesByVariable) {
  9821. this.left.addExportedVariables(variables, exportNamesByVariable);
  9822. }
  9823. declare(kind, init) {
  9824. return this.left.declare(kind, init);
  9825. }
  9826. deoptimizePath(path) {
  9827. path.length === 0 && this.left.deoptimizePath(path);
  9828. }
  9829. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9830. return (path.length > 0 || this.left.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context));
  9831. }
  9832. markDeclarationReached() {
  9833. this.left.markDeclarationReached();
  9834. }
  9835. render(code, options, { isShorthandProperty } = BLANK) {
  9836. this.left.render(code, options, { isShorthandProperty });
  9837. this.right.render(code, options);
  9838. }
  9839. applyDeoptimizations() {
  9840. this.deoptimized = true;
  9841. this.left.deoptimizePath(EMPTY_PATH);
  9842. this.right.deoptimizePath(UNKNOWN_PATH);
  9843. this.context.requestTreeshakingPass();
  9844. }
  9845. }
  9846. class ArgumentsVariable extends LocalVariable {
  9847. constructor(context) {
  9848. super('arguments', null, UNKNOWN_EXPRESSION, context);
  9849. this.deoptimizedArguments = [];
  9850. }
  9851. addArgumentToBeDeoptimized(argument) {
  9852. if (this.included) {
  9853. argument.deoptimizePath(UNKNOWN_PATH);
  9854. }
  9855. else {
  9856. this.deoptimizedArguments.push(argument);
  9857. }
  9858. }
  9859. hasEffectsOnInteractionAtPath(path, { type }) {
  9860. return type !== INTERACTION_ACCESSED || path.length > 1;
  9861. }
  9862. include() {
  9863. super.include();
  9864. for (const argument of this.deoptimizedArguments) {
  9865. argument.deoptimizePath(UNKNOWN_PATH);
  9866. }
  9867. this.deoptimizedArguments.length = 0;
  9868. }
  9869. }
  9870. class ThisVariable extends ParameterVariable {
  9871. constructor(context) {
  9872. super('this', null, context);
  9873. }
  9874. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9875. return (context.replacedVariableInits.get(this) || UNKNOWN_EXPRESSION).hasEffectsOnInteractionAtPath(path, interaction, context);
  9876. }
  9877. }
  9878. class FunctionScope extends ReturnValueScope {
  9879. constructor(parent, context) {
  9880. super(parent, context);
  9881. this.variables.set('arguments', (this.argumentsVariable = new ArgumentsVariable(context)));
  9882. this.variables.set('this', (this.thisVariable = new ThisVariable(context)));
  9883. }
  9884. findLexicalBoundary() {
  9885. return this;
  9886. }
  9887. includeCallArguments(context, parameters) {
  9888. super.includeCallArguments(context, parameters);
  9889. if (this.argumentsVariable.included) {
  9890. for (const argument of parameters) {
  9891. if (!argument.included) {
  9892. argument.include(context, false);
  9893. }
  9894. }
  9895. }
  9896. }
  9897. }
  9898. class FunctionNode extends FunctionBase {
  9899. constructor() {
  9900. super(...arguments);
  9901. this.objectEntity = null;
  9902. }
  9903. createScope(parentScope) {
  9904. this.scope = new FunctionScope(parentScope, this.context);
  9905. this.constructedEntity = new ObjectEntity(Object.create(null), OBJECT_PROTOTYPE);
  9906. // This makes sure that all deoptimizations of "this" are applied to the
  9907. // constructed entity.
  9908. this.scope.thisVariable.addEntityToBeDeoptimized(this.constructedEntity);
  9909. }
  9910. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  9911. super.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  9912. if (interaction.type === INTERACTION_CALLED && path.length === 0 && interaction.args[0]) {
  9913. // args[0] is the "this" argument
  9914. this.scope.thisVariable.addEntityToBeDeoptimized(interaction.args[0]);
  9915. }
  9916. }
  9917. hasEffects(context) {
  9918. if (!this.deoptimized)
  9919. this.applyDeoptimizations();
  9920. if (this.annotationNoSideEffects) {
  9921. return false;
  9922. }
  9923. return !!this.id?.hasEffects(context);
  9924. }
  9925. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9926. if (super.hasEffectsOnInteractionAtPath(path, interaction, context))
  9927. return true;
  9928. if (this.annotationNoSideEffects) {
  9929. return false;
  9930. }
  9931. if (interaction.type === INTERACTION_CALLED) {
  9932. const thisInit = context.replacedVariableInits.get(this.scope.thisVariable);
  9933. context.replacedVariableInits.set(this.scope.thisVariable, interaction.withNew ? this.constructedEntity : UNKNOWN_EXPRESSION);
  9934. const { brokenFlow, ignore, replacedVariableInits } = context;
  9935. context.ignore = {
  9936. breaks: false,
  9937. continues: false,
  9938. labels: new Set(),
  9939. returnYield: true,
  9940. this: interaction.withNew
  9941. };
  9942. if (this.body.hasEffects(context))
  9943. return true;
  9944. context.brokenFlow = brokenFlow;
  9945. if (thisInit) {
  9946. replacedVariableInits.set(this.scope.thisVariable, thisInit);
  9947. }
  9948. else {
  9949. replacedVariableInits.delete(this.scope.thisVariable);
  9950. }
  9951. context.ignore = ignore;
  9952. }
  9953. return false;
  9954. }
  9955. include(context, includeChildrenRecursively) {
  9956. super.include(context, includeChildrenRecursively);
  9957. this.id?.include();
  9958. const hasArguments = this.scope.argumentsVariable.included;
  9959. for (const parameter of this.params) {
  9960. if (!(parameter instanceof Identifier) || hasArguments) {
  9961. parameter.include(context, includeChildrenRecursively);
  9962. }
  9963. }
  9964. }
  9965. initialise() {
  9966. super.initialise();
  9967. this.id?.declare('function', this);
  9968. }
  9969. addArgumentToBeDeoptimized(argument) {
  9970. this.scope.argumentsVariable.addArgumentToBeDeoptimized(argument);
  9971. }
  9972. getObjectEntity() {
  9973. if (this.objectEntity !== null) {
  9974. return this.objectEntity;
  9975. }
  9976. return (this.objectEntity = new ObjectEntity([
  9977. {
  9978. key: 'prototype',
  9979. kind: 'init',
  9980. property: new ObjectEntity([], OBJECT_PROTOTYPE)
  9981. }
  9982. ], OBJECT_PROTOTYPE));
  9983. }
  9984. }
  9985. class AwaitExpression extends NodeBase {
  9986. hasEffects() {
  9987. if (!this.deoptimized)
  9988. this.applyDeoptimizations();
  9989. return true;
  9990. }
  9991. include(context, includeChildrenRecursively) {
  9992. if (!this.deoptimized)
  9993. this.applyDeoptimizations();
  9994. if (!this.included) {
  9995. this.included = true;
  9996. checkTopLevelAwait: if (!this.context.usesTopLevelAwait) {
  9997. let parent = this.parent;
  9998. do {
  9999. if (parent instanceof FunctionNode || parent instanceof ArrowFunctionExpression)
  10000. break checkTopLevelAwait;
  10001. } while ((parent = parent.parent));
  10002. this.context.usesTopLevelAwait = true;
  10003. }
  10004. }
  10005. this.argument.include(context, includeChildrenRecursively);
  10006. }
  10007. }
  10008. const binaryOperators = {
  10009. '!=': (left, right) => left != right,
  10010. '!==': (left, right) => left !== right,
  10011. '%': (left, right) => left % right,
  10012. '&': (left, right) => left & right,
  10013. '*': (left, right) => left * right,
  10014. // At the moment, "**" will be transpiled to Math.pow
  10015. '**': (left, right) => left ** right,
  10016. '+': (left, right) => left + right,
  10017. '-': (left, right) => left - right,
  10018. '/': (left, right) => left / right,
  10019. '<': (left, right) => left < right,
  10020. '<<': (left, right) => left << right,
  10021. '<=': (left, right) => left <= right,
  10022. '==': (left, right) => left == right,
  10023. '===': (left, right) => left === right,
  10024. '>': (left, right) => left > right,
  10025. '>=': (left, right) => left >= right,
  10026. '>>': (left, right) => left >> right,
  10027. '>>>': (left, right) => left >>> right,
  10028. '^': (left, right) => left ^ right,
  10029. '|': (left, right) => left | right
  10030. // We use the fallback for cases where we return something unknown
  10031. // in: () => UnknownValue,
  10032. // instanceof: () => UnknownValue,
  10033. };
  10034. class BinaryExpression extends NodeBase {
  10035. deoptimizeCache() { }
  10036. getLiteralValueAtPath(path, recursionTracker, origin) {
  10037. if (path.length > 0)
  10038. return UnknownValue;
  10039. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  10040. if (typeof leftValue === 'symbol')
  10041. return UnknownValue;
  10042. const rightValue = this.right.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  10043. if (typeof rightValue === 'symbol')
  10044. return UnknownValue;
  10045. const operatorFunction = binaryOperators[this.operator];
  10046. if (!operatorFunction)
  10047. return UnknownValue;
  10048. return operatorFunction(leftValue, rightValue);
  10049. }
  10050. hasEffects(context) {
  10051. // support some implicit type coercion runtime errors
  10052. if (this.operator === '+' &&
  10053. this.parent instanceof ExpressionStatement &&
  10054. this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) === '') {
  10055. return true;
  10056. }
  10057. return super.hasEffects(context);
  10058. }
  10059. hasEffectsOnInteractionAtPath(path, { type }) {
  10060. return type !== INTERACTION_ACCESSED || path.length > 1;
  10061. }
  10062. render(code, options, { renderedSurroundingElement } = BLANK) {
  10063. this.left.render(code, options, { renderedSurroundingElement });
  10064. this.right.render(code, options);
  10065. }
  10066. }
  10067. class BreakStatement extends NodeBase {
  10068. hasEffects(context) {
  10069. if (this.label) {
  10070. if (!context.ignore.labels.has(this.label.name))
  10071. return true;
  10072. context.includedLabels.add(this.label.name);
  10073. }
  10074. else {
  10075. if (!context.ignore.breaks)
  10076. return true;
  10077. context.hasBreak = true;
  10078. }
  10079. context.brokenFlow = true;
  10080. return false;
  10081. }
  10082. include(context) {
  10083. this.included = true;
  10084. if (this.label) {
  10085. this.label.include();
  10086. context.includedLabels.add(this.label.name);
  10087. }
  10088. else {
  10089. context.hasBreak = true;
  10090. }
  10091. context.brokenFlow = true;
  10092. }
  10093. }
  10094. function renderCallArguments(code, options, node) {
  10095. if (node.arguments.length > 0) {
  10096. if (node.arguments[node.arguments.length - 1].included) {
  10097. for (const argument of node.arguments) {
  10098. argument.render(code, options);
  10099. }
  10100. }
  10101. else {
  10102. let lastIncludedIndex = node.arguments.length - 2;
  10103. while (lastIncludedIndex >= 0 && !node.arguments[lastIncludedIndex].included) {
  10104. lastIncludedIndex--;
  10105. }
  10106. if (lastIncludedIndex >= 0) {
  10107. for (let index = 0; index <= lastIncludedIndex; index++) {
  10108. node.arguments[index].render(code, options);
  10109. }
  10110. code.remove(findFirstOccurrenceOutsideComment(code.original, ',', node.arguments[lastIncludedIndex].end), node.end - 1);
  10111. }
  10112. else {
  10113. code.remove(findFirstOccurrenceOutsideComment(code.original, '(', node.callee.end) + 1, node.end - 1);
  10114. }
  10115. }
  10116. }
  10117. }
  10118. class Literal extends NodeBase {
  10119. deoptimizeArgumentsOnInteractionAtPath() { }
  10120. getLiteralValueAtPath(path) {
  10121. if (path.length > 0 ||
  10122. // unknown literals can also be null but do not start with an "n"
  10123. (this.value === null && this.context.code.charCodeAt(this.start) !== 110) ||
  10124. typeof this.value === 'bigint' ||
  10125. // to support shims for regular expressions
  10126. this.context.code.charCodeAt(this.start) === 47) {
  10127. return UnknownValue;
  10128. }
  10129. return this.value;
  10130. }
  10131. getReturnExpressionWhenCalledAtPath(path) {
  10132. if (path.length !== 1)
  10133. return UNKNOWN_RETURN_EXPRESSION;
  10134. return getMemberReturnExpressionWhenCalled(this.members, path[0]);
  10135. }
  10136. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10137. switch (interaction.type) {
  10138. case INTERACTION_ACCESSED: {
  10139. return path.length > (this.value === null ? 0 : 1);
  10140. }
  10141. case INTERACTION_ASSIGNED: {
  10142. return true;
  10143. }
  10144. case INTERACTION_CALLED: {
  10145. if (this.included &&
  10146. this.value instanceof RegExp &&
  10147. (this.value.global || this.value.sticky)) {
  10148. return true;
  10149. }
  10150. return (path.length !== 1 ||
  10151. hasMemberEffectWhenCalled(this.members, path[0], interaction, context));
  10152. }
  10153. }
  10154. }
  10155. initialise() {
  10156. this.members = getLiteralMembersForValue(this.value);
  10157. }
  10158. parseNode(esTreeNode) {
  10159. this.value = esTreeNode.value;
  10160. this.regex = esTreeNode.regex;
  10161. super.parseNode(esTreeNode);
  10162. }
  10163. render(code) {
  10164. if (typeof this.value === 'string') {
  10165. code.indentExclusionRanges.push([this.start + 1, this.end - 1]);
  10166. }
  10167. }
  10168. }
  10169. // To avoid infinite recursions
  10170. const MAX_PATH_DEPTH = 7;
  10171. function getResolvablePropertyKey(memberExpression) {
  10172. return memberExpression.computed
  10173. ? getResolvableComputedPropertyKey(memberExpression.property)
  10174. : memberExpression.property.name;
  10175. }
  10176. function getResolvableComputedPropertyKey(propertyKey) {
  10177. if (propertyKey instanceof Literal) {
  10178. return String(propertyKey.value);
  10179. }
  10180. return null;
  10181. }
  10182. function getPathIfNotComputed(memberExpression) {
  10183. const nextPathKey = memberExpression.propertyKey;
  10184. const object = memberExpression.object;
  10185. if (typeof nextPathKey === 'string') {
  10186. if (object instanceof Identifier) {
  10187. return [
  10188. { key: object.name, pos: object.start },
  10189. { key: nextPathKey, pos: memberExpression.property.start }
  10190. ];
  10191. }
  10192. if (object instanceof MemberExpression) {
  10193. const parentPath = getPathIfNotComputed(object);
  10194. return (parentPath && [...parentPath, { key: nextPathKey, pos: memberExpression.property.start }]);
  10195. }
  10196. }
  10197. return null;
  10198. }
  10199. function getStringFromPath(path) {
  10200. let pathString = path[0].key;
  10201. for (let index = 1; index < path.length; index++) {
  10202. pathString += '.' + path[index].key;
  10203. }
  10204. return pathString;
  10205. }
  10206. class MemberExpression extends NodeBase {
  10207. constructor() {
  10208. super(...arguments);
  10209. this.variable = null;
  10210. this.assignmentDeoptimized = false;
  10211. this.bound = false;
  10212. this.expressionsToBeDeoptimized = [];
  10213. this.isUndefined = false;
  10214. }
  10215. bind() {
  10216. this.bound = true;
  10217. const path = getPathIfNotComputed(this);
  10218. const baseVariable = path && this.scope.findVariable(path[0].key);
  10219. if (baseVariable?.isNamespace) {
  10220. const resolvedVariable = resolveNamespaceVariables(baseVariable, path.slice(1), this.context);
  10221. if (!resolvedVariable) {
  10222. super.bind();
  10223. }
  10224. else if (resolvedVariable === 'undefined') {
  10225. this.isUndefined = true;
  10226. }
  10227. else {
  10228. this.variable = resolvedVariable;
  10229. this.scope.addNamespaceMemberAccess(getStringFromPath(path), resolvedVariable);
  10230. }
  10231. }
  10232. else {
  10233. super.bind();
  10234. }
  10235. }
  10236. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  10237. if (this.variable) {
  10238. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  10239. }
  10240. else if (!this.isUndefined) {
  10241. if (path.length < MAX_PATH_DEPTH) {
  10242. this.object.deoptimizeArgumentsOnInteractionAtPath(interaction, [this.getPropertyKey(), ...path], recursionTracker);
  10243. }
  10244. else {
  10245. deoptimizeInteraction(interaction);
  10246. }
  10247. }
  10248. }
  10249. deoptimizeCache() {
  10250. const { expressionsToBeDeoptimized, object } = this;
  10251. this.expressionsToBeDeoptimized = EMPTY_ARRAY;
  10252. this.propertyKey = UnknownKey;
  10253. object.deoptimizePath(UNKNOWN_PATH);
  10254. for (const expression of expressionsToBeDeoptimized) {
  10255. expression.deoptimizeCache();
  10256. }
  10257. }
  10258. deoptimizePath(path) {
  10259. if (path.length === 0)
  10260. this.disallowNamespaceReassignment();
  10261. if (this.variable) {
  10262. this.variable.deoptimizePath(path);
  10263. }
  10264. else if (!this.isUndefined && path.length < MAX_PATH_DEPTH) {
  10265. const propertyKey = this.getPropertyKey();
  10266. this.object.deoptimizePath([
  10267. propertyKey === UnknownKey ? UnknownNonAccessorKey : propertyKey,
  10268. ...path
  10269. ]);
  10270. }
  10271. }
  10272. getLiteralValueAtPath(path, recursionTracker, origin) {
  10273. if (this.variable) {
  10274. return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
  10275. }
  10276. if (this.isUndefined) {
  10277. return undefined;
  10278. }
  10279. if (this.propertyKey !== UnknownKey && path.length < MAX_PATH_DEPTH) {
  10280. this.expressionsToBeDeoptimized.push(origin);
  10281. return this.object.getLiteralValueAtPath([this.getPropertyKey(), ...path], recursionTracker, origin);
  10282. }
  10283. return UnknownValue;
  10284. }
  10285. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  10286. if (this.variable) {
  10287. return this.variable.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  10288. }
  10289. if (this.isUndefined) {
  10290. return [UNDEFINED_EXPRESSION, false];
  10291. }
  10292. if (this.propertyKey !== UnknownKey && path.length < MAX_PATH_DEPTH) {
  10293. this.expressionsToBeDeoptimized.push(origin);
  10294. return this.object.getReturnExpressionWhenCalledAtPath([this.getPropertyKey(), ...path], interaction, recursionTracker, origin);
  10295. }
  10296. return UNKNOWN_RETURN_EXPRESSION;
  10297. }
  10298. hasEffects(context) {
  10299. if (!this.deoptimized)
  10300. this.applyDeoptimizations();
  10301. return (this.property.hasEffects(context) ||
  10302. this.object.hasEffects(context) ||
  10303. this.hasAccessEffect(context));
  10304. }
  10305. hasEffectsAsAssignmentTarget(context, checkAccess) {
  10306. if (checkAccess && !this.deoptimized)
  10307. this.applyDeoptimizations();
  10308. if (!this.assignmentDeoptimized)
  10309. this.applyAssignmentDeoptimization();
  10310. return (this.property.hasEffects(context) ||
  10311. this.object.hasEffects(context) ||
  10312. (checkAccess && this.hasAccessEffect(context)) ||
  10313. this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
  10314. }
  10315. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10316. if (this.variable) {
  10317. return this.variable.hasEffectsOnInteractionAtPath(path, interaction, context);
  10318. }
  10319. if (this.isUndefined) {
  10320. return true;
  10321. }
  10322. if (path.length < MAX_PATH_DEPTH) {
  10323. return this.object.hasEffectsOnInteractionAtPath([this.getPropertyKey(), ...path], interaction, context);
  10324. }
  10325. return true;
  10326. }
  10327. include(context, includeChildrenRecursively) {
  10328. if (!this.deoptimized)
  10329. this.applyDeoptimizations();
  10330. this.includeProperties(context, includeChildrenRecursively);
  10331. }
  10332. includeAsAssignmentTarget(context, includeChildrenRecursively, deoptimizeAccess) {
  10333. if (!this.assignmentDeoptimized)
  10334. this.applyAssignmentDeoptimization();
  10335. if (deoptimizeAccess) {
  10336. this.include(context, includeChildrenRecursively);
  10337. }
  10338. else {
  10339. this.includeProperties(context, includeChildrenRecursively);
  10340. }
  10341. }
  10342. includeCallArguments(context, parameters) {
  10343. if (this.variable) {
  10344. this.variable.includeCallArguments(context, parameters);
  10345. }
  10346. else {
  10347. super.includeCallArguments(context, parameters);
  10348. }
  10349. }
  10350. initialise() {
  10351. this.propertyKey = getResolvablePropertyKey(this);
  10352. this.accessInteraction = { args: [this.object], type: INTERACTION_ACCESSED };
  10353. }
  10354. isSkippedAsOptional(origin) {
  10355. return (!this.variable &&
  10356. !this.isUndefined &&
  10357. (this.object.isSkippedAsOptional?.(origin) ||
  10358. (this.optional &&
  10359. this.object.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, origin) == null)));
  10360. }
  10361. render(code, options, { renderedParentType, isCalleeOfRenderedParent, renderedSurroundingElement } = BLANK) {
  10362. if (this.variable || this.isUndefined) {
  10363. const { snippets: { getPropertyAccess } } = options;
  10364. let replacement = this.variable ? this.variable.getName(getPropertyAccess) : 'undefined';
  10365. if (renderedParentType && isCalleeOfRenderedParent)
  10366. replacement = '0, ' + replacement;
  10367. code.overwrite(this.start, this.end, replacement, {
  10368. contentOnly: true,
  10369. storeName: true
  10370. });
  10371. }
  10372. else {
  10373. if (renderedParentType && isCalleeOfRenderedParent) {
  10374. code.appendRight(this.start, '0, ');
  10375. }
  10376. this.object.render(code, options, { renderedSurroundingElement });
  10377. this.property.render(code, options);
  10378. }
  10379. }
  10380. setAssignedValue(value) {
  10381. this.assignmentInteraction = {
  10382. args: [this.object, value],
  10383. type: INTERACTION_ASSIGNED
  10384. };
  10385. }
  10386. applyDeoptimizations() {
  10387. this.deoptimized = true;
  10388. const { propertyReadSideEffects } = this.context.options
  10389. .treeshake;
  10390. if (
  10391. // Namespaces are not bound and should not be deoptimized
  10392. this.bound &&
  10393. propertyReadSideEffects &&
  10394. !(this.variable || this.isUndefined)) {
  10395. const propertyKey = this.getPropertyKey();
  10396. this.object.deoptimizeArgumentsOnInteractionAtPath(this.accessInteraction, [propertyKey], SHARED_RECURSION_TRACKER);
  10397. this.context.requestTreeshakingPass();
  10398. }
  10399. }
  10400. applyAssignmentDeoptimization() {
  10401. this.assignmentDeoptimized = true;
  10402. const { propertyReadSideEffects } = this.context.options
  10403. .treeshake;
  10404. if (
  10405. // Namespaces are not bound and should not be deoptimized
  10406. this.bound &&
  10407. propertyReadSideEffects &&
  10408. !(this.variable || this.isUndefined)) {
  10409. this.object.deoptimizeArgumentsOnInteractionAtPath(this.assignmentInteraction, [this.getPropertyKey()], SHARED_RECURSION_TRACKER);
  10410. this.context.requestTreeshakingPass();
  10411. }
  10412. }
  10413. disallowNamespaceReassignment() {
  10414. if (this.object instanceof Identifier) {
  10415. const variable = this.scope.findVariable(this.object.name);
  10416. if (variable.isNamespace) {
  10417. if (this.variable) {
  10418. this.context.includeVariableInModule(this.variable);
  10419. }
  10420. this.context.log(LOGLEVEL_WARN, logIllegalImportReassignment(this.object.name, this.context.module.id), this.start);
  10421. }
  10422. }
  10423. }
  10424. getPropertyKey() {
  10425. if (this.propertyKey === null) {
  10426. this.propertyKey = UnknownKey;
  10427. const value = this.property.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  10428. return (this.propertyKey =
  10429. value === SymbolToStringTag
  10430. ? value
  10431. : typeof value === 'symbol'
  10432. ? UnknownKey
  10433. : String(value));
  10434. }
  10435. return this.propertyKey;
  10436. }
  10437. hasAccessEffect(context) {
  10438. const { propertyReadSideEffects } = this.context.options
  10439. .treeshake;
  10440. return (!(this.variable || this.isUndefined) &&
  10441. propertyReadSideEffects &&
  10442. (propertyReadSideEffects === 'always' ||
  10443. this.object.hasEffectsOnInteractionAtPath([this.getPropertyKey()], this.accessInteraction, context)));
  10444. }
  10445. includeProperties(context, includeChildrenRecursively) {
  10446. if (!this.included) {
  10447. this.included = true;
  10448. if (this.variable) {
  10449. this.context.includeVariableInModule(this.variable);
  10450. }
  10451. }
  10452. this.object.include(context, includeChildrenRecursively);
  10453. this.property.include(context, includeChildrenRecursively);
  10454. }
  10455. }
  10456. function resolveNamespaceVariables(baseVariable, path, astContext) {
  10457. if (path.length === 0)
  10458. return baseVariable;
  10459. if (!baseVariable.isNamespace || baseVariable instanceof ExternalVariable)
  10460. return null;
  10461. const exportName = path[0].key;
  10462. const variable = baseVariable.context.traceExport(exportName);
  10463. if (!variable) {
  10464. if (path.length === 1) {
  10465. const fileName = baseVariable.context.fileName;
  10466. astContext.log(LOGLEVEL_WARN, logMissingExport(exportName, astContext.module.id, fileName), path[0].pos);
  10467. return 'undefined';
  10468. }
  10469. return null;
  10470. }
  10471. return resolveNamespaceVariables(variable, path.slice(1), astContext);
  10472. }
  10473. class CallExpressionBase extends NodeBase {
  10474. constructor() {
  10475. super(...arguments);
  10476. this.returnExpression = null;
  10477. this.deoptimizableDependentExpressions = [];
  10478. this.expressionsToBeDeoptimized = new Set();
  10479. }
  10480. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  10481. const { args } = interaction;
  10482. const [returnExpression, isPure] = this.getReturnExpression(recursionTracker);
  10483. if (isPure)
  10484. return;
  10485. const deoptimizedExpressions = args.filter(expression => !!expression && expression !== UNKNOWN_EXPRESSION);
  10486. if (deoptimizedExpressions.length === 0)
  10487. return;
  10488. if (returnExpression === UNKNOWN_EXPRESSION) {
  10489. for (const expression of deoptimizedExpressions) {
  10490. expression.deoptimizePath(UNKNOWN_PATH);
  10491. }
  10492. }
  10493. else {
  10494. recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  10495. for (const expression of deoptimizedExpressions) {
  10496. this.expressionsToBeDeoptimized.add(expression);
  10497. }
  10498. returnExpression.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  10499. }, null);
  10500. }
  10501. }
  10502. deoptimizeCache() {
  10503. if (this.returnExpression?.[0] !== UNKNOWN_EXPRESSION) {
  10504. this.returnExpression = UNKNOWN_RETURN_EXPRESSION;
  10505. const { deoptimizableDependentExpressions, expressionsToBeDeoptimized } = this;
  10506. this.expressionsToBeDeoptimized = EMPTY_SET;
  10507. this.deoptimizableDependentExpressions = EMPTY_ARRAY;
  10508. for (const expression of deoptimizableDependentExpressions) {
  10509. expression.deoptimizeCache();
  10510. }
  10511. for (const expression of expressionsToBeDeoptimized) {
  10512. expression.deoptimizePath(UNKNOWN_PATH);
  10513. }
  10514. }
  10515. }
  10516. deoptimizePath(path) {
  10517. if (path.length === 0 ||
  10518. this.context.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  10519. return;
  10520. }
  10521. const [returnExpression] = this.getReturnExpression();
  10522. if (returnExpression !== UNKNOWN_EXPRESSION) {
  10523. returnExpression.deoptimizePath(path);
  10524. }
  10525. }
  10526. getLiteralValueAtPath(path, recursionTracker, origin) {
  10527. const [returnExpression] = this.getReturnExpression(recursionTracker);
  10528. if (returnExpression === UNKNOWN_EXPRESSION) {
  10529. return UnknownValue;
  10530. }
  10531. return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  10532. this.deoptimizableDependentExpressions.push(origin);
  10533. return returnExpression.getLiteralValueAtPath(path, recursionTracker, origin);
  10534. }, UnknownValue);
  10535. }
  10536. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  10537. const returnExpression = this.getReturnExpression(recursionTracker);
  10538. if (returnExpression[0] === UNKNOWN_EXPRESSION) {
  10539. return returnExpression;
  10540. }
  10541. return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  10542. this.deoptimizableDependentExpressions.push(origin);
  10543. const [expression, isPure] = returnExpression[0].getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  10544. return [expression, isPure || returnExpression[1]];
  10545. }, UNKNOWN_RETURN_EXPRESSION);
  10546. }
  10547. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10548. const { type } = interaction;
  10549. if (type === INTERACTION_CALLED) {
  10550. const { args, withNew } = interaction;
  10551. if ((withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, args, this)) {
  10552. return false;
  10553. }
  10554. }
  10555. else if ((type === INTERACTION_ASSIGNED
  10556. ? context.assigned
  10557. : context.accessed).trackEntityAtPathAndGetIfTracked(path, this)) {
  10558. return false;
  10559. }
  10560. const [returnExpression, isPure] = this.getReturnExpression();
  10561. return ((type === INTERACTION_ASSIGNED || !isPure) &&
  10562. returnExpression.hasEffectsOnInteractionAtPath(path, interaction, context));
  10563. }
  10564. }
  10565. class CallExpression extends CallExpressionBase {
  10566. bind() {
  10567. super.bind();
  10568. if (this.callee instanceof Identifier) {
  10569. const variable = this.scope.findVariable(this.callee.name);
  10570. if (variable.isNamespace) {
  10571. this.context.log(LOGLEVEL_WARN, logCannotCallNamespace(this.callee.name), this.start);
  10572. }
  10573. if (this.callee.name === 'eval') {
  10574. this.context.log(LOGLEVEL_WARN, logEval(this.context.module.id), this.start);
  10575. }
  10576. }
  10577. this.interaction = {
  10578. args: [
  10579. this.callee instanceof MemberExpression && !this.callee.variable
  10580. ? this.callee.object
  10581. : null,
  10582. ...this.arguments
  10583. ],
  10584. type: INTERACTION_CALLED,
  10585. withNew: false
  10586. };
  10587. }
  10588. hasEffects(context) {
  10589. try {
  10590. for (const argument of this.arguments) {
  10591. if (argument.hasEffects(context))
  10592. return true;
  10593. }
  10594. if (this.annotationPure) {
  10595. return false;
  10596. }
  10597. return (this.callee.hasEffects(context) ||
  10598. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  10599. }
  10600. finally {
  10601. if (!this.deoptimized)
  10602. this.applyDeoptimizations();
  10603. }
  10604. }
  10605. include(context, includeChildrenRecursively) {
  10606. if (!this.deoptimized)
  10607. this.applyDeoptimizations();
  10608. if (includeChildrenRecursively) {
  10609. super.include(context, includeChildrenRecursively);
  10610. if (includeChildrenRecursively === INCLUDE_PARAMETERS &&
  10611. this.callee instanceof Identifier &&
  10612. this.callee.variable) {
  10613. this.callee.variable.markCalledFromTryStatement();
  10614. }
  10615. }
  10616. else {
  10617. this.included = true;
  10618. this.callee.include(context, false);
  10619. }
  10620. this.callee.includeCallArguments(context, this.arguments);
  10621. }
  10622. isSkippedAsOptional(origin) {
  10623. return (this.callee.isSkippedAsOptional?.(origin) ||
  10624. (this.optional &&
  10625. this.callee.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, origin) == null));
  10626. }
  10627. render(code, options, { renderedSurroundingElement } = BLANK) {
  10628. this.callee.render(code, options, {
  10629. isCalleeOfRenderedParent: true,
  10630. renderedSurroundingElement
  10631. });
  10632. renderCallArguments(code, options, this);
  10633. }
  10634. applyDeoptimizations() {
  10635. this.deoptimized = true;
  10636. this.callee.deoptimizeArgumentsOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  10637. this.context.requestTreeshakingPass();
  10638. }
  10639. getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) {
  10640. if (this.returnExpression === null) {
  10641. this.returnExpression = UNKNOWN_RETURN_EXPRESSION;
  10642. return (this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.interaction, recursionTracker, this));
  10643. }
  10644. return this.returnExpression;
  10645. }
  10646. }
  10647. class CatchScope extends ParameterScope {
  10648. addDeclaration(identifier, context, init, isHoisted) {
  10649. const existingParameter = this.variables.get(identifier.name);
  10650. if (existingParameter) {
  10651. // While we still create a hoisted declaration, the initializer goes to
  10652. // the parameter. Note that technically, the declaration now belongs to
  10653. // two variables, which is not correct but should not cause issues.
  10654. this.parent.addDeclaration(identifier, context, UNDEFINED_EXPRESSION, isHoisted);
  10655. existingParameter.addDeclaration(identifier, init);
  10656. return existingParameter;
  10657. }
  10658. return this.parent.addDeclaration(identifier, context, init, isHoisted);
  10659. }
  10660. }
  10661. class CatchClause extends NodeBase {
  10662. createScope(parentScope) {
  10663. this.scope = new CatchScope(parentScope, this.context);
  10664. }
  10665. parseNode(esTreeNode) {
  10666. // Parameters need to be declared first as the logic is that initializers
  10667. // of hoisted body variables are associated with parameters of the same
  10668. // name instead of the variable
  10669. const { param } = esTreeNode;
  10670. if (param) {
  10671. this.param = new (this.context.getNodeConstructor(param.type))(param, this, this.scope);
  10672. this.param.declare('parameter', UNKNOWN_EXPRESSION);
  10673. }
  10674. super.parseNode(esTreeNode);
  10675. }
  10676. }
  10677. class ChainExpression extends NodeBase {
  10678. // deoptimizations are not relevant as we are not caching values
  10679. deoptimizeCache() { }
  10680. getLiteralValueAtPath(path, recursionTracker, origin) {
  10681. if (this.expression.isSkippedAsOptional(origin))
  10682. return undefined;
  10683. return this.expression.getLiteralValueAtPath(path, recursionTracker, origin);
  10684. }
  10685. hasEffects(context) {
  10686. if (this.expression.isSkippedAsOptional(this))
  10687. return false;
  10688. return this.expression.hasEffects(context);
  10689. }
  10690. }
  10691. class ClassBodyScope extends ChildScope {
  10692. constructor(parent, classNode, context) {
  10693. super(parent);
  10694. this.variables.set('this', (this.thisVariable = new LocalVariable('this', null, classNode, context)));
  10695. this.instanceScope = new ChildScope(this);
  10696. this.instanceScope.variables.set('this', new ThisVariable(context));
  10697. }
  10698. findLexicalBoundary() {
  10699. return this;
  10700. }
  10701. }
  10702. class ClassBody extends NodeBase {
  10703. createScope(parentScope) {
  10704. this.scope = new ClassBodyScope(parentScope, this.parent, this.context);
  10705. }
  10706. include(context, includeChildrenRecursively) {
  10707. this.included = true;
  10708. this.context.includeVariableInModule(this.scope.thisVariable);
  10709. for (const definition of this.body) {
  10710. definition.include(context, includeChildrenRecursively);
  10711. }
  10712. }
  10713. parseNode(esTreeNode) {
  10714. const body = (this.body = []);
  10715. for (const definition of esTreeNode.body) {
  10716. body.push(new (this.context.getNodeConstructor(definition.type))(definition, this, definition.static ? this.scope : this.scope.instanceScope));
  10717. }
  10718. super.parseNode(esTreeNode);
  10719. }
  10720. applyDeoptimizations() { }
  10721. }
  10722. class MethodBase extends NodeBase {
  10723. constructor() {
  10724. super(...arguments);
  10725. this.accessedValue = null;
  10726. }
  10727. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  10728. if (interaction.type === INTERACTION_ACCESSED && this.kind === 'get' && path.length === 0) {
  10729. return this.value.deoptimizeArgumentsOnInteractionAtPath({
  10730. args: interaction.args,
  10731. type: INTERACTION_CALLED,
  10732. withNew: false
  10733. }, EMPTY_PATH, recursionTracker);
  10734. }
  10735. if (interaction.type === INTERACTION_ASSIGNED && this.kind === 'set' && path.length === 0) {
  10736. return this.value.deoptimizeArgumentsOnInteractionAtPath({
  10737. args: interaction.args,
  10738. type: INTERACTION_CALLED,
  10739. withNew: false
  10740. }, EMPTY_PATH, recursionTracker);
  10741. }
  10742. this.getAccessedValue()[0].deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  10743. }
  10744. // As getter properties directly receive their values from fixed function
  10745. // expressions, there is no known situation where a getter is deoptimized.
  10746. deoptimizeCache() { }
  10747. deoptimizePath(path) {
  10748. this.getAccessedValue()[0].deoptimizePath(path);
  10749. }
  10750. getLiteralValueAtPath(path, recursionTracker, origin) {
  10751. return this.getAccessedValue()[0].getLiteralValueAtPath(path, recursionTracker, origin);
  10752. }
  10753. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  10754. return this.getAccessedValue()[0].getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  10755. }
  10756. hasEffects(context) {
  10757. return this.key.hasEffects(context);
  10758. }
  10759. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10760. if (this.kind === 'get' && interaction.type === INTERACTION_ACCESSED && path.length === 0) {
  10761. return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
  10762. args: interaction.args,
  10763. type: INTERACTION_CALLED,
  10764. withNew: false
  10765. }, context);
  10766. }
  10767. // setters are only called for empty paths
  10768. if (this.kind === 'set' && interaction.type === INTERACTION_ASSIGNED) {
  10769. return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
  10770. args: interaction.args,
  10771. type: INTERACTION_CALLED,
  10772. withNew: false
  10773. }, context);
  10774. }
  10775. return this.getAccessedValue()[0].hasEffectsOnInteractionAtPath(path, interaction, context);
  10776. }
  10777. applyDeoptimizations() { }
  10778. getAccessedValue() {
  10779. if (this.accessedValue === null) {
  10780. if (this.kind === 'get') {
  10781. this.accessedValue = UNKNOWN_RETURN_EXPRESSION;
  10782. return (this.accessedValue = this.value.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, SHARED_RECURSION_TRACKER, this));
  10783. }
  10784. else {
  10785. return (this.accessedValue = [this.value, false]);
  10786. }
  10787. }
  10788. return this.accessedValue;
  10789. }
  10790. }
  10791. class MethodDefinition extends MethodBase {
  10792. applyDeoptimizations() { }
  10793. }
  10794. class ObjectMember extends ExpressionEntity {
  10795. constructor(object, key) {
  10796. super();
  10797. this.object = object;
  10798. this.key = key;
  10799. }
  10800. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  10801. this.object.deoptimizeArgumentsOnInteractionAtPath(interaction, [this.key, ...path], recursionTracker);
  10802. }
  10803. deoptimizePath(path) {
  10804. this.object.deoptimizePath([this.key, ...path]);
  10805. }
  10806. getLiteralValueAtPath(path, recursionTracker, origin) {
  10807. return this.object.getLiteralValueAtPath([this.key, ...path], recursionTracker, origin);
  10808. }
  10809. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  10810. return this.object.getReturnExpressionWhenCalledAtPath([this.key, ...path], interaction, recursionTracker, origin);
  10811. }
  10812. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10813. return this.object.hasEffectsOnInteractionAtPath([this.key, ...path], interaction, context);
  10814. }
  10815. }
  10816. class ClassNode extends NodeBase {
  10817. constructor() {
  10818. super(...arguments);
  10819. this.objectEntity = null;
  10820. }
  10821. createScope(parentScope) {
  10822. this.scope = new ChildScope(parentScope);
  10823. }
  10824. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  10825. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  10826. }
  10827. deoptimizeCache() {
  10828. this.getObjectEntity().deoptimizeAllProperties();
  10829. }
  10830. deoptimizePath(path) {
  10831. this.getObjectEntity().deoptimizePath(path);
  10832. }
  10833. getLiteralValueAtPath(path, recursionTracker, origin) {
  10834. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  10835. }
  10836. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  10837. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  10838. }
  10839. hasEffects(context) {
  10840. if (!this.deoptimized)
  10841. this.applyDeoptimizations();
  10842. const initEffect = this.superClass?.hasEffects(context) || this.body.hasEffects(context);
  10843. this.id?.markDeclarationReached();
  10844. return initEffect || super.hasEffects(context);
  10845. }
  10846. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10847. return interaction.type === INTERACTION_CALLED && path.length === 0
  10848. ? !interaction.withNew ||
  10849. (this.classConstructor === null
  10850. ? this.superClass?.hasEffectsOnInteractionAtPath(path, interaction, context)
  10851. : this.classConstructor.hasEffectsOnInteractionAtPath(path, interaction, context)) ||
  10852. false
  10853. : this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  10854. }
  10855. include(context, includeChildrenRecursively) {
  10856. if (!this.deoptimized)
  10857. this.applyDeoptimizations();
  10858. this.included = true;
  10859. this.superClass?.include(context, includeChildrenRecursively);
  10860. this.body.include(context, includeChildrenRecursively);
  10861. if (this.id) {
  10862. this.id.markDeclarationReached();
  10863. this.id.include();
  10864. }
  10865. }
  10866. initialise() {
  10867. this.id?.declare('class', this);
  10868. for (const method of this.body.body) {
  10869. if (method instanceof MethodDefinition && method.kind === 'constructor') {
  10870. this.classConstructor = method;
  10871. return;
  10872. }
  10873. }
  10874. this.classConstructor = null;
  10875. }
  10876. applyDeoptimizations() {
  10877. this.deoptimized = true;
  10878. for (const definition of this.body.body) {
  10879. if (!(definition.static ||
  10880. (definition instanceof MethodDefinition && definition.kind === 'constructor'))) {
  10881. // Calls to methods are not tracked, ensure that the return value is deoptimized
  10882. definition.deoptimizePath(UNKNOWN_PATH);
  10883. }
  10884. }
  10885. this.context.requestTreeshakingPass();
  10886. }
  10887. getObjectEntity() {
  10888. if (this.objectEntity !== null) {
  10889. return this.objectEntity;
  10890. }
  10891. const staticProperties = [];
  10892. const dynamicMethods = [];
  10893. for (const definition of this.body.body) {
  10894. const properties = definition.static ? staticProperties : dynamicMethods;
  10895. const definitionKind = definition.kind;
  10896. // Note that class fields do not end up on the prototype
  10897. if (properties === dynamicMethods && !definitionKind)
  10898. continue;
  10899. const kind = definitionKind === 'set' || definitionKind === 'get' ? definitionKind : 'init';
  10900. let key;
  10901. if (definition.computed) {
  10902. const keyValue = definition.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  10903. if (typeof keyValue === 'symbol') {
  10904. properties.push({ key: UnknownKey, kind, property: definition });
  10905. continue;
  10906. }
  10907. else {
  10908. key = String(keyValue);
  10909. }
  10910. }
  10911. else {
  10912. key =
  10913. definition.key instanceof Identifier
  10914. ? definition.key.name
  10915. : String(definition.key.value);
  10916. }
  10917. properties.push({ key, kind, property: definition });
  10918. }
  10919. staticProperties.unshift({
  10920. key: 'prototype',
  10921. kind: 'init',
  10922. property: new ObjectEntity(dynamicMethods, this.superClass ? new ObjectMember(this.superClass, 'prototype') : OBJECT_PROTOTYPE)
  10923. });
  10924. return (this.objectEntity = new ObjectEntity(staticProperties, this.superClass || OBJECT_PROTOTYPE));
  10925. }
  10926. }
  10927. class ClassDeclaration extends ClassNode {
  10928. initialise() {
  10929. super.initialise();
  10930. if (this.id !== null) {
  10931. this.id.variable.isId = true;
  10932. }
  10933. }
  10934. parseNode(esTreeNode) {
  10935. if (esTreeNode.id !== null) {
  10936. this.id = new Identifier(esTreeNode.id, this, this.scope.parent);
  10937. }
  10938. super.parseNode(esTreeNode);
  10939. }
  10940. render(code, options) {
  10941. const { exportNamesByVariable, format, snippets: { _, getPropertyAccess } } = options;
  10942. if (this.id) {
  10943. const { variable, name } = this.id;
  10944. if (format === 'system' && exportNamesByVariable.has(variable)) {
  10945. code.appendLeft(this.end, `${_}${getSystemExportStatement([variable], options)};`);
  10946. }
  10947. const renderedVariable = variable.getName(getPropertyAccess);
  10948. if (renderedVariable !== name) {
  10949. this.superClass?.render(code, options);
  10950. this.body.render(code, {
  10951. ...options,
  10952. useOriginalName: (_variable) => _variable === variable
  10953. });
  10954. code.prependRight(this.start, `let ${renderedVariable}${_}=${_}`);
  10955. code.prependLeft(this.end, ';');
  10956. return;
  10957. }
  10958. }
  10959. super.render(code, options);
  10960. }
  10961. applyDeoptimizations() {
  10962. super.applyDeoptimizations();
  10963. const { id, scope } = this;
  10964. if (id) {
  10965. const { name, variable } = id;
  10966. for (const accessedVariable of scope.accessedOutsideVariables.values()) {
  10967. if (accessedVariable !== variable) {
  10968. accessedVariable.forbidName(name);
  10969. }
  10970. }
  10971. }
  10972. }
  10973. }
  10974. class ClassExpression extends ClassNode {
  10975. render(code, options, { renderedSurroundingElement } = BLANK) {
  10976. super.render(code, options);
  10977. if (renderedSurroundingElement === ExpressionStatement$1) {
  10978. code.appendRight(this.start, '(');
  10979. code.prependLeft(this.end, ')');
  10980. }
  10981. }
  10982. }
  10983. class MultiExpression extends ExpressionEntity {
  10984. constructor(expressions) {
  10985. super();
  10986. this.expressions = expressions;
  10987. this.included = false;
  10988. }
  10989. deoptimizePath(path) {
  10990. for (const expression of this.expressions) {
  10991. expression.deoptimizePath(path);
  10992. }
  10993. }
  10994. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  10995. return [
  10996. new MultiExpression(this.expressions.map(expression => expression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0])),
  10997. false
  10998. ];
  10999. }
  11000. hasEffectsOnInteractionAtPath(path, interaction, context) {
  11001. for (const expression of this.expressions) {
  11002. if (expression.hasEffectsOnInteractionAtPath(path, interaction, context))
  11003. return true;
  11004. }
  11005. return false;
  11006. }
  11007. }
  11008. class ConditionalExpression extends NodeBase {
  11009. constructor() {
  11010. super(...arguments);
  11011. this.expressionsToBeDeoptimized = [];
  11012. this.isBranchResolutionAnalysed = false;
  11013. this.usedBranch = null;
  11014. }
  11015. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  11016. this.consequent.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  11017. this.alternate.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  11018. }
  11019. deoptimizeCache() {
  11020. if (this.usedBranch !== null) {
  11021. const unusedBranch = this.usedBranch === this.consequent ? this.alternate : this.consequent;
  11022. this.usedBranch = null;
  11023. unusedBranch.deoptimizePath(UNKNOWN_PATH);
  11024. const { expressionsToBeDeoptimized } = this;
  11025. this.expressionsToBeDeoptimized = EMPTY_ARRAY;
  11026. for (const expression of expressionsToBeDeoptimized) {
  11027. expression.deoptimizeCache();
  11028. }
  11029. }
  11030. }
  11031. deoptimizePath(path) {
  11032. const usedBranch = this.getUsedBranch();
  11033. if (usedBranch) {
  11034. usedBranch.deoptimizePath(path);
  11035. }
  11036. else {
  11037. this.consequent.deoptimizePath(path);
  11038. this.alternate.deoptimizePath(path);
  11039. }
  11040. }
  11041. getLiteralValueAtPath(path, recursionTracker, origin) {
  11042. const usedBranch = this.getUsedBranch();
  11043. if (!usedBranch)
  11044. return UnknownValue;
  11045. this.expressionsToBeDeoptimized.push(origin);
  11046. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  11047. }
  11048. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  11049. const usedBranch = this.getUsedBranch();
  11050. if (!usedBranch)
  11051. return [
  11052. new MultiExpression([
  11053. this.consequent.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0],
  11054. this.alternate.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0]
  11055. ]),
  11056. false
  11057. ];
  11058. this.expressionsToBeDeoptimized.push(origin);
  11059. return usedBranch.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  11060. }
  11061. hasEffects(context) {
  11062. if (this.test.hasEffects(context))
  11063. return true;
  11064. const usedBranch = this.getUsedBranch();
  11065. if (!usedBranch) {
  11066. return this.consequent.hasEffects(context) || this.alternate.hasEffects(context);
  11067. }
  11068. return usedBranch.hasEffects(context);
  11069. }
  11070. hasEffectsOnInteractionAtPath(path, interaction, context) {
  11071. const usedBranch = this.getUsedBranch();
  11072. if (!usedBranch) {
  11073. return (this.consequent.hasEffectsOnInteractionAtPath(path, interaction, context) ||
  11074. this.alternate.hasEffectsOnInteractionAtPath(path, interaction, context));
  11075. }
  11076. return usedBranch.hasEffectsOnInteractionAtPath(path, interaction, context);
  11077. }
  11078. include(context, includeChildrenRecursively) {
  11079. this.included = true;
  11080. const usedBranch = this.getUsedBranch();
  11081. if (includeChildrenRecursively || this.test.shouldBeIncluded(context) || usedBranch === null) {
  11082. this.test.include(context, includeChildrenRecursively);
  11083. this.consequent.include(context, includeChildrenRecursively);
  11084. this.alternate.include(context, includeChildrenRecursively);
  11085. }
  11086. else {
  11087. usedBranch.include(context, includeChildrenRecursively);
  11088. }
  11089. }
  11090. includeCallArguments(context, parameters) {
  11091. const usedBranch = this.getUsedBranch();
  11092. if (usedBranch) {
  11093. usedBranch.includeCallArguments(context, parameters);
  11094. }
  11095. else {
  11096. this.consequent.includeCallArguments(context, parameters);
  11097. this.alternate.includeCallArguments(context, parameters);
  11098. }
  11099. }
  11100. render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  11101. const usedBranch = this.getUsedBranch();
  11102. if (this.test.included) {
  11103. this.test.render(code, options, { renderedSurroundingElement });
  11104. this.consequent.render(code, options);
  11105. this.alternate.render(code, options);
  11106. }
  11107. else {
  11108. const colonPos = findFirstOccurrenceOutsideComment(code.original, ':', this.consequent.end);
  11109. const inclusionStart = findNonWhiteSpace(code.original, (this.consequent.included
  11110. ? findFirstOccurrenceOutsideComment(code.original, '?', this.test.end)
  11111. : colonPos) + 1);
  11112. if (preventASI) {
  11113. removeLineBreaks(code, inclusionStart, usedBranch.start);
  11114. }
  11115. code.remove(this.start, inclusionStart);
  11116. if (this.consequent.included) {
  11117. code.remove(colonPos, this.end);
  11118. }
  11119. removeAnnotations(this, code);
  11120. usedBranch.render(code, options, {
  11121. isCalleeOfRenderedParent,
  11122. preventASI: true,
  11123. renderedParentType: renderedParentType || this.parent.type,
  11124. renderedSurroundingElement: renderedSurroundingElement || this.parent.type
  11125. });
  11126. }
  11127. }
  11128. getUsedBranch() {
  11129. if (this.isBranchResolutionAnalysed) {
  11130. return this.usedBranch;
  11131. }
  11132. this.isBranchResolutionAnalysed = true;
  11133. const testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  11134. return typeof testValue === 'symbol'
  11135. ? null
  11136. : (this.usedBranch = testValue ? this.consequent : this.alternate);
  11137. }
  11138. }
  11139. class ContinueStatement extends NodeBase {
  11140. hasEffects(context) {
  11141. if (this.label) {
  11142. if (!context.ignore.labels.has(this.label.name))
  11143. return true;
  11144. context.includedLabels.add(this.label.name);
  11145. }
  11146. else {
  11147. if (!context.ignore.continues)
  11148. return true;
  11149. context.hasContinue = true;
  11150. }
  11151. context.brokenFlow = true;
  11152. return false;
  11153. }
  11154. include(context) {
  11155. this.included = true;
  11156. if (this.label) {
  11157. this.label.include();
  11158. context.includedLabels.add(this.label.name);
  11159. }
  11160. else {
  11161. context.hasContinue = true;
  11162. }
  11163. context.brokenFlow = true;
  11164. }
  11165. }
  11166. function hasLoopBodyEffects(context, body) {
  11167. const { brokenFlow, hasBreak, hasContinue, ignore } = context;
  11168. const { breaks, continues } = ignore;
  11169. ignore.breaks = true;
  11170. ignore.continues = true;
  11171. context.hasBreak = false;
  11172. context.hasContinue = false;
  11173. if (body.hasEffects(context))
  11174. return true;
  11175. ignore.breaks = breaks;
  11176. ignore.continues = continues;
  11177. context.hasBreak = hasBreak;
  11178. context.hasContinue = hasContinue;
  11179. context.brokenFlow = brokenFlow;
  11180. return false;
  11181. }
  11182. function includeLoopBody(context, body, includeChildrenRecursively) {
  11183. const { brokenFlow, hasBreak, hasContinue } = context;
  11184. context.hasBreak = false;
  11185. context.hasContinue = false;
  11186. body.include(context, includeChildrenRecursively, { asSingleStatement: true });
  11187. context.hasBreak = hasBreak;
  11188. context.hasContinue = hasContinue;
  11189. context.brokenFlow = brokenFlow;
  11190. }
  11191. class DoWhileStatement extends NodeBase {
  11192. hasEffects(context) {
  11193. if (this.test.hasEffects(context))
  11194. return true;
  11195. return hasLoopBodyEffects(context, this.body);
  11196. }
  11197. include(context, includeChildrenRecursively) {
  11198. this.included = true;
  11199. this.test.include(context, includeChildrenRecursively);
  11200. includeLoopBody(context, this.body, includeChildrenRecursively);
  11201. }
  11202. }
  11203. class EmptyStatement extends NodeBase {
  11204. hasEffects() {
  11205. return false;
  11206. }
  11207. }
  11208. class ExportAllDeclaration extends NodeBase {
  11209. hasEffects() {
  11210. return false;
  11211. }
  11212. initialise() {
  11213. this.context.addExport(this);
  11214. }
  11215. render(code, _options, nodeRenderOptions) {
  11216. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  11217. }
  11218. applyDeoptimizations() { }
  11219. }
  11220. ExportAllDeclaration.prototype.needsBoundaries = true;
  11221. class FunctionDeclaration extends FunctionNode {
  11222. initialise() {
  11223. super.initialise();
  11224. if (this.id !== null) {
  11225. this.id.variable.isId = true;
  11226. }
  11227. }
  11228. parseNode(esTreeNode) {
  11229. if (esTreeNode.id !== null) {
  11230. this.id = new Identifier(esTreeNode.id, this, this.scope.parent);
  11231. }
  11232. super.parseNode(esTreeNode);
  11233. }
  11234. }
  11235. // The header ends at the first non-white-space after "default"
  11236. function getDeclarationStart(code, start) {
  11237. return findNonWhiteSpace(code, findFirstOccurrenceOutsideComment(code, 'default', start) + 7);
  11238. }
  11239. function getFunctionIdInsertPosition(code, start) {
  11240. const declarationEnd = findFirstOccurrenceOutsideComment(code, 'function', start) + 'function'.length;
  11241. code = code.slice(declarationEnd, findFirstOccurrenceOutsideComment(code, '(', declarationEnd));
  11242. const generatorStarPos = findFirstOccurrenceOutsideComment(code, '*');
  11243. if (generatorStarPos === -1) {
  11244. return declarationEnd;
  11245. }
  11246. return declarationEnd + generatorStarPos + 1;
  11247. }
  11248. class ExportDefaultDeclaration extends NodeBase {
  11249. include(context, includeChildrenRecursively) {
  11250. super.include(context, includeChildrenRecursively);
  11251. if (includeChildrenRecursively) {
  11252. this.context.includeVariableInModule(this.variable);
  11253. }
  11254. }
  11255. initialise() {
  11256. const declaration = this.declaration;
  11257. this.declarationName =
  11258. (declaration.id && declaration.id.name) || this.declaration.name;
  11259. this.variable = this.scope.addExportDefaultDeclaration(this.declarationName || this.context.getModuleName(), this, this.context);
  11260. this.context.addExport(this);
  11261. }
  11262. render(code, options, nodeRenderOptions) {
  11263. const { start, end } = nodeRenderOptions;
  11264. const declarationStart = getDeclarationStart(code.original, this.start);
  11265. if (this.declaration instanceof FunctionDeclaration) {
  11266. this.renderNamedDeclaration(code, declarationStart, this.declaration.id === null
  11267. ? getFunctionIdInsertPosition(code.original, declarationStart)
  11268. : null, options);
  11269. }
  11270. else if (this.declaration instanceof ClassDeclaration) {
  11271. this.renderNamedDeclaration(code, declarationStart, this.declaration.id === null
  11272. ? findFirstOccurrenceOutsideComment(code.original, 'class', start) + 'class'.length
  11273. : null, options);
  11274. }
  11275. else if (this.variable.getOriginalVariable() !== this.variable) {
  11276. // Remove altogether to prevent re-declaring the same variable
  11277. treeshakeNode(this, code, start, end);
  11278. return;
  11279. }
  11280. else if (this.variable.included) {
  11281. this.renderVariableDeclaration(code, declarationStart, options);
  11282. }
  11283. else {
  11284. code.remove(this.start, declarationStart);
  11285. this.declaration.render(code, options, {
  11286. renderedSurroundingElement: ExpressionStatement$1
  11287. });
  11288. if (code.original[this.end - 1] !== ';') {
  11289. code.appendLeft(this.end, ';');
  11290. }
  11291. return;
  11292. }
  11293. this.declaration.render(code, options);
  11294. }
  11295. applyDeoptimizations() { }
  11296. renderNamedDeclaration(code, declarationStart, idInsertPosition, options) {
  11297. const { exportNamesByVariable, format, snippets: { getPropertyAccess } } = options;
  11298. const name = this.variable.getName(getPropertyAccess);
  11299. // Remove `export default`
  11300. code.remove(this.start, declarationStart);
  11301. if (idInsertPosition !== null) {
  11302. code.appendLeft(idInsertPosition, ` ${name}`);
  11303. }
  11304. if (format === 'system' &&
  11305. this.declaration instanceof ClassDeclaration &&
  11306. exportNamesByVariable.has(this.variable)) {
  11307. code.appendLeft(this.end, ` ${getSystemExportStatement([this.variable], options)};`);
  11308. }
  11309. }
  11310. renderVariableDeclaration(code, declarationStart, { format, exportNamesByVariable, snippets: { cnst, getPropertyAccess } }) {
  11311. const hasTrailingSemicolon = code.original.charCodeAt(this.end - 1) === 59; /*";"*/
  11312. const systemExportNames = format === 'system' && exportNamesByVariable.get(this.variable);
  11313. if (systemExportNames) {
  11314. code.overwrite(this.start, declarationStart, `${cnst} ${this.variable.getName(getPropertyAccess)} = exports('${systemExportNames[0]}', `);
  11315. code.appendRight(hasTrailingSemicolon ? this.end - 1 : this.end, ')' + (hasTrailingSemicolon ? '' : ';'));
  11316. }
  11317. else {
  11318. code.overwrite(this.start, declarationStart, `${cnst} ${this.variable.getName(getPropertyAccess)} = `);
  11319. if (!hasTrailingSemicolon) {
  11320. code.appendLeft(this.end, ';');
  11321. }
  11322. }
  11323. }
  11324. }
  11325. ExportDefaultDeclaration.prototype.needsBoundaries = true;
  11326. class ExportNamedDeclaration extends NodeBase {
  11327. bind() {
  11328. // Do not bind specifiers
  11329. this.declaration?.bind();
  11330. }
  11331. hasEffects(context) {
  11332. return !!this.declaration?.hasEffects(context);
  11333. }
  11334. initialise() {
  11335. this.context.addExport(this);
  11336. }
  11337. render(code, options, nodeRenderOptions) {
  11338. const { start, end } = nodeRenderOptions;
  11339. if (this.declaration === null) {
  11340. code.remove(start, end);
  11341. }
  11342. else {
  11343. code.remove(this.start, this.declaration.start);
  11344. this.declaration.render(code, options, { end, start });
  11345. }
  11346. }
  11347. applyDeoptimizations() { }
  11348. }
  11349. ExportNamedDeclaration.prototype.needsBoundaries = true;
  11350. class ExportSpecifier extends NodeBase {
  11351. applyDeoptimizations() { }
  11352. }
  11353. class ForInStatement extends NodeBase {
  11354. createScope(parentScope) {
  11355. this.scope = new BlockScope(parentScope);
  11356. }
  11357. hasEffects(context) {
  11358. const { body, deoptimized, left, right } = this;
  11359. if (!deoptimized)
  11360. this.applyDeoptimizations();
  11361. if (left.hasEffectsAsAssignmentTarget(context, false) || right.hasEffects(context))
  11362. return true;
  11363. return hasLoopBodyEffects(context, body);
  11364. }
  11365. include(context, includeChildrenRecursively) {
  11366. const { body, deoptimized, left, right } = this;
  11367. if (!deoptimized)
  11368. this.applyDeoptimizations();
  11369. this.included = true;
  11370. left.includeAsAssignmentTarget(context, includeChildrenRecursively || true, false);
  11371. right.include(context, includeChildrenRecursively);
  11372. includeLoopBody(context, body, includeChildrenRecursively);
  11373. }
  11374. initialise() {
  11375. this.left.setAssignedValue(UNKNOWN_EXPRESSION);
  11376. }
  11377. render(code, options) {
  11378. this.left.render(code, options, NO_SEMICOLON);
  11379. this.right.render(code, options, NO_SEMICOLON);
  11380. // handle no space between "in" and the right side
  11381. if (code.original.charCodeAt(this.right.start - 1) === 110 /* n */) {
  11382. code.prependLeft(this.right.start, ' ');
  11383. }
  11384. this.body.render(code, options);
  11385. }
  11386. applyDeoptimizations() {
  11387. this.deoptimized = true;
  11388. this.left.deoptimizePath(EMPTY_PATH);
  11389. this.context.requestTreeshakingPass();
  11390. }
  11391. }
  11392. class ForOfStatement extends NodeBase {
  11393. createScope(parentScope) {
  11394. this.scope = new BlockScope(parentScope);
  11395. }
  11396. hasEffects() {
  11397. if (!this.deoptimized)
  11398. this.applyDeoptimizations();
  11399. // Placeholder until proper Symbol.Iterator support
  11400. return true;
  11401. }
  11402. include(context, includeChildrenRecursively) {
  11403. const { body, deoptimized, left, right } = this;
  11404. if (!deoptimized)
  11405. this.applyDeoptimizations();
  11406. this.included = true;
  11407. left.includeAsAssignmentTarget(context, includeChildrenRecursively || true, false);
  11408. right.include(context, includeChildrenRecursively);
  11409. includeLoopBody(context, body, includeChildrenRecursively);
  11410. }
  11411. initialise() {
  11412. this.left.setAssignedValue(UNKNOWN_EXPRESSION);
  11413. }
  11414. render(code, options) {
  11415. this.left.render(code, options, NO_SEMICOLON);
  11416. this.right.render(code, options, NO_SEMICOLON);
  11417. // handle no space between "of" and the right side
  11418. if (code.original.charCodeAt(this.right.start - 1) === 102 /* f */) {
  11419. code.prependLeft(this.right.start, ' ');
  11420. }
  11421. this.body.render(code, options);
  11422. }
  11423. applyDeoptimizations() {
  11424. this.deoptimized = true;
  11425. this.left.deoptimizePath(EMPTY_PATH);
  11426. this.right.deoptimizePath(UNKNOWN_PATH);
  11427. this.context.requestTreeshakingPass();
  11428. }
  11429. }
  11430. class ForStatement extends NodeBase {
  11431. createScope(parentScope) {
  11432. this.scope = new BlockScope(parentScope);
  11433. }
  11434. hasEffects(context) {
  11435. if (this.init?.hasEffects(context) ||
  11436. this.test?.hasEffects(context) ||
  11437. this.update?.hasEffects(context)) {
  11438. return true;
  11439. }
  11440. return hasLoopBodyEffects(context, this.body);
  11441. }
  11442. include(context, includeChildrenRecursively) {
  11443. this.included = true;
  11444. this.init?.include(context, includeChildrenRecursively, { asSingleStatement: true });
  11445. this.test?.include(context, includeChildrenRecursively);
  11446. this.update?.include(context, includeChildrenRecursively);
  11447. includeLoopBody(context, this.body, includeChildrenRecursively);
  11448. }
  11449. render(code, options) {
  11450. this.init?.render(code, options, NO_SEMICOLON);
  11451. this.test?.render(code, options, NO_SEMICOLON);
  11452. this.update?.render(code, options, NO_SEMICOLON);
  11453. this.body.render(code, options);
  11454. }
  11455. }
  11456. class FunctionExpression extends FunctionNode {
  11457. render(code, options, { renderedSurroundingElement } = BLANK) {
  11458. super.render(code, options);
  11459. if (renderedSurroundingElement === ExpressionStatement$1) {
  11460. code.appendRight(this.start, '(');
  11461. code.prependLeft(this.end, ')');
  11462. }
  11463. }
  11464. }
  11465. class TrackingScope extends BlockScope {
  11466. constructor() {
  11467. super(...arguments);
  11468. this.hoistedDeclarations = [];
  11469. }
  11470. addDeclaration(identifier, context, init, isHoisted) {
  11471. this.hoistedDeclarations.push(identifier);
  11472. return super.addDeclaration(identifier, context, init, isHoisted);
  11473. }
  11474. }
  11475. const unset = Symbol('unset');
  11476. class IfStatement extends NodeBase {
  11477. constructor() {
  11478. super(...arguments);
  11479. this.testValue = unset;
  11480. }
  11481. deoptimizeCache() {
  11482. this.testValue = UnknownValue;
  11483. }
  11484. hasEffects(context) {
  11485. if (this.test.hasEffects(context)) {
  11486. return true;
  11487. }
  11488. const testValue = this.getTestValue();
  11489. if (typeof testValue === 'symbol') {
  11490. const { brokenFlow } = context;
  11491. if (this.consequent.hasEffects(context))
  11492. return true;
  11493. // eslint-disable-next-line unicorn/consistent-destructuring
  11494. const consequentBrokenFlow = context.brokenFlow;
  11495. context.brokenFlow = brokenFlow;
  11496. if (this.alternate === null)
  11497. return false;
  11498. if (this.alternate.hasEffects(context))
  11499. return true;
  11500. // eslint-disable-next-line unicorn/consistent-destructuring
  11501. context.brokenFlow = context.brokenFlow && consequentBrokenFlow;
  11502. return false;
  11503. }
  11504. return testValue ? this.consequent.hasEffects(context) : !!this.alternate?.hasEffects(context);
  11505. }
  11506. include(context, includeChildrenRecursively) {
  11507. this.included = true;
  11508. if (includeChildrenRecursively) {
  11509. this.includeRecursively(includeChildrenRecursively, context);
  11510. }
  11511. else {
  11512. const testValue = this.getTestValue();
  11513. if (typeof testValue === 'symbol') {
  11514. this.includeUnknownTest(context);
  11515. }
  11516. else {
  11517. this.includeKnownTest(context, testValue);
  11518. }
  11519. }
  11520. }
  11521. parseNode(esTreeNode) {
  11522. this.consequentScope = new TrackingScope(this.scope);
  11523. this.consequent = new (this.context.getNodeConstructor(esTreeNode.consequent.type))(esTreeNode.consequent, this, this.consequentScope);
  11524. if (esTreeNode.alternate) {
  11525. this.alternateScope = new TrackingScope(this.scope);
  11526. this.alternate = new (this.context.getNodeConstructor(esTreeNode.alternate.type))(esTreeNode.alternate, this, this.alternateScope);
  11527. }
  11528. super.parseNode(esTreeNode);
  11529. }
  11530. render(code, options) {
  11531. const { snippets: { getPropertyAccess } } = options;
  11532. // Note that unknown test values are always included
  11533. const testValue = this.getTestValue();
  11534. const hoistedDeclarations = [];
  11535. const includesIfElse = this.test.included;
  11536. const noTreeshake = !this.context.options.treeshake;
  11537. if (includesIfElse) {
  11538. this.test.render(code, options);
  11539. }
  11540. else {
  11541. code.remove(this.start, this.consequent.start);
  11542. }
  11543. if (this.consequent.included && (noTreeshake || typeof testValue === 'symbol' || testValue)) {
  11544. this.consequent.render(code, options);
  11545. }
  11546. else {
  11547. code.overwrite(this.consequent.start, this.consequent.end, includesIfElse ? ';' : '');
  11548. hoistedDeclarations.push(...this.consequentScope.hoistedDeclarations);
  11549. }
  11550. if (this.alternate) {
  11551. if (this.alternate.included && (noTreeshake || typeof testValue === 'symbol' || !testValue)) {
  11552. if (includesIfElse) {
  11553. if (code.original.charCodeAt(this.alternate.start - 1) === 101) {
  11554. code.prependLeft(this.alternate.start, ' ');
  11555. }
  11556. }
  11557. else {
  11558. code.remove(this.consequent.end, this.alternate.start);
  11559. }
  11560. this.alternate.render(code, options);
  11561. }
  11562. else {
  11563. if (includesIfElse && this.shouldKeepAlternateBranch()) {
  11564. code.overwrite(this.alternate.start, this.end, ';');
  11565. }
  11566. else {
  11567. code.remove(this.consequent.end, this.end);
  11568. }
  11569. hoistedDeclarations.push(...this.alternateScope.hoistedDeclarations);
  11570. }
  11571. }
  11572. this.renderHoistedDeclarations(hoistedDeclarations, code, getPropertyAccess);
  11573. }
  11574. applyDeoptimizations() { }
  11575. getTestValue() {
  11576. if (this.testValue === unset) {
  11577. return (this.testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this));
  11578. }
  11579. return this.testValue;
  11580. }
  11581. includeKnownTest(context, testValue) {
  11582. if (this.test.shouldBeIncluded(context)) {
  11583. this.test.include(context, false);
  11584. }
  11585. if (testValue && this.consequent.shouldBeIncluded(context)) {
  11586. this.consequent.include(context, false, { asSingleStatement: true });
  11587. }
  11588. if (!testValue && this.alternate?.shouldBeIncluded(context)) {
  11589. this.alternate.include(context, false, { asSingleStatement: true });
  11590. }
  11591. }
  11592. includeRecursively(includeChildrenRecursively, context) {
  11593. this.test.include(context, includeChildrenRecursively);
  11594. this.consequent.include(context, includeChildrenRecursively);
  11595. this.alternate?.include(context, includeChildrenRecursively);
  11596. }
  11597. includeUnknownTest(context) {
  11598. this.test.include(context, false);
  11599. const { brokenFlow } = context;
  11600. let consequentBrokenFlow = false;
  11601. if (this.consequent.shouldBeIncluded(context)) {
  11602. this.consequent.include(context, false, { asSingleStatement: true });
  11603. // eslint-disable-next-line unicorn/consistent-destructuring
  11604. consequentBrokenFlow = context.brokenFlow;
  11605. context.brokenFlow = brokenFlow;
  11606. }
  11607. if (this.alternate?.shouldBeIncluded(context)) {
  11608. this.alternate.include(context, false, { asSingleStatement: true });
  11609. // eslint-disable-next-line unicorn/consistent-destructuring
  11610. context.brokenFlow = context.brokenFlow && consequentBrokenFlow;
  11611. }
  11612. }
  11613. renderHoistedDeclarations(hoistedDeclarations, code, getPropertyAccess) {
  11614. const hoistedVariables = [
  11615. ...new Set(hoistedDeclarations.map(identifier => {
  11616. const variable = identifier.variable;
  11617. return variable.included ? variable.getName(getPropertyAccess) : '';
  11618. }))
  11619. ]
  11620. .filter(Boolean)
  11621. .join(', ');
  11622. if (hoistedVariables) {
  11623. const parentType = this.parent.type;
  11624. const needsBraces = parentType !== Program$1 && parentType !== BlockStatement$1;
  11625. code.prependRight(this.start, `${needsBraces ? '{ ' : ''}var ${hoistedVariables}; `);
  11626. if (needsBraces) {
  11627. code.appendLeft(this.end, ` }`);
  11628. }
  11629. }
  11630. }
  11631. shouldKeepAlternateBranch() {
  11632. let currentParent = this.parent;
  11633. do {
  11634. if (currentParent instanceof IfStatement && currentParent.alternate) {
  11635. return true;
  11636. }
  11637. if (currentParent instanceof BlockStatement) {
  11638. return false;
  11639. }
  11640. currentParent = currentParent.parent;
  11641. } while (currentParent);
  11642. return false;
  11643. }
  11644. }
  11645. class ImportAttribute extends NodeBase {
  11646. }
  11647. class ImportDeclaration extends NodeBase {
  11648. // Do not bind specifiers or assertions
  11649. bind() { }
  11650. hasEffects() {
  11651. return false;
  11652. }
  11653. initialise() {
  11654. this.context.addImport(this);
  11655. }
  11656. render(code, _options, nodeRenderOptions) {
  11657. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  11658. }
  11659. applyDeoptimizations() { }
  11660. }
  11661. ImportDeclaration.prototype.needsBoundaries = true;
  11662. class ImportDefaultSpecifier extends NodeBase {
  11663. applyDeoptimizations() { }
  11664. }
  11665. const INTEROP_DEFAULT_VARIABLE = '_interopDefault';
  11666. const INTEROP_DEFAULT_COMPAT_VARIABLE = '_interopDefaultCompat';
  11667. const INTEROP_NAMESPACE_VARIABLE = '_interopNamespace';
  11668. const INTEROP_NAMESPACE_COMPAT_VARIABLE = '_interopNamespaceCompat';
  11669. const INTEROP_NAMESPACE_DEFAULT_VARIABLE = '_interopNamespaceDefault';
  11670. const INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE = '_interopNamespaceDefaultOnly';
  11671. const MERGE_NAMESPACES_VARIABLE = '_mergeNamespaces';
  11672. const DOCUMENT_CURRENT_SCRIPT = '_documentCurrentScript';
  11673. const defaultInteropHelpersByInteropType = {
  11674. auto: INTEROP_DEFAULT_VARIABLE,
  11675. compat: INTEROP_DEFAULT_COMPAT_VARIABLE,
  11676. default: null,
  11677. defaultOnly: null,
  11678. esModule: null
  11679. };
  11680. const isDefaultAProperty = (interopType, externalLiveBindings) => interopType === 'esModule' ||
  11681. (externalLiveBindings && (interopType === 'auto' || interopType === 'compat'));
  11682. const namespaceInteropHelpersByInteropType = {
  11683. auto: INTEROP_NAMESPACE_VARIABLE,
  11684. compat: INTEROP_NAMESPACE_COMPAT_VARIABLE,
  11685. default: INTEROP_NAMESPACE_DEFAULT_VARIABLE,
  11686. defaultOnly: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE,
  11687. esModule: null
  11688. };
  11689. const canDefaultBeTakenFromNamespace = (interopType, externalLiveBindings) => interopType !== 'esModule' && isDefaultAProperty(interopType, externalLiveBindings);
  11690. const getHelpersBlock = (additionalHelpers, accessedGlobals, indent, snippets, liveBindings, freeze, namespaceToStringTag) => {
  11691. const usedHelpers = new Set(additionalHelpers);
  11692. for (const variable of HELPER_NAMES) {
  11693. if (accessedGlobals.has(variable)) {
  11694. usedHelpers.add(variable);
  11695. }
  11696. }
  11697. return HELPER_NAMES.map(variable => usedHelpers.has(variable)
  11698. ? HELPER_GENERATORS[variable](indent, snippets, liveBindings, freeze, namespaceToStringTag, usedHelpers)
  11699. : '').join('');
  11700. };
  11701. const HELPER_GENERATORS = {
  11702. [DOCUMENT_CURRENT_SCRIPT](_t, { _, n }) {
  11703. return `var${_}${DOCUMENT_CURRENT_SCRIPT}${_}=${_}typeof${_}document${_}!==${_}'undefined'${_}?${_}document.currentScript${_}:${_}null;${n}`;
  11704. },
  11705. [INTEROP_DEFAULT_COMPAT_VARIABLE](_t, snippets, liveBindings) {
  11706. const { _, getDirectReturnFunction, n } = snippets;
  11707. const [left, right] = getDirectReturnFunction(['e'], {
  11708. functionReturn: true,
  11709. lineBreakIndent: null,
  11710. name: INTEROP_DEFAULT_COMPAT_VARIABLE
  11711. });
  11712. return (`${left}${getIsCompatNamespace(snippets)}${_}?${_}` +
  11713. `${liveBindings ? getDefaultLiveBinding(snippets) : getDefaultStatic(snippets)}${right}${n}${n}`);
  11714. },
  11715. [INTEROP_DEFAULT_VARIABLE](_t, snippets, liveBindings) {
  11716. const { _, getDirectReturnFunction, n } = snippets;
  11717. const [left, right] = getDirectReturnFunction(['e'], {
  11718. functionReturn: true,
  11719. lineBreakIndent: null,
  11720. name: INTEROP_DEFAULT_VARIABLE
  11721. });
  11722. return (`${left}e${_}&&${_}e.__esModule${_}?${_}` +
  11723. `${liveBindings ? getDefaultLiveBinding(snippets) : getDefaultStatic(snippets)}${right}${n}${n}`);
  11724. },
  11725. [INTEROP_NAMESPACE_COMPAT_VARIABLE](t, snippets, liveBindings, freeze, namespaceToStringTag, usedHelpers) {
  11726. const { _, getDirectReturnFunction, n } = snippets;
  11727. if (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)) {
  11728. const [left, right] = getDirectReturnFunction(['e'], {
  11729. functionReturn: true,
  11730. lineBreakIndent: null,
  11731. name: INTEROP_NAMESPACE_COMPAT_VARIABLE
  11732. });
  11733. return `${left}${getIsCompatNamespace(snippets)}${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${right}${n}${n}`;
  11734. }
  11735. return (`function ${INTEROP_NAMESPACE_COMPAT_VARIABLE}(e)${_}{${n}` +
  11736. `${t}if${_}(${getIsCompatNamespace(snippets)})${_}return e;${n}` +
  11737. createNamespaceObject(t, t, snippets, liveBindings, freeze, namespaceToStringTag) +
  11738. `}${n}${n}`);
  11739. },
  11740. [INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE](_t, snippets, _liveBindings, freeze, namespaceToStringTag) {
  11741. const { getDirectReturnFunction, getObject, n } = snippets;
  11742. const [left, right] = getDirectReturnFunction(['e'], {
  11743. functionReturn: true,
  11744. lineBreakIndent: null,
  11745. name: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE
  11746. });
  11747. return `${left}${getFrozen(freeze, getWithToStringTag(namespaceToStringTag, getObject([
  11748. ['__proto__', 'null'],
  11749. ['default', 'e']
  11750. ], { lineBreakIndent: null }), snippets))}${right}${n}${n}`;
  11751. },
  11752. [INTEROP_NAMESPACE_DEFAULT_VARIABLE](t, snippets, liveBindings, freeze, namespaceToStringTag) {
  11753. const { _, n } = snippets;
  11754. return (`function ${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${_}{${n}` +
  11755. createNamespaceObject(t, t, snippets, liveBindings, freeze, namespaceToStringTag) +
  11756. `}${n}${n}`);
  11757. },
  11758. [INTEROP_NAMESPACE_VARIABLE](t, snippets, liveBindings, freeze, namespaceToStringTag, usedHelpers) {
  11759. const { _, getDirectReturnFunction, n } = snippets;
  11760. if (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)) {
  11761. const [left, right] = getDirectReturnFunction(['e'], {
  11762. functionReturn: true,
  11763. lineBreakIndent: null,
  11764. name: INTEROP_NAMESPACE_VARIABLE
  11765. });
  11766. return `${left}e${_}&&${_}e.__esModule${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${right}${n}${n}`;
  11767. }
  11768. return (`function ${INTEROP_NAMESPACE_VARIABLE}(e)${_}{${n}` +
  11769. `${t}if${_}(e${_}&&${_}e.__esModule)${_}return e;${n}` +
  11770. createNamespaceObject(t, t, snippets, liveBindings, freeze, namespaceToStringTag) +
  11771. `}${n}${n}`);
  11772. },
  11773. [MERGE_NAMESPACES_VARIABLE](t, snippets, liveBindings, freeze, namespaceToStringTag) {
  11774. const { _, cnst, n } = snippets;
  11775. const useForEach = cnst === 'var' && liveBindings;
  11776. return (`function ${MERGE_NAMESPACES_VARIABLE}(n, m)${_}{${n}` +
  11777. `${t}${loopOverNamespaces(`{${n}` +
  11778. `${t}${t}${t}if${_}(k${_}!==${_}'default'${_}&&${_}!(k in n))${_}{${n}` +
  11779. (liveBindings
  11780. ? useForEach
  11781. ? copyOwnPropertyLiveBinding
  11782. : copyPropertyLiveBinding
  11783. : copyPropertyStatic)(t, t + t + t + t, snippets) +
  11784. `${t}${t}${t}}${n}` +
  11785. `${t}${t}}`, useForEach, t, snippets)}${n}` +
  11786. `${t}return ${getFrozen(freeze, getWithToStringTag(namespaceToStringTag, 'n', snippets))};${n}` +
  11787. `}${n}${n}`);
  11788. }
  11789. };
  11790. const getDefaultLiveBinding = ({ _, getObject }) => `e${_}:${_}${getObject([['default', 'e']], { lineBreakIndent: null })}`;
  11791. const getDefaultStatic = ({ _, getPropertyAccess }) => `e${getPropertyAccess('default')}${_}:${_}e`;
  11792. const getIsCompatNamespace = ({ _ }) => `e${_}&&${_}typeof e${_}===${_}'object'${_}&&${_}'default'${_}in e`;
  11793. const createNamespaceObject = (t, index, snippets, liveBindings, freeze, namespaceToStringTag) => {
  11794. const { _, cnst, getObject, getPropertyAccess, n, s } = snippets;
  11795. const copyProperty = `{${n}` +
  11796. (liveBindings ? copyNonDefaultOwnPropertyLiveBinding : copyPropertyStatic)(t, index + t + t, snippets) +
  11797. `${index}${t}}`;
  11798. return (`${index}${cnst} n${_}=${_}Object.create(null${namespaceToStringTag
  11799. ? `,${_}{${_}[Symbol.toStringTag]:${_}${getToStringTagValue(getObject)}${_}}`
  11800. : ''});${n}` +
  11801. `${index}if${_}(e)${_}{${n}` +
  11802. `${index}${t}${loopOverKeys(copyProperty, !liveBindings, snippets)}${n}` +
  11803. `${index}}${n}` +
  11804. `${index}n${getPropertyAccess('default')}${_}=${_}e;${n}` +
  11805. `${index}return ${getFrozen(freeze, 'n')}${s}${n}`);
  11806. };
  11807. const loopOverKeys = (body, allowVariableLoopVariable, { _, cnst, getFunctionIntro, s }) => cnst !== 'var' || allowVariableLoopVariable
  11808. ? `for${_}(${cnst} k in e)${_}${body}`
  11809. : `Object.keys(e).forEach(${getFunctionIntro(['k'], {
  11810. isAsync: false,
  11811. name: null
  11812. })}${body})${s}`;
  11813. const loopOverNamespaces = (body, useForEach, t, { _, cnst, getDirectReturnFunction, getFunctionIntro, n }) => {
  11814. if (useForEach) {
  11815. const [left, right] = getDirectReturnFunction(['e'], {
  11816. functionReturn: false,
  11817. lineBreakIndent: { base: t, t },
  11818. name: null
  11819. });
  11820. return (`m.forEach(${left}` +
  11821. `e${_}&&${_}typeof e${_}!==${_}'string'${_}&&${_}!Array.isArray(e)${_}&&${_}Object.keys(e).forEach(${getFunctionIntro(['k'], {
  11822. isAsync: false,
  11823. name: null
  11824. })}${body})${right});`);
  11825. }
  11826. return (`for${_}(var i${_}=${_}0;${_}i${_}<${_}m.length;${_}i++)${_}{${n}` +
  11827. `${t}${t}${cnst} e${_}=${_}m[i];${n}` +
  11828. `${t}${t}if${_}(typeof e${_}!==${_}'string'${_}&&${_}!Array.isArray(e))${_}{${_}for${_}(${cnst} k in e)${_}${body}${_}}${n}${t}}`);
  11829. };
  11830. const copyNonDefaultOwnPropertyLiveBinding = (t, index, snippets) => {
  11831. const { _, n } = snippets;
  11832. return (`${index}if${_}(k${_}!==${_}'default')${_}{${n}` +
  11833. copyOwnPropertyLiveBinding(t, index + t, snippets) +
  11834. `${index}}${n}`);
  11835. };
  11836. const copyOwnPropertyLiveBinding = (t, index, { _, cnst, getDirectReturnFunction, n }) => {
  11837. const [left, right] = getDirectReturnFunction([], {
  11838. functionReturn: true,
  11839. lineBreakIndent: null,
  11840. name: null
  11841. });
  11842. return (`${index}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
  11843. `${index}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
  11844. `${index}${t}enumerable:${_}true,${n}` +
  11845. `${index}${t}get:${_}${left}e[k]${right}${n}` +
  11846. `${index}});${n}`);
  11847. };
  11848. const copyPropertyLiveBinding = (t, index, { _, cnst, getDirectReturnFunction, n }) => {
  11849. const [left, right] = getDirectReturnFunction([], {
  11850. functionReturn: true,
  11851. lineBreakIndent: null,
  11852. name: null
  11853. });
  11854. return (`${index}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
  11855. `${index}if${_}(d)${_}{${n}` +
  11856. `${index}${t}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
  11857. `${index}${t}${t}enumerable:${_}true,${n}` +
  11858. `${index}${t}${t}get:${_}${left}e[k]${right}${n}` +
  11859. `${index}${t}});${n}` +
  11860. `${index}}${n}`);
  11861. };
  11862. const copyPropertyStatic = (_t, index, { _, n }) => `${index}n[k]${_}=${_}e[k];${n}`;
  11863. const getFrozen = (freeze, fragment) => freeze ? `Object.freeze(${fragment})` : fragment;
  11864. const getWithToStringTag = (namespaceToStringTag, fragment, { _, getObject }) => namespaceToStringTag
  11865. ? `Object.defineProperty(${fragment},${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)})`
  11866. : fragment;
  11867. const HELPER_NAMES = Object.keys(HELPER_GENERATORS);
  11868. function getToStringTagValue(getObject) {
  11869. return getObject([['value', "'Module'"]], {
  11870. lineBreakIndent: null
  11871. });
  11872. }
  11873. function isReassignedExportsMember(variable, exportNamesByVariable) {
  11874. return (variable.renderBaseName !== null && exportNamesByVariable.has(variable) && variable.isReassigned);
  11875. }
  11876. class VariableDeclarator extends NodeBase {
  11877. declareDeclarator(kind) {
  11878. this.id.declare(kind, this.init || UNDEFINED_EXPRESSION);
  11879. }
  11880. deoptimizePath(path) {
  11881. this.id.deoptimizePath(path);
  11882. }
  11883. hasEffects(context) {
  11884. if (!this.deoptimized)
  11885. this.applyDeoptimizations();
  11886. const initEffect = this.init?.hasEffects(context);
  11887. this.id.markDeclarationReached();
  11888. return initEffect || this.id.hasEffects(context);
  11889. }
  11890. include(context, includeChildrenRecursively) {
  11891. const { deoptimized, id, init } = this;
  11892. if (!deoptimized)
  11893. this.applyDeoptimizations();
  11894. this.included = true;
  11895. init?.include(context, includeChildrenRecursively);
  11896. id.markDeclarationReached();
  11897. if (includeChildrenRecursively || id.shouldBeIncluded(context)) {
  11898. id.include(context, includeChildrenRecursively);
  11899. }
  11900. }
  11901. render(code, options) {
  11902. const { exportNamesByVariable, snippets: { _, getPropertyAccess } } = options;
  11903. const { end, id, init, start } = this;
  11904. const renderId = id.included;
  11905. if (renderId) {
  11906. id.render(code, options);
  11907. }
  11908. else {
  11909. const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', id.end);
  11910. code.remove(start, findNonWhiteSpace(code.original, operatorPos + 1));
  11911. }
  11912. if (init) {
  11913. if (id instanceof Identifier && init instanceof ClassExpression && !init.id) {
  11914. const renderedVariable = id.variable.getName(getPropertyAccess);
  11915. if (renderedVariable !== id.name) {
  11916. code.appendLeft(init.start + 5, ` ${id.name}`);
  11917. }
  11918. }
  11919. init.render(code, options, renderId ? BLANK : { renderedSurroundingElement: ExpressionStatement$1 });
  11920. }
  11921. else if (id instanceof Identifier &&
  11922. isReassignedExportsMember(id.variable, exportNamesByVariable)) {
  11923. code.appendLeft(end, `${_}=${_}void 0`);
  11924. }
  11925. }
  11926. applyDeoptimizations() {
  11927. this.deoptimized = true;
  11928. const { id, init } = this;
  11929. if (init && id instanceof Identifier && init instanceof ClassExpression && !init.id) {
  11930. const { name, variable } = id;
  11931. for (const accessedVariable of init.scope.accessedOutsideVariables.values()) {
  11932. if (accessedVariable !== variable) {
  11933. accessedVariable.forbidName(name);
  11934. }
  11935. }
  11936. }
  11937. }
  11938. }
  11939. // TODO once ImportExpression follows official ESTree specs with "null" as
  11940. // default, keys.ts should be updated
  11941. class ImportExpression extends NodeBase {
  11942. constructor() {
  11943. super(...arguments);
  11944. this.inlineNamespace = null;
  11945. this.assertions = null;
  11946. this.mechanism = null;
  11947. this.namespaceExportName = undefined;
  11948. this.resolution = null;
  11949. this.resolutionString = null;
  11950. }
  11951. // Do not bind assertions
  11952. bind() {
  11953. this.source.bind();
  11954. }
  11955. /**
  11956. * Get imported variables for deterministic usage, valid cases are:
  11957. *
  11958. * - `const { foo } = await import('bar')`.
  11959. * - `(await import('bar')).foo`
  11960. * - `import('bar').then(({ foo }) => {})`
  11961. *
  11962. * Returns empty array if it's side-effect only import.
  11963. * Returns undefined if it's not fully deterministic.
  11964. */
  11965. getDeterministicImportedNames() {
  11966. const parent1 = this.parent;
  11967. // Side-effect only: import('bar')
  11968. if (parent1 instanceof ExpressionStatement) {
  11969. return EMPTY_ARRAY;
  11970. }
  11971. if (parent1 instanceof AwaitExpression) {
  11972. const parent2 = parent1.parent;
  11973. // Side-effect only: await import('bar')
  11974. if (parent2 instanceof ExpressionStatement) {
  11975. return EMPTY_ARRAY;
  11976. }
  11977. // Case 1: const { foo } = await import('bar')
  11978. if (parent2 instanceof VariableDeclarator) {
  11979. const declaration = parent2.id;
  11980. return declaration instanceof ObjectPattern
  11981. ? getDeterministicObjectDestructure(declaration)
  11982. : undefined;
  11983. }
  11984. // Case 2: (await import('bar')).foo
  11985. if (parent2 instanceof MemberExpression) {
  11986. const id = parent2.property;
  11987. if (!parent2.computed && id instanceof Identifier) {
  11988. return [id.name];
  11989. }
  11990. }
  11991. return;
  11992. }
  11993. // Case 3: import('bar').then(({ foo }) => {})
  11994. if (parent1 instanceof MemberExpression) {
  11995. const callExpression = parent1.parent;
  11996. const property = parent1.property;
  11997. if (!(callExpression instanceof CallExpression) || !(property instanceof Identifier)) {
  11998. return;
  11999. }
  12000. const memberName = property.name;
  12001. // side-effect only, when only chaining .catch or .finally
  12002. if (callExpression.parent instanceof ExpressionStatement &&
  12003. ['catch', 'finally'].includes(memberName)) {
  12004. return EMPTY_ARRAY;
  12005. }
  12006. if (memberName !== 'then')
  12007. return;
  12008. // Side-effect only: import('bar').then()
  12009. if (callExpression.arguments.length === 0) {
  12010. return EMPTY_ARRAY;
  12011. }
  12012. const argument = callExpression.arguments[0];
  12013. if (callExpression.arguments.length !== 1 ||
  12014. !(argument instanceof ArrowFunctionExpression || argument instanceof FunctionExpression)) {
  12015. return;
  12016. }
  12017. // Side-effect only: import('bar').then(() => {})
  12018. if (argument.params.length === 0) {
  12019. return EMPTY_ARRAY;
  12020. }
  12021. const declaration = argument.params[0];
  12022. if (argument.params.length === 1 && declaration instanceof ObjectPattern) {
  12023. return getDeterministicObjectDestructure(declaration);
  12024. }
  12025. return;
  12026. }
  12027. }
  12028. hasEffects() {
  12029. return true;
  12030. }
  12031. include(context, includeChildrenRecursively) {
  12032. if (!this.included) {
  12033. this.included = true;
  12034. this.context.includeDynamicImport(this);
  12035. this.scope.addAccessedDynamicImport(this);
  12036. }
  12037. this.source.include(context, includeChildrenRecursively);
  12038. }
  12039. initialise() {
  12040. this.context.addDynamicImport(this);
  12041. }
  12042. parseNode(esTreeNode) {
  12043. // Keep the source AST to be used by renderDynamicImport
  12044. super.parseNode(esTreeNode, ['source']);
  12045. }
  12046. render(code, options) {
  12047. const { snippets: { _, getDirectReturnFunction, getObject, getPropertyAccess } } = options;
  12048. if (this.inlineNamespace) {
  12049. const [left, right] = getDirectReturnFunction([], {
  12050. functionReturn: true,
  12051. lineBreakIndent: null,
  12052. name: null
  12053. });
  12054. code.overwrite(this.start, this.end, `Promise.resolve().then(${left}${this.inlineNamespace.getName(getPropertyAccess)}${right})`);
  12055. return;
  12056. }
  12057. if (this.mechanism) {
  12058. code.overwrite(this.start, findFirstOccurrenceOutsideComment(code.original, '(', this.start + 6) + 1, this.mechanism.left);
  12059. code.overwrite(this.end - 1, this.end, this.mechanism.right);
  12060. }
  12061. if (this.resolutionString) {
  12062. code.overwrite(this.source.start, this.source.end, this.resolutionString);
  12063. if (this.namespaceExportName) {
  12064. const [left, right] = getDirectReturnFunction(['n'], {
  12065. functionReturn: true,
  12066. lineBreakIndent: null,
  12067. name: null
  12068. });
  12069. code.prependLeft(this.end, `.then(${left}n.${this.namespaceExportName}${right})`);
  12070. }
  12071. }
  12072. else {
  12073. this.source.render(code, options);
  12074. }
  12075. if (this.assertions !== true) {
  12076. if (this.arguments) {
  12077. code.overwrite(this.source.end, this.end - 1, '', { contentOnly: true });
  12078. }
  12079. if (this.assertions) {
  12080. code.appendLeft(this.end - 1, `,${_}${getObject([['assert', this.assertions]], {
  12081. lineBreakIndent: null
  12082. })}`);
  12083. }
  12084. }
  12085. }
  12086. setExternalResolution(exportMode, resolution, options, snippets, pluginDriver, accessedGlobalsByScope, resolutionString, namespaceExportName, assertions) {
  12087. const { format } = options;
  12088. this.inlineNamespace = null;
  12089. this.resolution = resolution;
  12090. this.resolutionString = resolutionString;
  12091. this.namespaceExportName = namespaceExportName;
  12092. this.assertions = assertions;
  12093. const accessedGlobals = [...(accessedImportGlobals[format] || [])];
  12094. let helper;
  12095. ({ helper, mechanism: this.mechanism } = this.getDynamicImportMechanismAndHelper(resolution, exportMode, options, snippets, pluginDriver));
  12096. if (helper) {
  12097. accessedGlobals.push(helper);
  12098. }
  12099. if (accessedGlobals.length > 0) {
  12100. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  12101. }
  12102. }
  12103. setInternalResolution(inlineNamespace) {
  12104. this.inlineNamespace = inlineNamespace;
  12105. }
  12106. applyDeoptimizations() { }
  12107. getDynamicImportMechanismAndHelper(resolution, exportMode, { compact, dynamicImportFunction, dynamicImportInCjs, format, generatedCode: { arrowFunctions }, interop }, { _, getDirectReturnFunction, getDirectReturnIifeLeft }, pluginDriver) {
  12108. const mechanism = pluginDriver.hookFirstSync('renderDynamicImport', [
  12109. {
  12110. customResolution: typeof this.resolution === 'string' ? this.resolution : null,
  12111. format,
  12112. moduleId: this.context.module.id,
  12113. targetModuleId: this.resolution && typeof this.resolution !== 'string' ? this.resolution.id : null
  12114. }
  12115. ]);
  12116. if (mechanism) {
  12117. return { helper: null, mechanism };
  12118. }
  12119. const hasDynamicTarget = !this.resolution || typeof this.resolution === 'string';
  12120. switch (format) {
  12121. case 'cjs': {
  12122. if (dynamicImportInCjs &&
  12123. (!resolution || typeof resolution === 'string' || resolution instanceof ExternalModule)) {
  12124. return { helper: null, mechanism: null };
  12125. }
  12126. const helper = getInteropHelper(resolution, exportMode, interop);
  12127. let left = `require(`;
  12128. let right = `)`;
  12129. if (helper) {
  12130. left = `/*#__PURE__*/${helper}(${left}`;
  12131. right += ')';
  12132. }
  12133. const [functionLeft, functionRight] = getDirectReturnFunction([], {
  12134. functionReturn: true,
  12135. lineBreakIndent: null,
  12136. name: null
  12137. });
  12138. left = `Promise.resolve().then(${functionLeft}${left}`;
  12139. right += `${functionRight})`;
  12140. if (!arrowFunctions && hasDynamicTarget) {
  12141. left = getDirectReturnIifeLeft(['t'], `${left}t${right}`, {
  12142. needsArrowReturnParens: false,
  12143. needsWrappedFunction: true
  12144. });
  12145. right = ')';
  12146. }
  12147. return {
  12148. helper,
  12149. mechanism: { left, right }
  12150. };
  12151. }
  12152. case 'amd': {
  12153. const resolve = compact ? 'c' : 'resolve';
  12154. const reject = compact ? 'e' : 'reject';
  12155. const helper = getInteropHelper(resolution, exportMode, interop);
  12156. const [resolveLeft, resolveRight] = getDirectReturnFunction(['m'], {
  12157. functionReturn: false,
  12158. lineBreakIndent: null,
  12159. name: null
  12160. });
  12161. const resolveNamespace = helper
  12162. ? `${resolveLeft}${resolve}(/*#__PURE__*/${helper}(m))${resolveRight}`
  12163. : resolve;
  12164. const [handlerLeft, handlerRight] = getDirectReturnFunction([resolve, reject], {
  12165. functionReturn: false,
  12166. lineBreakIndent: null,
  12167. name: null
  12168. });
  12169. let left = `new Promise(${handlerLeft}require([`;
  12170. let right = `],${_}${resolveNamespace},${_}${reject})${handlerRight})`;
  12171. if (!arrowFunctions && hasDynamicTarget) {
  12172. left = getDirectReturnIifeLeft(['t'], `${left}t${right}`, {
  12173. needsArrowReturnParens: false,
  12174. needsWrappedFunction: true
  12175. });
  12176. right = ')';
  12177. }
  12178. return {
  12179. helper,
  12180. mechanism: { left, right }
  12181. };
  12182. }
  12183. case 'system': {
  12184. return {
  12185. helper: null,
  12186. mechanism: {
  12187. left: 'module.import(',
  12188. right: ')'
  12189. }
  12190. };
  12191. }
  12192. case 'es': {
  12193. if (dynamicImportFunction) {
  12194. return {
  12195. helper: null,
  12196. mechanism: {
  12197. left: `${dynamicImportFunction}(`,
  12198. right: ')'
  12199. }
  12200. };
  12201. }
  12202. }
  12203. }
  12204. return { helper: null, mechanism: null };
  12205. }
  12206. }
  12207. function getInteropHelper(resolution, exportMode, interop) {
  12208. return exportMode === 'external'
  12209. ? namespaceInteropHelpersByInteropType[interop(resolution instanceof ExternalModule ? resolution.id : null)]
  12210. : exportMode === 'default'
  12211. ? INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE
  12212. : null;
  12213. }
  12214. const accessedImportGlobals = {
  12215. amd: ['require'],
  12216. cjs: ['require'],
  12217. system: ['module']
  12218. };
  12219. function getDeterministicObjectDestructure(objectPattern) {
  12220. const variables = [];
  12221. for (const property of objectPattern.properties) {
  12222. if (property.type === 'RestElement' || property.computed || property.key.type !== 'Identifier')
  12223. return;
  12224. variables.push(property.key.name);
  12225. }
  12226. return variables;
  12227. }
  12228. class ImportNamespaceSpecifier extends NodeBase {
  12229. applyDeoptimizations() { }
  12230. }
  12231. class ImportSpecifier extends NodeBase {
  12232. applyDeoptimizations() { }
  12233. }
  12234. class LabeledStatement extends NodeBase {
  12235. hasEffects(context) {
  12236. const brokenFlow = context.brokenFlow;
  12237. context.ignore.labels.add(this.label.name);
  12238. if (this.body.hasEffects(context))
  12239. return true;
  12240. context.ignore.labels.delete(this.label.name);
  12241. if (context.includedLabels.has(this.label.name)) {
  12242. context.includedLabels.delete(this.label.name);
  12243. context.brokenFlow = brokenFlow;
  12244. }
  12245. return false;
  12246. }
  12247. include(context, includeChildrenRecursively) {
  12248. this.included = true;
  12249. const brokenFlow = context.brokenFlow;
  12250. this.body.include(context, includeChildrenRecursively);
  12251. if (includeChildrenRecursively || context.includedLabels.has(this.label.name)) {
  12252. this.label.include();
  12253. context.includedLabels.delete(this.label.name);
  12254. context.brokenFlow = brokenFlow;
  12255. }
  12256. }
  12257. render(code, options) {
  12258. if (this.label.included) {
  12259. this.label.render(code, options);
  12260. }
  12261. else {
  12262. code.remove(this.start, findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, ':', this.label.end) + 1));
  12263. }
  12264. this.body.render(code, options);
  12265. }
  12266. }
  12267. class LogicalExpression extends NodeBase {
  12268. constructor() {
  12269. super(...arguments);
  12270. // We collect deoptimization information if usedBranch !== null
  12271. this.expressionsToBeDeoptimized = [];
  12272. this.isBranchResolutionAnalysed = false;
  12273. this.usedBranch = null;
  12274. }
  12275. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  12276. this.left.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  12277. this.right.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  12278. }
  12279. deoptimizeCache() {
  12280. if (this.usedBranch) {
  12281. const unusedBranch = this.usedBranch === this.left ? this.right : this.left;
  12282. this.usedBranch = null;
  12283. unusedBranch.deoptimizePath(UNKNOWN_PATH);
  12284. const { context, expressionsToBeDeoptimized } = this;
  12285. this.expressionsToBeDeoptimized = EMPTY_ARRAY;
  12286. for (const expression of expressionsToBeDeoptimized) {
  12287. expression.deoptimizeCache();
  12288. }
  12289. // Request another pass because we need to ensure "include" runs again if
  12290. // it is rendered
  12291. context.requestTreeshakingPass();
  12292. }
  12293. }
  12294. deoptimizePath(path) {
  12295. const usedBranch = this.getUsedBranch();
  12296. if (usedBranch) {
  12297. usedBranch.deoptimizePath(path);
  12298. }
  12299. else {
  12300. this.left.deoptimizePath(path);
  12301. this.right.deoptimizePath(path);
  12302. }
  12303. }
  12304. getLiteralValueAtPath(path, recursionTracker, origin) {
  12305. const usedBranch = this.getUsedBranch();
  12306. if (!usedBranch)
  12307. return UnknownValue;
  12308. this.expressionsToBeDeoptimized.push(origin);
  12309. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  12310. }
  12311. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  12312. const usedBranch = this.getUsedBranch();
  12313. if (!usedBranch)
  12314. return [
  12315. new MultiExpression([
  12316. this.left.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0],
  12317. this.right.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0]
  12318. ]),
  12319. false
  12320. ];
  12321. this.expressionsToBeDeoptimized.push(origin);
  12322. return usedBranch.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  12323. }
  12324. hasEffects(context) {
  12325. if (this.left.hasEffects(context)) {
  12326. return true;
  12327. }
  12328. if (this.getUsedBranch() !== this.left) {
  12329. return this.right.hasEffects(context);
  12330. }
  12331. return false;
  12332. }
  12333. hasEffectsOnInteractionAtPath(path, interaction, context) {
  12334. const usedBranch = this.getUsedBranch();
  12335. if (!usedBranch) {
  12336. return (this.left.hasEffectsOnInteractionAtPath(path, interaction, context) ||
  12337. this.right.hasEffectsOnInteractionAtPath(path, interaction, context));
  12338. }
  12339. return usedBranch.hasEffectsOnInteractionAtPath(path, interaction, context);
  12340. }
  12341. include(context, includeChildrenRecursively) {
  12342. this.included = true;
  12343. const usedBranch = this.getUsedBranch();
  12344. if (includeChildrenRecursively ||
  12345. (usedBranch === this.right && this.left.shouldBeIncluded(context)) ||
  12346. !usedBranch) {
  12347. this.left.include(context, includeChildrenRecursively);
  12348. this.right.include(context, includeChildrenRecursively);
  12349. }
  12350. else {
  12351. usedBranch.include(context, includeChildrenRecursively);
  12352. }
  12353. }
  12354. render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  12355. if (!this.left.included || !this.right.included) {
  12356. const operatorPos = findFirstOccurrenceOutsideComment(code.original, this.operator, this.left.end);
  12357. if (this.right.included) {
  12358. const removePos = findNonWhiteSpace(code.original, operatorPos + 2);
  12359. code.remove(this.start, removePos);
  12360. if (preventASI) {
  12361. removeLineBreaks(code, removePos, this.right.start);
  12362. }
  12363. }
  12364. else {
  12365. code.remove(operatorPos, this.end);
  12366. }
  12367. removeAnnotations(this, code);
  12368. this.getUsedBranch().render(code, options, {
  12369. isCalleeOfRenderedParent,
  12370. preventASI,
  12371. renderedParentType: renderedParentType || this.parent.type,
  12372. renderedSurroundingElement: renderedSurroundingElement || this.parent.type
  12373. });
  12374. }
  12375. else {
  12376. this.left.render(code, options, {
  12377. preventASI,
  12378. renderedSurroundingElement
  12379. });
  12380. this.right.render(code, options);
  12381. }
  12382. }
  12383. getUsedBranch() {
  12384. if (!this.isBranchResolutionAnalysed) {
  12385. this.isBranchResolutionAnalysed = true;
  12386. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  12387. if (typeof leftValue === 'symbol') {
  12388. return null;
  12389. }
  12390. else {
  12391. this.usedBranch =
  12392. (this.operator === '||' && leftValue) ||
  12393. (this.operator === '&&' && !leftValue) ||
  12394. (this.operator === '??' && leftValue != null)
  12395. ? this.left
  12396. : this.right;
  12397. }
  12398. }
  12399. return this.usedBranch;
  12400. }
  12401. }
  12402. const FILE_PREFIX = 'ROLLUP_FILE_URL_';
  12403. const IMPORT = 'import';
  12404. class MetaProperty extends NodeBase {
  12405. constructor() {
  12406. super(...arguments);
  12407. this.metaProperty = null;
  12408. this.preliminaryChunkId = null;
  12409. this.referenceId = null;
  12410. }
  12411. getReferencedFileName(outputPluginDriver) {
  12412. const { meta: { name }, metaProperty } = this;
  12413. if (name === IMPORT && metaProperty?.startsWith(FILE_PREFIX)) {
  12414. return outputPluginDriver.getFileName(metaProperty.slice(FILE_PREFIX.length));
  12415. }
  12416. return null;
  12417. }
  12418. hasEffects() {
  12419. return false;
  12420. }
  12421. hasEffectsOnInteractionAtPath(path, { type }) {
  12422. return path.length > 1 || type !== INTERACTION_ACCESSED;
  12423. }
  12424. include() {
  12425. if (!this.included) {
  12426. this.included = true;
  12427. if (this.meta.name === IMPORT) {
  12428. this.context.addImportMeta(this);
  12429. const parent = this.parent;
  12430. const metaProperty = (this.metaProperty =
  12431. parent instanceof MemberExpression && typeof parent.propertyKey === 'string'
  12432. ? parent.propertyKey
  12433. : null);
  12434. if (metaProperty?.startsWith(FILE_PREFIX)) {
  12435. this.referenceId = metaProperty.slice(FILE_PREFIX.length);
  12436. }
  12437. }
  12438. }
  12439. }
  12440. render(code, renderOptions) {
  12441. const { format, pluginDriver, snippets } = renderOptions;
  12442. const { context: { module }, meta: { name }, metaProperty, parent, preliminaryChunkId, referenceId, start, end } = this;
  12443. const { id: moduleId } = module;
  12444. if (name !== IMPORT)
  12445. return;
  12446. const chunkId = preliminaryChunkId;
  12447. if (referenceId) {
  12448. const fileName = pluginDriver.getFileName(referenceId);
  12449. const relativePath = normalize(node_path.relative(node_path.dirname(chunkId), fileName));
  12450. const replacement = pluginDriver.hookFirstSync('resolveFileUrl', [
  12451. { chunkId, fileName, format, moduleId, referenceId, relativePath }
  12452. ]) || relativeUrlMechanisms[format](relativePath);
  12453. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  12454. return;
  12455. }
  12456. let replacement = pluginDriver.hookFirstSync('resolveImportMeta', [
  12457. metaProperty,
  12458. { chunkId, format, moduleId }
  12459. ]);
  12460. if (!replacement) {
  12461. replacement = importMetaMechanisms[format]?.(metaProperty, { chunkId, snippets });
  12462. renderOptions.accessedDocumentCurrentScript || (renderOptions.accessedDocumentCurrentScript = formatsMaybeAccessDocumentCurrentScript.includes(format) && replacement !== 'undefined');
  12463. }
  12464. if (typeof replacement === 'string') {
  12465. if (parent instanceof MemberExpression) {
  12466. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  12467. }
  12468. else {
  12469. code.overwrite(start, end, replacement, { contentOnly: true });
  12470. }
  12471. }
  12472. }
  12473. setResolution(format, accessedGlobalsByScope, preliminaryChunkId) {
  12474. this.preliminaryChunkId = preliminaryChunkId;
  12475. const accessedGlobals = (this.metaProperty?.startsWith(FILE_PREFIX) ? accessedFileUrlGlobals : accessedMetaUrlGlobals)[format];
  12476. if (accessedGlobals.length > 0) {
  12477. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  12478. }
  12479. }
  12480. }
  12481. const formatsMaybeAccessDocumentCurrentScript = ['cjs', 'iife', 'umd'];
  12482. const accessedMetaUrlGlobals = {
  12483. amd: ['document', 'module', 'URL'],
  12484. cjs: ['document', 'require', 'URL', DOCUMENT_CURRENT_SCRIPT],
  12485. es: [],
  12486. iife: ['document', 'URL', DOCUMENT_CURRENT_SCRIPT],
  12487. system: ['module'],
  12488. umd: ['document', 'require', 'URL', DOCUMENT_CURRENT_SCRIPT]
  12489. };
  12490. const accessedFileUrlGlobals = {
  12491. amd: ['document', 'require', 'URL'],
  12492. cjs: ['document', 'require', 'URL'],
  12493. es: [],
  12494. iife: ['document', 'URL'],
  12495. system: ['module', 'URL'],
  12496. umd: ['document', 'require', 'URL']
  12497. };
  12498. const getResolveUrl = (path, URL = 'URL') => `new ${URL}(${path}).href`;
  12499. const getRelativeUrlFromDocument = (relativePath, umd = false) => getResolveUrl(`'${escapeId(relativePath)}', ${umd ? `typeof document === 'undefined' ? location.href : ` : ''}document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT' && document.currentScript.src || document.baseURI`);
  12500. const getGenericImportMetaMechanism = (getUrl) => (property, { chunkId }) => {
  12501. const urlMechanism = getUrl(chunkId);
  12502. return property === null
  12503. ? `({ url: ${urlMechanism} })`
  12504. : property === 'url'
  12505. ? urlMechanism
  12506. : 'undefined';
  12507. };
  12508. const getFileUrlFromFullPath = (path) => `require('u' + 'rl').pathToFileURL(${path}).href`;
  12509. const getFileUrlFromRelativePath = (path) => getFileUrlFromFullPath(`__dirname + '/${path}'`);
  12510. const getUrlFromDocument = (chunkId, umd = false) => `${umd ? `typeof document === 'undefined' ? location.href : ` : ''}(${DOCUMENT_CURRENT_SCRIPT} && ${DOCUMENT_CURRENT_SCRIPT}.tagName.toUpperCase() === 'SCRIPT' && ${DOCUMENT_CURRENT_SCRIPT}.src || new URL('${escapeId(chunkId)}', document.baseURI).href)`;
  12511. const relativeUrlMechanisms = {
  12512. amd: relativePath => {
  12513. if (relativePath[0] !== '.')
  12514. relativePath = './' + relativePath;
  12515. return getResolveUrl(`require.toUrl('${relativePath}'), document.baseURI`);
  12516. },
  12517. cjs: relativePath => `(typeof document === 'undefined' ? ${getFileUrlFromRelativePath(relativePath)} : ${getRelativeUrlFromDocument(relativePath)})`,
  12518. es: relativePath => getResolveUrl(`'${relativePath}', import.meta.url`),
  12519. iife: relativePath => getRelativeUrlFromDocument(relativePath),
  12520. system: relativePath => getResolveUrl(`'${relativePath}', module.meta.url`),
  12521. umd: relativePath => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getFileUrlFromRelativePath(relativePath)} : ${getRelativeUrlFromDocument(relativePath, true)})`
  12522. };
  12523. const importMetaMechanisms = {
  12524. amd: getGenericImportMetaMechanism(() => getResolveUrl(`module.uri, document.baseURI`)),
  12525. cjs: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' ? ${getFileUrlFromFullPath('__filename')} : ${getUrlFromDocument(chunkId)})`),
  12526. iife: getGenericImportMetaMechanism(chunkId => getUrlFromDocument(chunkId)),
  12527. system: (property, { snippets: { getPropertyAccess } }) => property === null ? `module.meta` : `module.meta${getPropertyAccess(property)}`,
  12528. umd: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getFileUrlFromFullPath('__filename')} : ${getUrlFromDocument(chunkId, true)})`)
  12529. };
  12530. class NewExpression extends NodeBase {
  12531. hasEffects(context) {
  12532. try {
  12533. for (const argument of this.arguments) {
  12534. if (argument.hasEffects(context))
  12535. return true;
  12536. }
  12537. if (this.annotationPure) {
  12538. return false;
  12539. }
  12540. return (this.callee.hasEffects(context) ||
  12541. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  12542. }
  12543. finally {
  12544. if (!this.deoptimized)
  12545. this.applyDeoptimizations();
  12546. }
  12547. }
  12548. hasEffectsOnInteractionAtPath(path, { type }) {
  12549. return path.length > 0 || type !== INTERACTION_ACCESSED;
  12550. }
  12551. include(context, includeChildrenRecursively) {
  12552. if (!this.deoptimized)
  12553. this.applyDeoptimizations();
  12554. if (includeChildrenRecursively) {
  12555. super.include(context, includeChildrenRecursively);
  12556. }
  12557. else {
  12558. this.included = true;
  12559. this.callee.include(context, false);
  12560. }
  12561. this.callee.includeCallArguments(context, this.arguments);
  12562. }
  12563. initialise() {
  12564. this.interaction = {
  12565. args: [null, ...this.arguments],
  12566. type: INTERACTION_CALLED,
  12567. withNew: true
  12568. };
  12569. }
  12570. render(code, options) {
  12571. this.callee.render(code, options);
  12572. renderCallArguments(code, options, this);
  12573. }
  12574. applyDeoptimizations() {
  12575. this.deoptimized = true;
  12576. this.callee.deoptimizeArgumentsOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  12577. this.context.requestTreeshakingPass();
  12578. }
  12579. }
  12580. class ObjectExpression extends NodeBase {
  12581. constructor() {
  12582. super(...arguments);
  12583. this.objectEntity = null;
  12584. }
  12585. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  12586. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  12587. }
  12588. deoptimizeCache() {
  12589. this.getObjectEntity().deoptimizeAllProperties();
  12590. }
  12591. deoptimizePath(path) {
  12592. this.getObjectEntity().deoptimizePath(path);
  12593. }
  12594. getLiteralValueAtPath(path, recursionTracker, origin) {
  12595. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  12596. }
  12597. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  12598. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  12599. }
  12600. hasEffectsOnInteractionAtPath(path, interaction, context) {
  12601. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  12602. }
  12603. render(code, options, { renderedSurroundingElement } = BLANK) {
  12604. super.render(code, options);
  12605. if (renderedSurroundingElement === ExpressionStatement$1 ||
  12606. renderedSurroundingElement === ArrowFunctionExpression$1) {
  12607. code.appendRight(this.start, '(');
  12608. code.prependLeft(this.end, ')');
  12609. }
  12610. }
  12611. applyDeoptimizations() { }
  12612. getObjectEntity() {
  12613. if (this.objectEntity !== null) {
  12614. return this.objectEntity;
  12615. }
  12616. let prototype = OBJECT_PROTOTYPE;
  12617. const properties = [];
  12618. for (const property of this.properties) {
  12619. if (property instanceof SpreadElement) {
  12620. properties.push({ key: UnknownKey, kind: 'init', property });
  12621. continue;
  12622. }
  12623. let key;
  12624. if (property.computed) {
  12625. const keyValue = property.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  12626. if (typeof keyValue === 'symbol') {
  12627. properties.push({ key: UnknownKey, kind: property.kind, property });
  12628. continue;
  12629. }
  12630. else {
  12631. key = String(keyValue);
  12632. }
  12633. }
  12634. else {
  12635. key =
  12636. property.key instanceof Identifier
  12637. ? property.key.name
  12638. : String(property.key.value);
  12639. if (key === '__proto__' && property.kind === 'init') {
  12640. prototype =
  12641. property.value instanceof Literal && property.value.value === null
  12642. ? null
  12643. : property.value;
  12644. continue;
  12645. }
  12646. }
  12647. properties.push({ key, kind: property.kind, property });
  12648. }
  12649. return (this.objectEntity = new ObjectEntity(properties, prototype));
  12650. }
  12651. }
  12652. class PrivateIdentifier extends NodeBase {
  12653. }
  12654. class Program extends NodeBase {
  12655. constructor() {
  12656. super(...arguments);
  12657. this.hasCachedEffect = null;
  12658. this.hasLoggedEffect = false;
  12659. }
  12660. hasCachedEffects() {
  12661. if (!this.included) {
  12662. return false;
  12663. }
  12664. return this.hasCachedEffect === null
  12665. ? (this.hasCachedEffect = this.hasEffects(createHasEffectsContext()))
  12666. : this.hasCachedEffect;
  12667. }
  12668. hasEffects(context) {
  12669. for (const node of this.body) {
  12670. if (node.hasEffects(context)) {
  12671. if (this.context.options.experimentalLogSideEffects && !this.hasLoggedEffect) {
  12672. this.hasLoggedEffect = true;
  12673. const { code, log, module } = this.context;
  12674. log(LOGLEVEL_INFO, logFirstSideEffect(code, module.id, locate(code, node.start, { offsetLine: 1 })), node.start);
  12675. }
  12676. return (this.hasCachedEffect = true);
  12677. }
  12678. }
  12679. return false;
  12680. }
  12681. include(context, includeChildrenRecursively) {
  12682. this.included = true;
  12683. for (const node of this.body) {
  12684. if (includeChildrenRecursively || node.shouldBeIncluded(context)) {
  12685. node.include(context, includeChildrenRecursively);
  12686. }
  12687. }
  12688. }
  12689. render(code, options) {
  12690. let start = this.start;
  12691. if (code.original.startsWith('#!')) {
  12692. start = Math.min(code.original.indexOf('\n') + 1, this.end);
  12693. code.remove(0, start);
  12694. }
  12695. if (this.body.length > 0) {
  12696. // Keep all consecutive lines that start with a comment
  12697. while (code.original[start] === '/' && /[*/]/.test(code.original[start + 1])) {
  12698. const firstLineBreak = findFirstLineBreakOutsideComment(code.original.slice(start, this.body[0].start));
  12699. if (firstLineBreak[0] === -1) {
  12700. break;
  12701. }
  12702. start += firstLineBreak[1];
  12703. }
  12704. renderStatementList(this.body, code, start, this.end, options);
  12705. }
  12706. else {
  12707. super.render(code, options);
  12708. }
  12709. }
  12710. applyDeoptimizations() { }
  12711. }
  12712. class Property extends MethodBase {
  12713. constructor() {
  12714. super(...arguments);
  12715. this.declarationInit = null;
  12716. }
  12717. declare(kind, init) {
  12718. this.declarationInit = init;
  12719. return this.value.declare(kind, UNKNOWN_EXPRESSION);
  12720. }
  12721. hasEffects(context) {
  12722. if (!this.deoptimized)
  12723. this.applyDeoptimizations();
  12724. const propertyReadSideEffects = this.context.options.treeshake
  12725. .propertyReadSideEffects;
  12726. return ((this.parent.type === 'ObjectPattern' && propertyReadSideEffects === 'always') ||
  12727. this.key.hasEffects(context) ||
  12728. this.value.hasEffects(context));
  12729. }
  12730. markDeclarationReached() {
  12731. this.value.markDeclarationReached();
  12732. }
  12733. render(code, options) {
  12734. if (!this.shorthand) {
  12735. this.key.render(code, options);
  12736. }
  12737. this.value.render(code, options, { isShorthandProperty: this.shorthand });
  12738. }
  12739. applyDeoptimizations() {
  12740. this.deoptimized = true;
  12741. if (this.declarationInit !== null) {
  12742. this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
  12743. this.context.requestTreeshakingPass();
  12744. }
  12745. }
  12746. }
  12747. class PropertyDefinition extends NodeBase {
  12748. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  12749. this.value?.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  12750. }
  12751. deoptimizePath(path) {
  12752. this.value?.deoptimizePath(path);
  12753. }
  12754. getLiteralValueAtPath(path, recursionTracker, origin) {
  12755. return this.value
  12756. ? this.value.getLiteralValueAtPath(path, recursionTracker, origin)
  12757. : UnknownValue;
  12758. }
  12759. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  12760. return this.value
  12761. ? this.value.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)
  12762. : UNKNOWN_RETURN_EXPRESSION;
  12763. }
  12764. hasEffects(context) {
  12765. return this.key.hasEffects(context) || (this.static && !!this.value?.hasEffects(context));
  12766. }
  12767. hasEffectsOnInteractionAtPath(path, interaction, context) {
  12768. return !this.value || this.value.hasEffectsOnInteractionAtPath(path, interaction, context);
  12769. }
  12770. applyDeoptimizations() { }
  12771. }
  12772. class ReturnStatement extends NodeBase {
  12773. hasEffects(context) {
  12774. if (!context.ignore.returnYield || this.argument?.hasEffects(context))
  12775. return true;
  12776. context.brokenFlow = true;
  12777. return false;
  12778. }
  12779. include(context, includeChildrenRecursively) {
  12780. this.included = true;
  12781. this.argument?.include(context, includeChildrenRecursively);
  12782. context.brokenFlow = true;
  12783. }
  12784. initialise() {
  12785. this.scope.addReturnExpression(this.argument || UNKNOWN_EXPRESSION);
  12786. }
  12787. render(code, options) {
  12788. if (this.argument) {
  12789. this.argument.render(code, options, { preventASI: true });
  12790. if (this.argument.start === this.start + 6 /* 'return'.length */) {
  12791. code.prependLeft(this.start + 6, ' ');
  12792. }
  12793. }
  12794. }
  12795. }
  12796. class SequenceExpression extends NodeBase {
  12797. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  12798. this.expressions[this.expressions.length - 1].deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  12799. }
  12800. deoptimizePath(path) {
  12801. this.expressions[this.expressions.length - 1].deoptimizePath(path);
  12802. }
  12803. getLiteralValueAtPath(path, recursionTracker, origin) {
  12804. return this.expressions[this.expressions.length - 1].getLiteralValueAtPath(path, recursionTracker, origin);
  12805. }
  12806. hasEffects(context) {
  12807. for (const expression of this.expressions) {
  12808. if (expression.hasEffects(context))
  12809. return true;
  12810. }
  12811. return false;
  12812. }
  12813. hasEffectsOnInteractionAtPath(path, interaction, context) {
  12814. return this.expressions[this.expressions.length - 1].hasEffectsOnInteractionAtPath(path, interaction, context);
  12815. }
  12816. include(context, includeChildrenRecursively) {
  12817. this.included = true;
  12818. const lastExpression = this.expressions[this.expressions.length - 1];
  12819. for (const expression of this.expressions) {
  12820. if (includeChildrenRecursively ||
  12821. (expression === lastExpression && !(this.parent instanceof ExpressionStatement)) ||
  12822. expression.shouldBeIncluded(context))
  12823. expression.include(context, includeChildrenRecursively);
  12824. }
  12825. }
  12826. render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
  12827. let includedNodes = 0;
  12828. let lastSeparatorPos = null;
  12829. const lastNode = this.expressions[this.expressions.length - 1];
  12830. for (const { node, separator, start, end } of getCommaSeparatedNodesWithBoundaries(this.expressions, code, this.start, this.end)) {
  12831. if (!node.included) {
  12832. treeshakeNode(node, code, start, end);
  12833. continue;
  12834. }
  12835. includedNodes++;
  12836. lastSeparatorPos = separator;
  12837. if (includedNodes === 1 && preventASI) {
  12838. removeLineBreaks(code, start, node.start);
  12839. }
  12840. if (includedNodes === 1) {
  12841. const parentType = renderedParentType || this.parent.type;
  12842. node.render(code, options, {
  12843. isCalleeOfRenderedParent: isCalleeOfRenderedParent && node === lastNode,
  12844. renderedParentType: parentType,
  12845. renderedSurroundingElement: parentType
  12846. });
  12847. }
  12848. else {
  12849. node.render(code, options);
  12850. }
  12851. }
  12852. if (lastSeparatorPos) {
  12853. code.remove(lastSeparatorPos, this.end);
  12854. }
  12855. }
  12856. }
  12857. class StaticBlock extends NodeBase {
  12858. createScope(parentScope) {
  12859. this.scope = new BlockScope(parentScope);
  12860. }
  12861. hasEffects(context) {
  12862. for (const node of this.body) {
  12863. if (node.hasEffects(context))
  12864. return true;
  12865. }
  12866. return false;
  12867. }
  12868. include(context, includeChildrenRecursively) {
  12869. this.included = true;
  12870. for (const node of this.body) {
  12871. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  12872. node.include(context, includeChildrenRecursively);
  12873. }
  12874. }
  12875. render(code, options) {
  12876. if (this.body.length > 0) {
  12877. const bodyStartPos = findFirstOccurrenceOutsideComment(code.original.slice(this.start, this.end), '{') + 1;
  12878. renderStatementList(this.body, code, this.start + bodyStartPos, this.end - 1, options);
  12879. }
  12880. else {
  12881. super.render(code, options);
  12882. }
  12883. }
  12884. }
  12885. class Super extends NodeBase {
  12886. bind() {
  12887. this.variable = this.scope.findVariable('this');
  12888. }
  12889. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  12890. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  12891. }
  12892. deoptimizePath(path) {
  12893. this.variable.deoptimizePath(path);
  12894. }
  12895. include() {
  12896. if (!this.included) {
  12897. this.included = true;
  12898. this.context.includeVariableInModule(this.variable);
  12899. }
  12900. }
  12901. }
  12902. class SwitchCase extends NodeBase {
  12903. hasEffects(context) {
  12904. if (this.test?.hasEffects(context))
  12905. return true;
  12906. for (const node of this.consequent) {
  12907. if (context.brokenFlow)
  12908. break;
  12909. if (node.hasEffects(context))
  12910. return true;
  12911. }
  12912. return false;
  12913. }
  12914. include(context, includeChildrenRecursively) {
  12915. this.included = true;
  12916. this.test?.include(context, includeChildrenRecursively);
  12917. for (const node of this.consequent) {
  12918. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  12919. node.include(context, includeChildrenRecursively);
  12920. }
  12921. }
  12922. render(code, options, nodeRenderOptions) {
  12923. if (this.consequent.length > 0) {
  12924. this.test && this.test.render(code, options);
  12925. const testEnd = this.test
  12926. ? this.test.end
  12927. : findFirstOccurrenceOutsideComment(code.original, 'default', this.start) + 7;
  12928. const consequentStart = findFirstOccurrenceOutsideComment(code.original, ':', testEnd) + 1;
  12929. renderStatementList(this.consequent, code, consequentStart, nodeRenderOptions.end, options);
  12930. }
  12931. else {
  12932. super.render(code, options);
  12933. }
  12934. }
  12935. }
  12936. SwitchCase.prototype.needsBoundaries = true;
  12937. class SwitchStatement extends NodeBase {
  12938. createScope(parentScope) {
  12939. this.parentScope = parentScope;
  12940. this.scope = new BlockScope(parentScope);
  12941. }
  12942. hasEffects(context) {
  12943. if (this.discriminant.hasEffects(context))
  12944. return true;
  12945. const { brokenFlow, hasBreak, ignore } = context;
  12946. const { breaks } = ignore;
  12947. ignore.breaks = true;
  12948. context.hasBreak = false;
  12949. let onlyHasBrokenFlow = true;
  12950. for (const switchCase of this.cases) {
  12951. if (switchCase.hasEffects(context))
  12952. return true;
  12953. // eslint-disable-next-line unicorn/consistent-destructuring
  12954. onlyHasBrokenFlow && (onlyHasBrokenFlow = context.brokenFlow && !context.hasBreak);
  12955. context.hasBreak = false;
  12956. context.brokenFlow = brokenFlow;
  12957. }
  12958. if (this.defaultCase !== null) {
  12959. context.brokenFlow = onlyHasBrokenFlow;
  12960. }
  12961. ignore.breaks = breaks;
  12962. context.hasBreak = hasBreak;
  12963. return false;
  12964. }
  12965. include(context, includeChildrenRecursively) {
  12966. this.included = true;
  12967. this.discriminant.include(context, includeChildrenRecursively);
  12968. const { brokenFlow, hasBreak } = context;
  12969. context.hasBreak = false;
  12970. let onlyHasBrokenFlow = true;
  12971. let isCaseIncluded = includeChildrenRecursively ||
  12972. (this.defaultCase !== null && this.defaultCase < this.cases.length - 1);
  12973. for (let caseIndex = this.cases.length - 1; caseIndex >= 0; caseIndex--) {
  12974. const switchCase = this.cases[caseIndex];
  12975. if (switchCase.included) {
  12976. isCaseIncluded = true;
  12977. }
  12978. if (!isCaseIncluded) {
  12979. const hasEffectsContext = createHasEffectsContext();
  12980. hasEffectsContext.ignore.breaks = true;
  12981. isCaseIncluded = switchCase.hasEffects(hasEffectsContext);
  12982. }
  12983. if (isCaseIncluded) {
  12984. switchCase.include(context, includeChildrenRecursively);
  12985. // eslint-disable-next-line unicorn/consistent-destructuring
  12986. onlyHasBrokenFlow && (onlyHasBrokenFlow = context.brokenFlow && !context.hasBreak);
  12987. context.hasBreak = false;
  12988. context.brokenFlow = brokenFlow;
  12989. }
  12990. else {
  12991. onlyHasBrokenFlow = brokenFlow;
  12992. }
  12993. }
  12994. if (isCaseIncluded && this.defaultCase !== null) {
  12995. context.brokenFlow = onlyHasBrokenFlow;
  12996. }
  12997. context.hasBreak = hasBreak;
  12998. }
  12999. initialise() {
  13000. for (let caseIndex = 0; caseIndex < this.cases.length; caseIndex++) {
  13001. if (this.cases[caseIndex].test === null) {
  13002. this.defaultCase = caseIndex;
  13003. return;
  13004. }
  13005. }
  13006. this.defaultCase = null;
  13007. }
  13008. parseNode(esTreeNode) {
  13009. this.discriminant = new (this.context.getNodeConstructor(esTreeNode.discriminant.type))(esTreeNode.discriminant, this, this.parentScope);
  13010. super.parseNode(esTreeNode);
  13011. }
  13012. render(code, options) {
  13013. this.discriminant.render(code, options);
  13014. if (this.cases.length > 0) {
  13015. renderStatementList(this.cases, code, this.cases[0].start, this.end - 1, options);
  13016. }
  13017. }
  13018. }
  13019. class TaggedTemplateExpression extends CallExpressionBase {
  13020. bind() {
  13021. super.bind();
  13022. if (this.tag.type === Identifier$1) {
  13023. const name = this.tag.name;
  13024. const variable = this.scope.findVariable(name);
  13025. if (variable.isNamespace) {
  13026. this.context.log(LOGLEVEL_WARN, logCannotCallNamespace(name), this.start);
  13027. }
  13028. }
  13029. }
  13030. hasEffects(context) {
  13031. try {
  13032. for (const argument of this.quasi.expressions) {
  13033. if (argument.hasEffects(context))
  13034. return true;
  13035. }
  13036. return (this.tag.hasEffects(context) ||
  13037. this.tag.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  13038. }
  13039. finally {
  13040. if (!this.deoptimized)
  13041. this.applyDeoptimizations();
  13042. }
  13043. }
  13044. include(context, includeChildrenRecursively) {
  13045. if (!this.deoptimized)
  13046. this.applyDeoptimizations();
  13047. if (includeChildrenRecursively) {
  13048. super.include(context, includeChildrenRecursively);
  13049. }
  13050. else {
  13051. this.included = true;
  13052. this.tag.include(context, includeChildrenRecursively);
  13053. this.quasi.include(context, includeChildrenRecursively);
  13054. }
  13055. this.tag.includeCallArguments(context, this.args);
  13056. const [returnExpression] = this.getReturnExpression();
  13057. if (!returnExpression.included) {
  13058. returnExpression.include(context, false);
  13059. }
  13060. }
  13061. initialise() {
  13062. this.args = [UNKNOWN_EXPRESSION, ...this.quasi.expressions];
  13063. this.interaction = {
  13064. args: [
  13065. this.tag instanceof MemberExpression && !this.tag.variable ? this.tag.object : null,
  13066. ...this.args
  13067. ],
  13068. type: INTERACTION_CALLED,
  13069. withNew: false
  13070. };
  13071. }
  13072. render(code, options) {
  13073. this.tag.render(code, options, { isCalleeOfRenderedParent: true });
  13074. this.quasi.render(code, options);
  13075. }
  13076. applyDeoptimizations() {
  13077. this.deoptimized = true;
  13078. this.tag.deoptimizeArgumentsOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  13079. this.context.requestTreeshakingPass();
  13080. }
  13081. getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) {
  13082. if (this.returnExpression === null) {
  13083. this.returnExpression = UNKNOWN_RETURN_EXPRESSION;
  13084. return (this.returnExpression = this.tag.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.interaction, recursionTracker, this));
  13085. }
  13086. return this.returnExpression;
  13087. }
  13088. }
  13089. class TemplateElement extends NodeBase {
  13090. // Do not try to bind value
  13091. bind() { }
  13092. hasEffects() {
  13093. return false;
  13094. }
  13095. include() {
  13096. this.included = true;
  13097. }
  13098. parseNode(esTreeNode) {
  13099. this.value = esTreeNode.value;
  13100. super.parseNode(esTreeNode);
  13101. }
  13102. render() { }
  13103. }
  13104. class TemplateLiteral extends NodeBase {
  13105. deoptimizeArgumentsOnInteractionAtPath() { }
  13106. getLiteralValueAtPath(path) {
  13107. if (path.length > 0 || this.quasis.length !== 1) {
  13108. return UnknownValue;
  13109. }
  13110. return this.quasis[0].value.cooked;
  13111. }
  13112. getReturnExpressionWhenCalledAtPath(path) {
  13113. if (path.length !== 1) {
  13114. return UNKNOWN_RETURN_EXPRESSION;
  13115. }
  13116. return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
  13117. }
  13118. hasEffectsOnInteractionAtPath(path, interaction, context) {
  13119. if (interaction.type === INTERACTION_ACCESSED) {
  13120. return path.length > 1;
  13121. }
  13122. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  13123. return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
  13124. }
  13125. return true;
  13126. }
  13127. render(code, options) {
  13128. code.indentExclusionRanges.push([this.start, this.end]);
  13129. super.render(code, options);
  13130. }
  13131. }
  13132. class UndefinedVariable extends Variable {
  13133. constructor() {
  13134. super('undefined');
  13135. }
  13136. getLiteralValueAtPath() {
  13137. return undefined;
  13138. }
  13139. }
  13140. class ExportDefaultVariable extends LocalVariable {
  13141. constructor(name, exportDefaultDeclaration, context) {
  13142. super(name, exportDefaultDeclaration, exportDefaultDeclaration.declaration, context);
  13143. this.hasId = false;
  13144. this.originalId = null;
  13145. this.originalVariable = null;
  13146. const declaration = exportDefaultDeclaration.declaration;
  13147. if ((declaration instanceof FunctionDeclaration || declaration instanceof ClassDeclaration) &&
  13148. declaration.id) {
  13149. this.hasId = true;
  13150. this.originalId = declaration.id;
  13151. }
  13152. else if (declaration instanceof Identifier) {
  13153. this.originalId = declaration;
  13154. }
  13155. }
  13156. addReference(identifier) {
  13157. if (!this.hasId) {
  13158. this.name = identifier.name;
  13159. }
  13160. }
  13161. forbidName(name) {
  13162. const original = this.getOriginalVariable();
  13163. if (original === this) {
  13164. super.forbidName(name);
  13165. }
  13166. else {
  13167. original.forbidName(name);
  13168. }
  13169. }
  13170. getAssignedVariableName() {
  13171. return (this.originalId && this.originalId.name) || null;
  13172. }
  13173. getBaseVariableName() {
  13174. const original = this.getOriginalVariable();
  13175. return original === this ? super.getBaseVariableName() : original.getBaseVariableName();
  13176. }
  13177. getDirectOriginalVariable() {
  13178. return this.originalId &&
  13179. (this.hasId ||
  13180. !(this.originalId.isPossibleTDZ() ||
  13181. this.originalId.variable.isReassigned ||
  13182. this.originalId.variable instanceof UndefinedVariable ||
  13183. // this avoids a circular dependency
  13184. 'syntheticNamespace' in this.originalId.variable))
  13185. ? this.originalId.variable
  13186. : null;
  13187. }
  13188. getName(getPropertyAccess) {
  13189. const original = this.getOriginalVariable();
  13190. return original === this
  13191. ? super.getName(getPropertyAccess)
  13192. : original.getName(getPropertyAccess);
  13193. }
  13194. getOriginalVariable() {
  13195. if (this.originalVariable)
  13196. return this.originalVariable;
  13197. // eslint-disable-next-line @typescript-eslint/no-this-alias
  13198. let original = this;
  13199. let currentVariable;
  13200. const checkedVariables = new Set();
  13201. do {
  13202. checkedVariables.add(original);
  13203. currentVariable = original;
  13204. original = currentVariable.getDirectOriginalVariable();
  13205. } while (original instanceof ExportDefaultVariable && !checkedVariables.has(original));
  13206. return (this.originalVariable = original || currentVariable);
  13207. }
  13208. }
  13209. class ModuleScope extends ChildScope {
  13210. constructor(parent, context) {
  13211. super(parent);
  13212. this.context = context;
  13213. this.variables.set('this', new LocalVariable('this', null, UNDEFINED_EXPRESSION, context));
  13214. }
  13215. addExportDefaultDeclaration(name, exportDefaultDeclaration, context) {
  13216. const variable = new ExportDefaultVariable(name, exportDefaultDeclaration, context);
  13217. this.variables.set('default', variable);
  13218. return variable;
  13219. }
  13220. addNamespaceMemberAccess() { }
  13221. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  13222. // all module level variables are already deconflicted when deconflicting the chunk
  13223. for (const scope of this.children)
  13224. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  13225. }
  13226. findLexicalBoundary() {
  13227. return this;
  13228. }
  13229. findVariable(name) {
  13230. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  13231. if (knownVariable) {
  13232. return knownVariable;
  13233. }
  13234. const variable = this.context.traceVariable(name) || this.parent.findVariable(name);
  13235. if (variable instanceof GlobalVariable) {
  13236. this.accessedOutsideVariables.set(name, variable);
  13237. }
  13238. return variable;
  13239. }
  13240. }
  13241. class ThisExpression extends NodeBase {
  13242. bind() {
  13243. this.variable = this.scope.findVariable('this');
  13244. }
  13245. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  13246. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  13247. }
  13248. deoptimizePath(path) {
  13249. this.variable.deoptimizePath(path);
  13250. }
  13251. hasEffectsOnInteractionAtPath(path, interaction, context) {
  13252. if (path.length === 0) {
  13253. return interaction.type !== INTERACTION_ACCESSED;
  13254. }
  13255. return this.variable.hasEffectsOnInteractionAtPath(path, interaction, context);
  13256. }
  13257. include() {
  13258. if (!this.included) {
  13259. this.included = true;
  13260. this.context.includeVariableInModule(this.variable);
  13261. }
  13262. }
  13263. initialise() {
  13264. this.alias =
  13265. this.scope.findLexicalBoundary() instanceof ModuleScope ? this.context.moduleContext : null;
  13266. if (this.alias === 'undefined') {
  13267. this.context.log(LOGLEVEL_WARN, logThisIsUndefined(), this.start);
  13268. }
  13269. }
  13270. render(code) {
  13271. if (this.alias !== null) {
  13272. code.overwrite(this.start, this.end, this.alias, {
  13273. contentOnly: false,
  13274. storeName: true
  13275. });
  13276. }
  13277. }
  13278. }
  13279. class ThrowStatement extends NodeBase {
  13280. hasEffects() {
  13281. return true;
  13282. }
  13283. include(context, includeChildrenRecursively) {
  13284. this.included = true;
  13285. this.argument.include(context, includeChildrenRecursively);
  13286. context.brokenFlow = true;
  13287. }
  13288. render(code, options) {
  13289. this.argument.render(code, options, { preventASI: true });
  13290. if (this.argument.start === this.start + 5 /* 'throw'.length */) {
  13291. code.prependLeft(this.start + 5, ' ');
  13292. }
  13293. }
  13294. }
  13295. class TryStatement extends NodeBase {
  13296. constructor() {
  13297. super(...arguments);
  13298. this.directlyIncluded = false;
  13299. this.includedLabelsAfterBlock = null;
  13300. }
  13301. hasEffects(context) {
  13302. return ((this.context.options.treeshake.tryCatchDeoptimization
  13303. ? this.block.body.length > 0
  13304. : this.block.hasEffects(context)) || !!this.finalizer?.hasEffects(context));
  13305. }
  13306. include(context, includeChildrenRecursively) {
  13307. const tryCatchDeoptimization = this.context.options.treeshake
  13308. ?.tryCatchDeoptimization;
  13309. const { brokenFlow, includedLabels } = context;
  13310. if (!this.directlyIncluded || !tryCatchDeoptimization) {
  13311. this.included = true;
  13312. this.directlyIncluded = true;
  13313. this.block.include(context, tryCatchDeoptimization ? INCLUDE_PARAMETERS : includeChildrenRecursively);
  13314. if (includedLabels.size > 0) {
  13315. this.includedLabelsAfterBlock = [...includedLabels];
  13316. }
  13317. context.brokenFlow = brokenFlow;
  13318. }
  13319. else if (this.includedLabelsAfterBlock) {
  13320. for (const label of this.includedLabelsAfterBlock) {
  13321. includedLabels.add(label);
  13322. }
  13323. }
  13324. if (this.handler !== null) {
  13325. this.handler.include(context, includeChildrenRecursively);
  13326. context.brokenFlow = brokenFlow;
  13327. }
  13328. this.finalizer?.include(context, includeChildrenRecursively);
  13329. }
  13330. }
  13331. const unaryOperators = {
  13332. '!': value => !value,
  13333. '+': value => +value,
  13334. '-': value => -value,
  13335. delete: () => UnknownValue,
  13336. typeof: value => typeof value,
  13337. void: () => undefined,
  13338. '~': value => ~value
  13339. };
  13340. class UnaryExpression extends NodeBase {
  13341. getLiteralValueAtPath(path, recursionTracker, origin) {
  13342. if (path.length > 0)
  13343. return UnknownValue;
  13344. const argumentValue = this.argument.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  13345. if (typeof argumentValue === 'symbol')
  13346. return UnknownValue;
  13347. return unaryOperators[this.operator](argumentValue);
  13348. }
  13349. hasEffects(context) {
  13350. if (!this.deoptimized)
  13351. this.applyDeoptimizations();
  13352. if (this.operator === 'typeof' && this.argument instanceof Identifier)
  13353. return false;
  13354. return (this.argument.hasEffects(context) ||
  13355. (this.operator === 'delete' &&
  13356. this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context)));
  13357. }
  13358. hasEffectsOnInteractionAtPath(path, { type }) {
  13359. return type !== INTERACTION_ACCESSED || path.length > (this.operator === 'void' ? 0 : 1);
  13360. }
  13361. applyDeoptimizations() {
  13362. this.deoptimized = true;
  13363. if (this.operator === 'delete') {
  13364. this.argument.deoptimizePath(EMPTY_PATH);
  13365. this.context.requestTreeshakingPass();
  13366. }
  13367. }
  13368. }
  13369. class UnknownNode extends NodeBase {
  13370. hasEffects() {
  13371. return true;
  13372. }
  13373. include(context) {
  13374. super.include(context, true);
  13375. }
  13376. }
  13377. class UpdateExpression extends NodeBase {
  13378. hasEffects(context) {
  13379. if (!this.deoptimized)
  13380. this.applyDeoptimizations();
  13381. return this.argument.hasEffectsAsAssignmentTarget(context, true);
  13382. }
  13383. hasEffectsOnInteractionAtPath(path, { type }) {
  13384. return path.length > 1 || type !== INTERACTION_ACCESSED;
  13385. }
  13386. include(context, includeChildrenRecursively) {
  13387. if (!this.deoptimized)
  13388. this.applyDeoptimizations();
  13389. this.included = true;
  13390. this.argument.includeAsAssignmentTarget(context, includeChildrenRecursively, true);
  13391. }
  13392. initialise() {
  13393. this.argument.setAssignedValue(UNKNOWN_EXPRESSION);
  13394. }
  13395. render(code, options) {
  13396. const { exportNamesByVariable, format, snippets: { _ } } = options;
  13397. this.argument.render(code, options);
  13398. if (format === 'system') {
  13399. const variable = this.argument.variable;
  13400. const exportNames = exportNamesByVariable.get(variable);
  13401. if (exportNames) {
  13402. if (this.prefix) {
  13403. if (exportNames.length === 1) {
  13404. renderSystemExportExpression(variable, this.start, this.end, code, options);
  13405. }
  13406. else {
  13407. renderSystemExportSequenceAfterExpression(variable, this.start, this.end, this.parent.type !== ExpressionStatement$1, code, options);
  13408. }
  13409. }
  13410. else {
  13411. const operator = this.operator[0];
  13412. renderSystemExportSequenceBeforeExpression(variable, this.start, this.end, this.parent.type !== ExpressionStatement$1, code, options, `${_}${operator}${_}1`);
  13413. }
  13414. }
  13415. }
  13416. }
  13417. applyDeoptimizations() {
  13418. this.deoptimized = true;
  13419. this.argument.deoptimizePath(EMPTY_PATH);
  13420. if (this.argument instanceof Identifier) {
  13421. const variable = this.scope.findVariable(this.argument.name);
  13422. variable.isReassigned = true;
  13423. }
  13424. this.context.requestTreeshakingPass();
  13425. }
  13426. }
  13427. function areAllDeclarationsIncludedAndNotExported(declarations, exportNamesByVariable) {
  13428. for (const declarator of declarations) {
  13429. if (!declarator.id.included)
  13430. return false;
  13431. if (declarator.id.type === Identifier$1) {
  13432. if (exportNamesByVariable.has(declarator.id.variable))
  13433. return false;
  13434. }
  13435. else {
  13436. const exportedVariables = [];
  13437. declarator.id.addExportedVariables(exportedVariables, exportNamesByVariable);
  13438. if (exportedVariables.length > 0)
  13439. return false;
  13440. }
  13441. }
  13442. return true;
  13443. }
  13444. class VariableDeclaration extends NodeBase {
  13445. deoptimizePath() {
  13446. for (const declarator of this.declarations) {
  13447. declarator.deoptimizePath(EMPTY_PATH);
  13448. }
  13449. }
  13450. hasEffectsOnInteractionAtPath() {
  13451. return false;
  13452. }
  13453. include(context, includeChildrenRecursively, { asSingleStatement } = BLANK) {
  13454. this.included = true;
  13455. for (const declarator of this.declarations) {
  13456. if (includeChildrenRecursively || declarator.shouldBeIncluded(context))
  13457. declarator.include(context, includeChildrenRecursively);
  13458. const { id, init } = declarator;
  13459. if (asSingleStatement) {
  13460. id.include(context, includeChildrenRecursively);
  13461. }
  13462. if (init &&
  13463. id.included &&
  13464. !init.included &&
  13465. (id instanceof ObjectPattern || id instanceof ArrayPattern)) {
  13466. init.include(context, includeChildrenRecursively);
  13467. }
  13468. }
  13469. }
  13470. initialise() {
  13471. for (const declarator of this.declarations) {
  13472. declarator.declareDeclarator(this.kind);
  13473. }
  13474. }
  13475. render(code, options, nodeRenderOptions = BLANK) {
  13476. if (areAllDeclarationsIncludedAndNotExported(this.declarations, options.exportNamesByVariable)) {
  13477. for (const declarator of this.declarations) {
  13478. declarator.render(code, options);
  13479. }
  13480. if (!nodeRenderOptions.isNoStatement &&
  13481. code.original.charCodeAt(this.end - 1) !== 59 /*";"*/) {
  13482. code.appendLeft(this.end, ';');
  13483. }
  13484. }
  13485. else {
  13486. this.renderReplacedDeclarations(code, options);
  13487. }
  13488. }
  13489. applyDeoptimizations() { }
  13490. renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, systemPatternExports, options) {
  13491. if (code.original.charCodeAt(this.end - 1) === 59 /*";"*/) {
  13492. code.remove(this.end - 1, this.end);
  13493. }
  13494. separatorString += ';';
  13495. if (lastSeparatorPos === null) {
  13496. code.appendLeft(renderedContentEnd, separatorString);
  13497. }
  13498. else {
  13499. if (code.original.charCodeAt(actualContentEnd - 1) === 10 /*"\n"*/ &&
  13500. (code.original.charCodeAt(this.end) === 10 /*"\n"*/ ||
  13501. code.original.charCodeAt(this.end) === 13) /*"\r"*/) {
  13502. actualContentEnd--;
  13503. if (code.original.charCodeAt(actualContentEnd) === 13 /*"\r"*/) {
  13504. actualContentEnd--;
  13505. }
  13506. }
  13507. if (actualContentEnd === lastSeparatorPos + 1) {
  13508. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString);
  13509. }
  13510. else {
  13511. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  13512. code.remove(actualContentEnd, renderedContentEnd);
  13513. }
  13514. }
  13515. if (systemPatternExports.length > 0) {
  13516. code.appendLeft(renderedContentEnd, ` ${getSystemExportStatement(systemPatternExports, options)};`);
  13517. }
  13518. }
  13519. renderReplacedDeclarations(code, options) {
  13520. const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.declarations, code, this.start + this.kind.length, this.end - (code.original.charCodeAt(this.end - 1) === 59 /*";"*/ ? 1 : 0));
  13521. let actualContentEnd, renderedContentEnd;
  13522. renderedContentEnd = findNonWhiteSpace(code.original, this.start + this.kind.length);
  13523. let lastSeparatorPos = renderedContentEnd - 1;
  13524. code.remove(this.start, lastSeparatorPos);
  13525. let isInDeclaration = false;
  13526. let hasRenderedContent = false;
  13527. let separatorString = '', leadingString, nextSeparatorString;
  13528. const aggregatedSystemExports = [];
  13529. const singleSystemExport = gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports);
  13530. for (const { node, start, separator, contentEnd, end } of separatedNodes) {
  13531. if (!node.included) {
  13532. code.remove(start, end);
  13533. continue;
  13534. }
  13535. node.render(code, options);
  13536. leadingString = '';
  13537. nextSeparatorString = '';
  13538. if (!node.id.included ||
  13539. (node.id instanceof Identifier &&
  13540. isReassignedExportsMember(node.id.variable, options.exportNamesByVariable))) {
  13541. if (hasRenderedContent) {
  13542. separatorString += ';';
  13543. }
  13544. isInDeclaration = false;
  13545. }
  13546. else {
  13547. if (singleSystemExport && singleSystemExport === node.id.variable) {
  13548. const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', node.id.end);
  13549. renderSystemExportExpression(singleSystemExport, findNonWhiteSpace(code.original, operatorPos + 1), separator === null ? contentEnd : separator, code, options);
  13550. }
  13551. if (isInDeclaration) {
  13552. separatorString += ',';
  13553. }
  13554. else {
  13555. if (hasRenderedContent) {
  13556. separatorString += ';';
  13557. }
  13558. leadingString += `${this.kind} `;
  13559. isInDeclaration = true;
  13560. }
  13561. }
  13562. if (renderedContentEnd === lastSeparatorPos + 1) {
  13563. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString + leadingString);
  13564. }
  13565. else {
  13566. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  13567. code.appendLeft(renderedContentEnd, leadingString);
  13568. }
  13569. actualContentEnd = contentEnd;
  13570. renderedContentEnd = end;
  13571. hasRenderedContent = true;
  13572. lastSeparatorPos = separator;
  13573. separatorString = nextSeparatorString;
  13574. }
  13575. this.renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, aggregatedSystemExports, options);
  13576. }
  13577. }
  13578. function gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports) {
  13579. let singleSystemExport = null;
  13580. if (options.format === 'system') {
  13581. for (const { node } of separatedNodes) {
  13582. if (node.id instanceof Identifier &&
  13583. node.init &&
  13584. aggregatedSystemExports.length === 0 &&
  13585. options.exportNamesByVariable.get(node.id.variable)?.length === 1) {
  13586. singleSystemExport = node.id.variable;
  13587. aggregatedSystemExports.push(singleSystemExport);
  13588. }
  13589. else {
  13590. node.id.addExportedVariables(aggregatedSystemExports, options.exportNamesByVariable);
  13591. }
  13592. }
  13593. if (aggregatedSystemExports.length > 1) {
  13594. singleSystemExport = null;
  13595. }
  13596. else if (singleSystemExport) {
  13597. aggregatedSystemExports.length = 0;
  13598. }
  13599. }
  13600. return singleSystemExport;
  13601. }
  13602. class WhileStatement extends NodeBase {
  13603. hasEffects(context) {
  13604. if (this.test.hasEffects(context))
  13605. return true;
  13606. return hasLoopBodyEffects(context, this.body);
  13607. }
  13608. include(context, includeChildrenRecursively) {
  13609. this.included = true;
  13610. this.test.include(context, includeChildrenRecursively);
  13611. includeLoopBody(context, this.body, includeChildrenRecursively);
  13612. }
  13613. }
  13614. class YieldExpression extends NodeBase {
  13615. hasEffects(context) {
  13616. if (!this.deoptimized)
  13617. this.applyDeoptimizations();
  13618. return !(context.ignore.returnYield && !this.argument?.hasEffects(context));
  13619. }
  13620. render(code, options) {
  13621. if (this.argument) {
  13622. this.argument.render(code, options, { preventASI: true });
  13623. if (this.argument.start === this.start + 5 /* 'yield'.length */) {
  13624. code.prependLeft(this.start + 5, ' ');
  13625. }
  13626. }
  13627. }
  13628. }
  13629. const nodeConstructors = {
  13630. ArrayExpression,
  13631. ArrayPattern,
  13632. ArrowFunctionExpression,
  13633. AssignmentExpression,
  13634. AssignmentPattern,
  13635. AwaitExpression,
  13636. BinaryExpression,
  13637. BlockStatement,
  13638. BreakStatement,
  13639. CallExpression,
  13640. CatchClause,
  13641. ChainExpression,
  13642. ClassBody,
  13643. ClassDeclaration,
  13644. ClassExpression,
  13645. ConditionalExpression,
  13646. ContinueStatement,
  13647. DoWhileStatement,
  13648. EmptyStatement,
  13649. ExportAllDeclaration,
  13650. ExportDefaultDeclaration,
  13651. ExportNamedDeclaration,
  13652. ExportSpecifier,
  13653. ExpressionStatement,
  13654. ForInStatement,
  13655. ForOfStatement,
  13656. ForStatement,
  13657. FunctionDeclaration,
  13658. FunctionExpression,
  13659. Identifier,
  13660. IfStatement,
  13661. ImportAttribute,
  13662. ImportDeclaration,
  13663. ImportDefaultSpecifier,
  13664. ImportExpression,
  13665. ImportNamespaceSpecifier,
  13666. ImportSpecifier,
  13667. LabeledStatement,
  13668. Literal,
  13669. LogicalExpression,
  13670. MemberExpression,
  13671. MetaProperty,
  13672. MethodDefinition,
  13673. NewExpression,
  13674. ObjectExpression,
  13675. ObjectPattern,
  13676. PrivateIdentifier,
  13677. Program,
  13678. Property,
  13679. PropertyDefinition,
  13680. RestElement,
  13681. ReturnStatement,
  13682. SequenceExpression,
  13683. SpreadElement,
  13684. StaticBlock,
  13685. Super,
  13686. SwitchCase,
  13687. SwitchStatement,
  13688. TaggedTemplateExpression,
  13689. TemplateElement,
  13690. TemplateLiteral,
  13691. ThisExpression,
  13692. ThrowStatement,
  13693. TryStatement,
  13694. UnaryExpression,
  13695. UnknownNode,
  13696. UpdateExpression,
  13697. VariableDeclaration,
  13698. VariableDeclarator,
  13699. WhileStatement,
  13700. YieldExpression
  13701. };
  13702. const MISSING_EXPORT_SHIM_VARIABLE = '_missingExportShim';
  13703. class ExportShimVariable extends Variable {
  13704. constructor(module) {
  13705. super(MISSING_EXPORT_SHIM_VARIABLE);
  13706. this.module = module;
  13707. }
  13708. include() {
  13709. super.include();
  13710. this.module.needsExportShim = true;
  13711. }
  13712. }
  13713. class NamespaceVariable extends Variable {
  13714. constructor(context) {
  13715. super(context.getModuleName());
  13716. this.memberVariables = null;
  13717. this.mergedNamespaces = [];
  13718. this.referencedEarly = false;
  13719. this.references = [];
  13720. this.context = context;
  13721. this.module = context.module;
  13722. }
  13723. addReference(identifier) {
  13724. this.references.push(identifier);
  13725. this.name = identifier.name;
  13726. }
  13727. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  13728. if (path.length > 1 || (path.length === 1 && interaction.type === INTERACTION_CALLED)) {
  13729. const key = path[0];
  13730. if (typeof key === 'string') {
  13731. this.getMemberVariables()[key]?.deoptimizeArgumentsOnInteractionAtPath(interaction, path.slice(1), recursionTracker);
  13732. }
  13733. else {
  13734. deoptimizeInteraction(interaction);
  13735. }
  13736. }
  13737. }
  13738. deoptimizePath(path) {
  13739. if (path.length > 1) {
  13740. const key = path[0];
  13741. if (typeof key === 'string') {
  13742. this.getMemberVariables()[key]?.deoptimizePath(path.slice(1));
  13743. }
  13744. }
  13745. }
  13746. getLiteralValueAtPath(path) {
  13747. if (path[0] === SymbolToStringTag) {
  13748. return 'Module';
  13749. }
  13750. return UnknownValue;
  13751. }
  13752. getMemberVariables() {
  13753. if (this.memberVariables) {
  13754. return this.memberVariables;
  13755. }
  13756. const memberVariables = Object.create(null);
  13757. const sortedExports = [...this.context.getExports(), ...this.context.getReexports()].sort();
  13758. for (const name of sortedExports) {
  13759. if (name[0] !== '*' && name !== this.module.info.syntheticNamedExports) {
  13760. const exportedVariable = this.context.traceExport(name);
  13761. if (exportedVariable) {
  13762. memberVariables[name] = exportedVariable;
  13763. }
  13764. }
  13765. }
  13766. return (this.memberVariables = memberVariables);
  13767. }
  13768. hasEffectsOnInteractionAtPath(path, interaction, context) {
  13769. const { type } = interaction;
  13770. if (path.length === 0) {
  13771. // This can only be a call anyway
  13772. return true;
  13773. }
  13774. if (path.length === 1 && type !== INTERACTION_CALLED) {
  13775. return type === INTERACTION_ASSIGNED;
  13776. }
  13777. const key = path[0];
  13778. if (typeof key !== 'string') {
  13779. return true;
  13780. }
  13781. const memberVariable = this.getMemberVariables()[key];
  13782. return (!memberVariable ||
  13783. memberVariable.hasEffectsOnInteractionAtPath(path.slice(1), interaction, context));
  13784. }
  13785. include() {
  13786. this.included = true;
  13787. this.context.includeAllExports();
  13788. }
  13789. prepare(accessedGlobalsByScope) {
  13790. if (this.mergedNamespaces.length > 0) {
  13791. this.module.scope.addAccessedGlobals([MERGE_NAMESPACES_VARIABLE], accessedGlobalsByScope);
  13792. }
  13793. }
  13794. renderBlock(options) {
  13795. const { exportNamesByVariable, format, freeze, indent: t, namespaceToStringTag, snippets: { _, cnst, getObject, getPropertyAccess, n, s } } = options;
  13796. const memberVariables = this.getMemberVariables();
  13797. const members = Object.entries(memberVariables)
  13798. .filter(([_, variable]) => variable.included)
  13799. .map(([name, variable]) => {
  13800. if (this.referencedEarly || variable.isReassigned || variable === this) {
  13801. return [
  13802. null,
  13803. `get ${name}${_}()${_}{${_}return ${variable.getName(getPropertyAccess)}${s}${_}}`
  13804. ];
  13805. }
  13806. return [name, variable.getName(getPropertyAccess)];
  13807. });
  13808. members.unshift([null, `__proto__:${_}null`]);
  13809. let output = getObject(members, { lineBreakIndent: { base: '', t } });
  13810. if (this.mergedNamespaces.length > 0) {
  13811. const assignmentArguments = this.mergedNamespaces.map(variable => variable.getName(getPropertyAccess));
  13812. output = `/*#__PURE__*/${MERGE_NAMESPACES_VARIABLE}(${output},${_}[${assignmentArguments.join(`,${_}`)}])`;
  13813. }
  13814. else {
  13815. // The helper to merge namespaces will also take care of freezing and toStringTag
  13816. if (namespaceToStringTag) {
  13817. output = `/*#__PURE__*/Object.defineProperty(${output},${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)})`;
  13818. }
  13819. if (freeze) {
  13820. output = `/*#__PURE__*/Object.freeze(${output})`;
  13821. }
  13822. }
  13823. const name = this.getName(getPropertyAccess);
  13824. output = `${cnst} ${name}${_}=${_}${output};`;
  13825. if (format === 'system' && exportNamesByVariable.has(this)) {
  13826. output += `${n}${getSystemExportStatement([this], options)};`;
  13827. }
  13828. return output;
  13829. }
  13830. renderFirst() {
  13831. return this.referencedEarly;
  13832. }
  13833. setMergedNamespaces(mergedNamespaces) {
  13834. this.mergedNamespaces = mergedNamespaces;
  13835. const moduleExecIndex = this.context.getModuleExecIndex();
  13836. for (const identifier of this.references) {
  13837. if (identifier.context.getModuleExecIndex() <= moduleExecIndex) {
  13838. this.referencedEarly = true;
  13839. break;
  13840. }
  13841. }
  13842. }
  13843. }
  13844. NamespaceVariable.prototype.isNamespace = true;
  13845. class SyntheticNamedExportVariable extends Variable {
  13846. constructor(context, name, syntheticNamespace) {
  13847. super(name);
  13848. this.baseVariable = null;
  13849. this.context = context;
  13850. this.module = context.module;
  13851. this.syntheticNamespace = syntheticNamespace;
  13852. }
  13853. getBaseVariable() {
  13854. if (this.baseVariable)
  13855. return this.baseVariable;
  13856. let baseVariable = this.syntheticNamespace;
  13857. while (baseVariable instanceof ExportDefaultVariable ||
  13858. baseVariable instanceof SyntheticNamedExportVariable) {
  13859. if (baseVariable instanceof ExportDefaultVariable) {
  13860. const original = baseVariable.getOriginalVariable();
  13861. if (original === baseVariable)
  13862. break;
  13863. baseVariable = original;
  13864. }
  13865. if (baseVariable instanceof SyntheticNamedExportVariable) {
  13866. baseVariable = baseVariable.syntheticNamespace;
  13867. }
  13868. }
  13869. return (this.baseVariable = baseVariable);
  13870. }
  13871. getBaseVariableName() {
  13872. return this.syntheticNamespace.getBaseVariableName();
  13873. }
  13874. getName(getPropertyAccess) {
  13875. return `${this.syntheticNamespace.getName(getPropertyAccess)}${getPropertyAccess(this.name)}`;
  13876. }
  13877. include() {
  13878. this.included = true;
  13879. this.context.includeVariableInModule(this.syntheticNamespace);
  13880. }
  13881. setRenderNames(baseName, name) {
  13882. super.setRenderNames(baseName, name);
  13883. }
  13884. }
  13885. const sourceMapCache = new WeakMap();
  13886. /**
  13887. * This clears the decoded array and falls back to the encoded string form.
  13888. * Sourcemap mappings arrays can be very large and holding on to them for longer
  13889. * than is necessary leads to poor heap utilization.
  13890. */
  13891. function resetCacheToEncoded(cache) {
  13892. if (cache.encodedMappings === undefined && cache.decodedMappings) {
  13893. cache.encodedMappings = encode(cache.decodedMappings);
  13894. }
  13895. cache.decodedMappings = undefined;
  13896. }
  13897. function resetSourcemapCache(map, sourcemapChain) {
  13898. if (map) {
  13899. const cache = sourceMapCache.get(map);
  13900. if (cache) {
  13901. resetCacheToEncoded(cache);
  13902. }
  13903. }
  13904. if (!sourcemapChain) {
  13905. return;
  13906. }
  13907. for (const map of sourcemapChain) {
  13908. if (map.missing)
  13909. continue;
  13910. resetSourcemapCache(map);
  13911. }
  13912. }
  13913. function decodedSourcemap(map) {
  13914. if (!map)
  13915. return null;
  13916. if (typeof map === 'string') {
  13917. map = JSON.parse(map);
  13918. }
  13919. if (!map.mappings) {
  13920. return {
  13921. mappings: [],
  13922. names: [],
  13923. sources: [],
  13924. version: 3
  13925. };
  13926. }
  13927. const originalMappings = map.mappings;
  13928. const isAlreadyDecoded = Array.isArray(originalMappings);
  13929. const cache = {
  13930. decodedMappings: isAlreadyDecoded ? originalMappings : undefined,
  13931. encodedMappings: isAlreadyDecoded ? undefined : originalMappings
  13932. };
  13933. const decodedMap = {
  13934. ...map,
  13935. // By moving mappings behind an accessor, we can avoid unneeded computation for cases
  13936. // where the mappings field is never actually accessed. This appears to greatly reduce
  13937. // the overhead of sourcemap decoding in terms of both compute time and memory usage.
  13938. get mappings() {
  13939. if (cache.decodedMappings) {
  13940. return cache.decodedMappings;
  13941. }
  13942. // If decodedMappings doesn't exist then encodedMappings should.
  13943. // The only scenario where cache.encodedMappings should be undefined is if the map
  13944. // this was constructed from was already decoded, or if mappings was set to a new
  13945. // decoded string. In either case, this line shouldn't get hit.
  13946. cache.decodedMappings = cache.encodedMappings ? decode(cache.encodedMappings) : [];
  13947. cache.encodedMappings = undefined;
  13948. return cache.decodedMappings;
  13949. }
  13950. };
  13951. sourceMapCache.set(decodedMap, cache);
  13952. return decodedMap;
  13953. }
  13954. function getId(m) {
  13955. return m.id;
  13956. }
  13957. function getOriginalLocation(sourcemapChain, location) {
  13958. const filteredSourcemapChain = sourcemapChain.filter((sourcemap) => !sourcemap.missing);
  13959. traceSourcemap: while (filteredSourcemapChain.length > 0) {
  13960. const sourcemap = filteredSourcemapChain.pop();
  13961. const line = sourcemap.mappings[location.line - 1];
  13962. if (line) {
  13963. const filteredLine = line.filter((segment) => segment.length > 1);
  13964. const lastSegment = filteredLine[filteredLine.length - 1];
  13965. for (const segment of filteredLine) {
  13966. if (segment[0] >= location.column || segment === lastSegment) {
  13967. location = {
  13968. column: segment[3],
  13969. line: segment[2] + 1
  13970. };
  13971. continue traceSourcemap;
  13972. }
  13973. }
  13974. }
  13975. throw new Error("Can't resolve original location of error.");
  13976. }
  13977. return location;
  13978. }
  13979. function getAssertionsFromImportExpression(node) {
  13980. const assertProperty = node.arguments?.[0]?.properties.find((property) => getPropertyKey(property) === 'assert')?.value;
  13981. if (!assertProperty) {
  13982. return EMPTY_OBJECT;
  13983. }
  13984. const assertFields = assertProperty.properties
  13985. .map(property => {
  13986. const key = getPropertyKey(property);
  13987. if (typeof key === 'string' &&
  13988. typeof property.value.value === 'string') {
  13989. return [key, property.value.value];
  13990. }
  13991. return null;
  13992. })
  13993. .filter((property) => !!property);
  13994. if (assertFields.length > 0) {
  13995. return Object.fromEntries(assertFields);
  13996. }
  13997. return EMPTY_OBJECT;
  13998. }
  13999. const getPropertyKey = (property) => {
  14000. const key = property.key;
  14001. return key && (key.name || key.value);
  14002. };
  14003. function getAssertionsFromImportExportDeclaration(assertions) {
  14004. return assertions?.length
  14005. ? Object.fromEntries(assertions.map(assertion => [getPropertyKey(assertion), assertion.value.value]))
  14006. : EMPTY_OBJECT;
  14007. }
  14008. function doAssertionsDiffer(assertionA, assertionB) {
  14009. const keysA = Object.keys(assertionA);
  14010. return (keysA.length !== Object.keys(assertionB).length ||
  14011. keysA.some(key => assertionA[key] !== assertionB[key]));
  14012. }
  14013. let timers = new Map();
  14014. function getPersistedLabel(label, level) {
  14015. switch (level) {
  14016. case 1: {
  14017. return `# ${label}`;
  14018. }
  14019. case 2: {
  14020. return `## ${label}`;
  14021. }
  14022. case 3: {
  14023. return label;
  14024. }
  14025. default: {
  14026. return `${' '.repeat(level - 4)}- ${label}`;
  14027. }
  14028. }
  14029. }
  14030. function timeStartImpl(label, level = 3) {
  14031. label = getPersistedLabel(label, level);
  14032. const startMemory = process$1.memoryUsage().heapUsed;
  14033. const startTime = node_perf_hooks.performance.now();
  14034. const timer = timers.get(label);
  14035. if (timer === undefined) {
  14036. timers.set(label, {
  14037. memory: 0,
  14038. startMemory,
  14039. startTime,
  14040. time: 0,
  14041. totalMemory: 0
  14042. });
  14043. }
  14044. else {
  14045. timer.startMemory = startMemory;
  14046. timer.startTime = startTime;
  14047. }
  14048. }
  14049. function timeEndImpl(label, level = 3) {
  14050. label = getPersistedLabel(label, level);
  14051. const timer = timers.get(label);
  14052. if (timer !== undefined) {
  14053. const currentMemory = process$1.memoryUsage().heapUsed;
  14054. timer.memory += currentMemory - timer.startMemory;
  14055. timer.time += node_perf_hooks.performance.now() - timer.startTime;
  14056. timer.totalMemory = Math.max(timer.totalMemory, currentMemory);
  14057. }
  14058. }
  14059. function getTimings() {
  14060. const newTimings = {};
  14061. for (const [label, { memory, time, totalMemory }] of timers) {
  14062. newTimings[label] = [time, memory, totalMemory];
  14063. }
  14064. return newTimings;
  14065. }
  14066. let timeStart = doNothing;
  14067. let timeEnd = doNothing;
  14068. const TIMED_PLUGIN_HOOKS = [
  14069. 'augmentChunkHash',
  14070. 'buildEnd',
  14071. 'buildStart',
  14072. 'generateBundle',
  14073. 'load',
  14074. 'moduleParsed',
  14075. 'options',
  14076. 'outputOptions',
  14077. 'renderChunk',
  14078. 'renderDynamicImport',
  14079. 'renderStart',
  14080. 'resolveDynamicImport',
  14081. 'resolveFileUrl',
  14082. 'resolveId',
  14083. 'resolveImportMeta',
  14084. 'shouldTransformCachedModule',
  14085. 'transform',
  14086. 'writeBundle'
  14087. ];
  14088. function getPluginWithTimers(plugin, index) {
  14089. if (plugin._hasTimer)
  14090. return plugin;
  14091. plugin._hasTimer = true;
  14092. for (const hook of TIMED_PLUGIN_HOOKS) {
  14093. if (hook in plugin) {
  14094. let timerLabel = `plugin ${index}`;
  14095. if (plugin.name) {
  14096. timerLabel += ` (${plugin.name})`;
  14097. }
  14098. timerLabel += ` - ${hook}`;
  14099. const handler = function (...parameters) {
  14100. timeStart(timerLabel, 4);
  14101. const result = hookFunction.apply(this, parameters);
  14102. timeEnd(timerLabel, 4);
  14103. return result;
  14104. };
  14105. let hookFunction;
  14106. if (typeof plugin[hook].handler === 'function') {
  14107. hookFunction = plugin[hook].handler;
  14108. plugin[hook].handler = handler;
  14109. }
  14110. else {
  14111. hookFunction = plugin[hook];
  14112. plugin[hook] = handler;
  14113. }
  14114. }
  14115. }
  14116. return plugin;
  14117. }
  14118. function initialiseTimers(inputOptions) {
  14119. if (inputOptions.perf) {
  14120. timers = new Map();
  14121. timeStart = timeStartImpl;
  14122. timeEnd = timeEndImpl;
  14123. inputOptions.plugins = inputOptions.plugins.map(getPluginWithTimers);
  14124. }
  14125. else {
  14126. timeStart = doNothing;
  14127. timeEnd = doNothing;
  14128. }
  14129. }
  14130. function markModuleAndImpureDependenciesAsExecuted(baseModule) {
  14131. baseModule.isExecuted = true;
  14132. const modules = [baseModule];
  14133. const visitedModules = new Set();
  14134. for (const module of modules) {
  14135. for (const dependency of [...module.dependencies, ...module.implicitlyLoadedBefore]) {
  14136. if (!(dependency instanceof ExternalModule) &&
  14137. !dependency.isExecuted &&
  14138. (dependency.info.moduleSideEffects || module.implicitlyLoadedBefore.has(dependency)) &&
  14139. !visitedModules.has(dependency.id)) {
  14140. dependency.isExecuted = true;
  14141. visitedModules.add(dependency.id);
  14142. modules.push(dependency);
  14143. }
  14144. }
  14145. }
  14146. }
  14147. const MISSING_EXPORT_SHIM_DESCRIPTION = {
  14148. identifier: null,
  14149. localName: MISSING_EXPORT_SHIM_VARIABLE
  14150. };
  14151. function getVariableForExportNameRecursive(target, name, importerForSideEffects, isExportAllSearch, searchedNamesAndModules = new Map()) {
  14152. const searchedModules = searchedNamesAndModules.get(name);
  14153. if (searchedModules) {
  14154. if (searchedModules.has(target)) {
  14155. return isExportAllSearch ? [null] : error(logCircularReexport(name, target.id));
  14156. }
  14157. searchedModules.add(target);
  14158. }
  14159. else {
  14160. searchedNamesAndModules.set(name, new Set([target]));
  14161. }
  14162. return target.getVariableForExportName(name, {
  14163. importerForSideEffects,
  14164. isExportAllSearch,
  14165. searchedNamesAndModules
  14166. });
  14167. }
  14168. function getAndExtendSideEffectModules(variable, module) {
  14169. const sideEffectModules = getOrCreate(module.sideEffectDependenciesByVariable, variable, (getNewSet));
  14170. let currentVariable = variable;
  14171. const referencedVariables = new Set([currentVariable]);
  14172. while (true) {
  14173. const importingModule = currentVariable.module;
  14174. currentVariable =
  14175. currentVariable instanceof ExportDefaultVariable
  14176. ? currentVariable.getDirectOriginalVariable()
  14177. : currentVariable instanceof SyntheticNamedExportVariable
  14178. ? currentVariable.syntheticNamespace
  14179. : null;
  14180. if (!currentVariable || referencedVariables.has(currentVariable)) {
  14181. break;
  14182. }
  14183. referencedVariables.add(currentVariable);
  14184. sideEffectModules.add(importingModule);
  14185. const originalSideEffects = importingModule.sideEffectDependenciesByVariable.get(currentVariable);
  14186. if (originalSideEffects) {
  14187. for (const module of originalSideEffects) {
  14188. sideEffectModules.add(module);
  14189. }
  14190. }
  14191. }
  14192. return sideEffectModules;
  14193. }
  14194. class Module {
  14195. constructor(graph, id, options, isEntry, moduleSideEffects, syntheticNamedExports, meta, assertions) {
  14196. this.graph = graph;
  14197. this.id = id;
  14198. this.options = options;
  14199. this.alternativeReexportModules = new Map();
  14200. this.chunkFileNames = new Set();
  14201. this.chunkNames = [];
  14202. this.cycles = new Set();
  14203. this.dependencies = new Set();
  14204. this.dynamicDependencies = new Set();
  14205. this.dynamicImporters = [];
  14206. this.dynamicImports = [];
  14207. this.execIndex = Infinity;
  14208. this.implicitlyLoadedAfter = new Set();
  14209. this.implicitlyLoadedBefore = new Set();
  14210. this.importDescriptions = new Map();
  14211. this.importMetas = [];
  14212. this.importedFromNotTreeshaken = false;
  14213. this.importers = [];
  14214. this.includedDynamicImporters = [];
  14215. this.includedImports = new Set();
  14216. this.isExecuted = false;
  14217. this.isUserDefinedEntryPoint = false;
  14218. this.needsExportShim = false;
  14219. this.sideEffectDependenciesByVariable = new Map();
  14220. this.sourcesWithAssertions = new Map();
  14221. this.allExportNames = null;
  14222. this.ast = null;
  14223. this.exportAllModules = [];
  14224. this.exportAllSources = new Set();
  14225. this.exportNamesByVariable = null;
  14226. this.exportShimVariable = new ExportShimVariable(this);
  14227. this.exports = new Map();
  14228. this.namespaceReexportsByName = new Map();
  14229. this.reexportDescriptions = new Map();
  14230. this.relevantDependencies = null;
  14231. this.syntheticExports = new Map();
  14232. this.syntheticNamespace = null;
  14233. this.transformDependencies = [];
  14234. this.transitiveReexports = null;
  14235. this.excludeFromSourcemap = /\0/.test(id);
  14236. this.context = options.moduleContext(id);
  14237. this.preserveSignature = this.options.preserveEntrySignatures;
  14238. // eslint-disable-next-line @typescript-eslint/no-this-alias
  14239. const module = this;
  14240. const { dynamicImports, dynamicImporters, exportAllSources, exports, implicitlyLoadedAfter, implicitlyLoadedBefore, importers, reexportDescriptions, sourcesWithAssertions } = this;
  14241. this.info = {
  14242. assertions,
  14243. ast: null,
  14244. code: null,
  14245. get dynamicallyImportedIdResolutions() {
  14246. return dynamicImports
  14247. .map(({ argument }) => typeof argument === 'string' && module.resolvedIds[argument])
  14248. .filter(Boolean);
  14249. },
  14250. get dynamicallyImportedIds() {
  14251. // We cannot use this.dynamicDependencies because this is needed before
  14252. // dynamicDependencies are populated
  14253. return dynamicImports.map(({ id }) => id).filter((id) => id != null);
  14254. },
  14255. get dynamicImporters() {
  14256. return dynamicImporters.sort();
  14257. },
  14258. get exportedBindings() {
  14259. const exportBindings = { '.': [...exports.keys()] };
  14260. for (const [name, { source }] of reexportDescriptions) {
  14261. (exportBindings[source] ?? (exportBindings[source] = [])).push(name);
  14262. }
  14263. for (const source of exportAllSources) {
  14264. (exportBindings[source] ?? (exportBindings[source] = [])).push('*');
  14265. }
  14266. return exportBindings;
  14267. },
  14268. get exports() {
  14269. return [
  14270. ...exports.keys(),
  14271. ...reexportDescriptions.keys(),
  14272. ...[...exportAllSources].map(() => '*')
  14273. ];
  14274. },
  14275. get hasDefaultExport() {
  14276. // This information is only valid after parsing
  14277. if (!module.ast) {
  14278. return null;
  14279. }
  14280. return module.exports.has('default') || reexportDescriptions.has('default');
  14281. },
  14282. get hasModuleSideEffects() {
  14283. warnDeprecation('Accessing ModuleInfo.hasModuleSideEffects from plugins is deprecated. Please use ModuleInfo.moduleSideEffects instead.', URL_THIS_GETMODULEINFO, true, options);
  14284. return this.moduleSideEffects;
  14285. },
  14286. id,
  14287. get implicitlyLoadedAfterOneOf() {
  14288. // eslint-disable-next-line unicorn/prefer-spread
  14289. return Array.from(implicitlyLoadedAfter, getId).sort();
  14290. },
  14291. get implicitlyLoadedBefore() {
  14292. // eslint-disable-next-line unicorn/prefer-spread
  14293. return Array.from(implicitlyLoadedBefore, getId).sort();
  14294. },
  14295. get importedIdResolutions() {
  14296. // eslint-disable-next-line unicorn/prefer-spread
  14297. return Array.from(sourcesWithAssertions.keys(), source => module.resolvedIds[source]).filter(Boolean);
  14298. },
  14299. get importedIds() {
  14300. // We cannot use this.dependencies because this is needed before
  14301. // dependencies are populated
  14302. // eslint-disable-next-line unicorn/prefer-spread
  14303. return Array.from(sourcesWithAssertions.keys(), source => module.resolvedIds[source]?.id).filter(Boolean);
  14304. },
  14305. get importers() {
  14306. return importers.sort();
  14307. },
  14308. isEntry,
  14309. isExternal: false,
  14310. get isIncluded() {
  14311. if (graph.phase !== BuildPhase.GENERATE) {
  14312. return null;
  14313. }
  14314. return module.isIncluded();
  14315. },
  14316. meta: { ...meta },
  14317. moduleSideEffects,
  14318. syntheticNamedExports
  14319. };
  14320. // Hide the deprecated key so that it only warns when accessed explicitly
  14321. // eslint-disable-next-line unicorn/consistent-destructuring
  14322. Object.defineProperty(this.info, 'hasModuleSideEffects', {
  14323. enumerable: false
  14324. });
  14325. }
  14326. basename() {
  14327. const base = node_path.basename(this.id);
  14328. const extension = node_path.extname(this.id);
  14329. return makeLegal(extension ? base.slice(0, -extension.length) : base);
  14330. }
  14331. bindReferences() {
  14332. this.ast.bind();
  14333. }
  14334. error(properties, pos) {
  14335. this.addLocationToLogProps(properties, pos);
  14336. return error(properties);
  14337. }
  14338. // sum up the length of all ast nodes that are included
  14339. estimateSize() {
  14340. let size = 0;
  14341. for (const node of this.ast.body) {
  14342. if (node.included) {
  14343. size += node.end - node.start;
  14344. }
  14345. }
  14346. return size;
  14347. }
  14348. getAllExportNames() {
  14349. if (this.allExportNames) {
  14350. return this.allExportNames;
  14351. }
  14352. this.allExportNames = new Set([...this.exports.keys(), ...this.reexportDescriptions.keys()]);
  14353. for (const module of this.exportAllModules) {
  14354. if (module instanceof ExternalModule) {
  14355. this.allExportNames.add(`*${module.id}`);
  14356. continue;
  14357. }
  14358. for (const name of module.getAllExportNames()) {
  14359. if (name !== 'default')
  14360. this.allExportNames.add(name);
  14361. }
  14362. }
  14363. // We do not count the synthetic namespace as a regular export to hide it
  14364. // from entry signatures and namespace objects
  14365. if (typeof this.info.syntheticNamedExports === 'string') {
  14366. this.allExportNames.delete(this.info.syntheticNamedExports);
  14367. }
  14368. return this.allExportNames;
  14369. }
  14370. getDependenciesToBeIncluded() {
  14371. if (this.relevantDependencies)
  14372. return this.relevantDependencies;
  14373. this.relevantDependencies = new Set();
  14374. const necessaryDependencies = new Set();
  14375. const alwaysCheckedDependencies = new Set();
  14376. const dependencyVariables = new Set(this.includedImports);
  14377. if (this.info.isEntry ||
  14378. this.includedDynamicImporters.length > 0 ||
  14379. this.namespace.included ||
  14380. this.implicitlyLoadedAfter.size > 0) {
  14381. for (const exportName of [...this.getReexports(), ...this.getExports()]) {
  14382. const [exportedVariable] = this.getVariableForExportName(exportName);
  14383. if (exportedVariable?.included) {
  14384. dependencyVariables.add(exportedVariable);
  14385. }
  14386. }
  14387. }
  14388. for (let variable of dependencyVariables) {
  14389. const sideEffectDependencies = this.sideEffectDependenciesByVariable.get(variable);
  14390. if (sideEffectDependencies) {
  14391. for (const module of sideEffectDependencies) {
  14392. alwaysCheckedDependencies.add(module);
  14393. }
  14394. }
  14395. if (variable instanceof SyntheticNamedExportVariable) {
  14396. variable = variable.getBaseVariable();
  14397. }
  14398. else if (variable instanceof ExportDefaultVariable) {
  14399. variable = variable.getOriginalVariable();
  14400. }
  14401. necessaryDependencies.add(variable.module);
  14402. }
  14403. if (!this.options.treeshake || this.info.moduleSideEffects === 'no-treeshake') {
  14404. for (const dependency of this.dependencies) {
  14405. this.relevantDependencies.add(dependency);
  14406. }
  14407. }
  14408. else {
  14409. this.addRelevantSideEffectDependencies(this.relevantDependencies, necessaryDependencies, alwaysCheckedDependencies);
  14410. }
  14411. for (const dependency of necessaryDependencies) {
  14412. this.relevantDependencies.add(dependency);
  14413. }
  14414. return this.relevantDependencies;
  14415. }
  14416. getExportNamesByVariable() {
  14417. if (this.exportNamesByVariable) {
  14418. return this.exportNamesByVariable;
  14419. }
  14420. const exportNamesByVariable = new Map();
  14421. for (const exportName of this.getAllExportNames()) {
  14422. let [tracedVariable] = this.getVariableForExportName(exportName);
  14423. if (tracedVariable instanceof ExportDefaultVariable) {
  14424. tracedVariable = tracedVariable.getOriginalVariable();
  14425. }
  14426. if (!tracedVariable ||
  14427. !(tracedVariable.included || tracedVariable instanceof ExternalVariable)) {
  14428. continue;
  14429. }
  14430. const existingExportNames = exportNamesByVariable.get(tracedVariable);
  14431. if (existingExportNames) {
  14432. existingExportNames.push(exportName);
  14433. }
  14434. else {
  14435. exportNamesByVariable.set(tracedVariable, [exportName]);
  14436. }
  14437. }
  14438. return (this.exportNamesByVariable = exportNamesByVariable);
  14439. }
  14440. getExports() {
  14441. return [...this.exports.keys()];
  14442. }
  14443. getReexports() {
  14444. if (this.transitiveReexports) {
  14445. return this.transitiveReexports;
  14446. }
  14447. // to avoid infinite recursion when using circular `export * from X`
  14448. this.transitiveReexports = [];
  14449. const reexports = new Set(this.reexportDescriptions.keys());
  14450. for (const module of this.exportAllModules) {
  14451. if (module instanceof ExternalModule) {
  14452. reexports.add(`*${module.id}`);
  14453. }
  14454. else {
  14455. for (const name of [...module.getReexports(), ...module.getExports()]) {
  14456. if (name !== 'default')
  14457. reexports.add(name);
  14458. }
  14459. }
  14460. }
  14461. return (this.transitiveReexports = [...reexports]);
  14462. }
  14463. getRenderedExports() {
  14464. // only direct exports are counted here, not reexports at all
  14465. const renderedExports = [];
  14466. const removedExports = [];
  14467. for (const exportName of this.exports.keys()) {
  14468. const [variable] = this.getVariableForExportName(exportName);
  14469. (variable && variable.included ? renderedExports : removedExports).push(exportName);
  14470. }
  14471. return { removedExports, renderedExports };
  14472. }
  14473. getSyntheticNamespace() {
  14474. if (this.syntheticNamespace === null) {
  14475. this.syntheticNamespace = undefined;
  14476. [this.syntheticNamespace] = this.getVariableForExportName(typeof this.info.syntheticNamedExports === 'string'
  14477. ? this.info.syntheticNamedExports
  14478. : 'default', { onlyExplicit: true });
  14479. }
  14480. if (!this.syntheticNamespace) {
  14481. return error(logSyntheticNamedExportsNeedNamespaceExport(this.id, this.info.syntheticNamedExports));
  14482. }
  14483. return this.syntheticNamespace;
  14484. }
  14485. getVariableForExportName(name, { importerForSideEffects, isExportAllSearch, onlyExplicit, searchedNamesAndModules } = EMPTY_OBJECT) {
  14486. if (name[0] === '*') {
  14487. if (name.length === 1) {
  14488. // export * from './other'
  14489. return [this.namespace];
  14490. }
  14491. // export * from 'external'
  14492. const module = this.graph.modulesById.get(name.slice(1));
  14493. return module.getVariableForExportName('*');
  14494. }
  14495. // export { foo } from './other'
  14496. const reexportDeclaration = this.reexportDescriptions.get(name);
  14497. if (reexportDeclaration) {
  14498. const [variable] = getVariableForExportNameRecursive(reexportDeclaration.module, reexportDeclaration.localName, importerForSideEffects, false, searchedNamesAndModules);
  14499. if (!variable) {
  14500. return this.error(logMissingExport(reexportDeclaration.localName, this.id, reexportDeclaration.module.id), reexportDeclaration.start);
  14501. }
  14502. if (importerForSideEffects) {
  14503. setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
  14504. if (this.info.moduleSideEffects) {
  14505. getOrCreate(importerForSideEffects.sideEffectDependenciesByVariable, variable, (getNewSet)).add(this);
  14506. }
  14507. }
  14508. return [variable];
  14509. }
  14510. const exportDeclaration = this.exports.get(name);
  14511. if (exportDeclaration) {
  14512. if (exportDeclaration === MISSING_EXPORT_SHIM_DESCRIPTION) {
  14513. return [this.exportShimVariable];
  14514. }
  14515. const name = exportDeclaration.localName;
  14516. const variable = this.traceVariable(name, {
  14517. importerForSideEffects,
  14518. searchedNamesAndModules
  14519. });
  14520. if (importerForSideEffects) {
  14521. setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
  14522. getOrCreate(importerForSideEffects.sideEffectDependenciesByVariable, variable, (getNewSet)).add(this);
  14523. }
  14524. return [variable];
  14525. }
  14526. if (onlyExplicit) {
  14527. return [null];
  14528. }
  14529. if (name !== 'default') {
  14530. const foundNamespaceReexport = this.namespaceReexportsByName.get(name) ??
  14531. this.getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules);
  14532. this.namespaceReexportsByName.set(name, foundNamespaceReexport);
  14533. if (foundNamespaceReexport[0]) {
  14534. return foundNamespaceReexport;
  14535. }
  14536. }
  14537. if (this.info.syntheticNamedExports) {
  14538. return [
  14539. getOrCreate(this.syntheticExports, name, () => new SyntheticNamedExportVariable(this.astContext, name, this.getSyntheticNamespace()))
  14540. ];
  14541. }
  14542. // we don't want to create shims when we are just
  14543. // probing export * modules for exports
  14544. if (!isExportAllSearch && this.options.shimMissingExports) {
  14545. this.shimMissingExport(name);
  14546. return [this.exportShimVariable];
  14547. }
  14548. return [null];
  14549. }
  14550. hasEffects() {
  14551. return this.info.moduleSideEffects === 'no-treeshake' || this.ast.hasCachedEffects();
  14552. }
  14553. include() {
  14554. const context = createInclusionContext();
  14555. if (this.ast.shouldBeIncluded(context))
  14556. this.ast.include(context, false);
  14557. }
  14558. includeAllExports(includeNamespaceMembers) {
  14559. if (!this.isExecuted) {
  14560. markModuleAndImpureDependenciesAsExecuted(this);
  14561. this.graph.needsTreeshakingPass = true;
  14562. }
  14563. for (const exportName of this.exports.keys()) {
  14564. if (includeNamespaceMembers || exportName !== this.info.syntheticNamedExports) {
  14565. const variable = this.getVariableForExportName(exportName)[0];
  14566. variable.deoptimizePath(UNKNOWN_PATH);
  14567. if (!variable.included) {
  14568. this.includeVariable(variable);
  14569. }
  14570. }
  14571. }
  14572. for (const name of this.getReexports()) {
  14573. const [variable] = this.getVariableForExportName(name);
  14574. if (variable) {
  14575. variable.deoptimizePath(UNKNOWN_PATH);
  14576. if (!variable.included) {
  14577. this.includeVariable(variable);
  14578. }
  14579. if (variable instanceof ExternalVariable) {
  14580. variable.module.reexported = true;
  14581. }
  14582. }
  14583. }
  14584. if (includeNamespaceMembers) {
  14585. this.namespace.setMergedNamespaces(this.includeAndGetAdditionalMergedNamespaces());
  14586. }
  14587. }
  14588. includeAllInBundle() {
  14589. this.ast.include(createInclusionContext(), true);
  14590. this.includeAllExports(false);
  14591. }
  14592. includeExportsByNames(names) {
  14593. if (!this.isExecuted) {
  14594. markModuleAndImpureDependenciesAsExecuted(this);
  14595. this.graph.needsTreeshakingPass = true;
  14596. }
  14597. let includeNamespaceMembers = false;
  14598. for (const name of names) {
  14599. const variable = this.getVariableForExportName(name)[0];
  14600. if (variable) {
  14601. variable.deoptimizePath(UNKNOWN_PATH);
  14602. if (!variable.included) {
  14603. this.includeVariable(variable);
  14604. }
  14605. }
  14606. if (!this.exports.has(name) && !this.reexportDescriptions.has(name)) {
  14607. includeNamespaceMembers = true;
  14608. }
  14609. }
  14610. if (includeNamespaceMembers) {
  14611. this.namespace.setMergedNamespaces(this.includeAndGetAdditionalMergedNamespaces());
  14612. }
  14613. }
  14614. isIncluded() {
  14615. // Modules where this.ast is missing have been loaded via this.load and are
  14616. // not yet fully processed, hence they cannot be included.
  14617. return (this.ast &&
  14618. (this.ast.included ||
  14619. this.namespace.included ||
  14620. this.importedFromNotTreeshaken ||
  14621. this.exportShimVariable.included));
  14622. }
  14623. linkImports() {
  14624. this.addModulesToImportDescriptions(this.importDescriptions);
  14625. this.addModulesToImportDescriptions(this.reexportDescriptions);
  14626. const externalExportAllModules = [];
  14627. for (const source of this.exportAllSources) {
  14628. const module = this.graph.modulesById.get(this.resolvedIds[source].id);
  14629. if (module instanceof ExternalModule) {
  14630. externalExportAllModules.push(module);
  14631. continue;
  14632. }
  14633. this.exportAllModules.push(module);
  14634. }
  14635. this.exportAllModules.push(...externalExportAllModules);
  14636. }
  14637. log(level, properties, pos) {
  14638. this.addLocationToLogProps(properties, pos);
  14639. this.options.onLog(level, properties);
  14640. }
  14641. render(options) {
  14642. const source = this.magicString.clone();
  14643. this.ast.render(source, options);
  14644. source.trim();
  14645. const { usesTopLevelAwait } = this.astContext;
  14646. if (usesTopLevelAwait && options.format !== 'es' && options.format !== 'system') {
  14647. return error(logInvalidFormatForTopLevelAwait(this.id, options.format));
  14648. }
  14649. return { source, usesTopLevelAwait };
  14650. }
  14651. setSource({ ast, code, customTransformCache, originalCode, originalSourcemap, resolvedIds, sourcemapChain, transformDependencies, transformFiles, ...moduleOptions }) {
  14652. timeStart('generate ast', 3);
  14653. this.info.code = code;
  14654. this.originalCode = originalCode;
  14655. // We need to call decodedSourcemap on the input in case they were hydrated from json in the cache and don't
  14656. // have the lazy evaluation cache configured. Right now this isn't enforced by the type system because the
  14657. // RollupCache stores `ExistingDecodedSourcemap` instead of `ExistingRawSourcemap`
  14658. this.originalSourcemap = decodedSourcemap(originalSourcemap);
  14659. this.sourcemapChain = sourcemapChain.map(mapOrMissing => mapOrMissing.missing ? mapOrMissing : decodedSourcemap(mapOrMissing));
  14660. // If coming from cache and this value is already fully decoded, we want to re-encode here to save memory.
  14661. resetSourcemapCache(this.originalSourcemap, this.sourcemapChain);
  14662. if (transformFiles) {
  14663. this.transformFiles = transformFiles;
  14664. }
  14665. this.transformDependencies = transformDependencies;
  14666. this.customTransformCache = customTransformCache;
  14667. this.updateOptions(moduleOptions);
  14668. const moduleAst = ast ?? this.tryParse();
  14669. timeEnd('generate ast', 3);
  14670. timeStart('analyze ast', 3);
  14671. this.resolvedIds = resolvedIds ?? Object.create(null);
  14672. // By default, `id` is the file name. Custom resolvers and loaders
  14673. // can change that, but it makes sense to use it for the source file name
  14674. const fileName = this.id;
  14675. this.magicString = new MagicString(code, {
  14676. filename: (this.excludeFromSourcemap ? null : fileName),
  14677. indentExclusionRanges: []
  14678. });
  14679. this.astContext = {
  14680. addDynamicImport: this.addDynamicImport.bind(this),
  14681. addExport: this.addExport.bind(this),
  14682. addImport: this.addImport.bind(this),
  14683. addImportMeta: this.addImportMeta.bind(this),
  14684. code,
  14685. deoptimizationTracker: this.graph.deoptimizationTracker,
  14686. error: this.error.bind(this),
  14687. fileName,
  14688. getExports: this.getExports.bind(this),
  14689. getModuleExecIndex: () => this.execIndex,
  14690. getModuleName: this.basename.bind(this),
  14691. getNodeConstructor: (name) => nodeConstructors[name] || nodeConstructors.UnknownNode,
  14692. getReexports: this.getReexports.bind(this),
  14693. importDescriptions: this.importDescriptions,
  14694. includeAllExports: () => this.includeAllExports(true),
  14695. includeDynamicImport: this.includeDynamicImport.bind(this),
  14696. includeVariableInModule: this.includeVariableInModule.bind(this),
  14697. log: this.log.bind(this),
  14698. magicString: this.magicString,
  14699. manualPureFunctions: this.graph.pureFunctions,
  14700. module: this,
  14701. moduleContext: this.context,
  14702. options: this.options,
  14703. requestTreeshakingPass: () => (this.graph.needsTreeshakingPass = true),
  14704. traceExport: (name) => this.getVariableForExportName(name)[0],
  14705. traceVariable: this.traceVariable.bind(this),
  14706. usesTopLevelAwait: false
  14707. };
  14708. this.scope = new ModuleScope(this.graph.scope, this.astContext);
  14709. this.namespace = new NamespaceVariable(this.astContext);
  14710. this.ast = new Program(moduleAst, { context: this.astContext, type: 'Module' }, this.scope);
  14711. // Assign AST directly if has existing one as there's no way to drop it from memory.
  14712. // If cache is enabled, also assign directly as otherwise it takes more CPU and memory to re-compute.
  14713. if (ast || this.options.cache !== false) {
  14714. this.info.ast = moduleAst;
  14715. }
  14716. else {
  14717. // Make lazy and apply LRU cache to not hog the memory
  14718. Object.defineProperty(this.info, 'ast', {
  14719. get: () => {
  14720. if (this.graph.astLru.has(fileName)) {
  14721. return this.graph.astLru.get(fileName);
  14722. }
  14723. else {
  14724. const parsedAst = this.tryParse();
  14725. this.graph.astLru.set(fileName, parsedAst);
  14726. return parsedAst;
  14727. }
  14728. }
  14729. });
  14730. }
  14731. timeEnd('analyze ast', 3);
  14732. }
  14733. toJSON() {
  14734. return {
  14735. assertions: this.info.assertions,
  14736. ast: this.info.ast,
  14737. code: this.info.code,
  14738. customTransformCache: this.customTransformCache,
  14739. // eslint-disable-next-line unicorn/prefer-spread
  14740. dependencies: Array.from(this.dependencies, getId),
  14741. id: this.id,
  14742. meta: this.info.meta,
  14743. moduleSideEffects: this.info.moduleSideEffects,
  14744. originalCode: this.originalCode,
  14745. originalSourcemap: this.originalSourcemap,
  14746. resolvedIds: this.resolvedIds,
  14747. sourcemapChain: this.sourcemapChain,
  14748. syntheticNamedExports: this.info.syntheticNamedExports,
  14749. transformDependencies: this.transformDependencies,
  14750. transformFiles: this.transformFiles
  14751. };
  14752. }
  14753. traceVariable(name, { importerForSideEffects, isExportAllSearch, searchedNamesAndModules } = EMPTY_OBJECT) {
  14754. const localVariable = this.scope.variables.get(name);
  14755. if (localVariable) {
  14756. return localVariable;
  14757. }
  14758. const importDescription = this.importDescriptions.get(name);
  14759. if (importDescription) {
  14760. const otherModule = importDescription.module;
  14761. if (otherModule instanceof Module && importDescription.name === '*') {
  14762. return otherModule.namespace;
  14763. }
  14764. const [declaration] = getVariableForExportNameRecursive(otherModule, importDescription.name, importerForSideEffects || this, isExportAllSearch, searchedNamesAndModules);
  14765. if (!declaration) {
  14766. return this.error(logMissingExport(importDescription.name, this.id, otherModule.id), importDescription.start);
  14767. }
  14768. return declaration;
  14769. }
  14770. return null;
  14771. }
  14772. updateOptions({ meta, moduleSideEffects, syntheticNamedExports }) {
  14773. if (moduleSideEffects != null) {
  14774. this.info.moduleSideEffects = moduleSideEffects;
  14775. }
  14776. if (syntheticNamedExports != null) {
  14777. this.info.syntheticNamedExports = syntheticNamedExports;
  14778. }
  14779. if (meta != null) {
  14780. Object.assign(this.info.meta, meta);
  14781. }
  14782. }
  14783. addDynamicImport(node) {
  14784. let argument = node.source;
  14785. if (argument instanceof TemplateLiteral) {
  14786. if (argument.quasis.length === 1 && argument.quasis[0].value.cooked) {
  14787. argument = argument.quasis[0].value.cooked;
  14788. }
  14789. }
  14790. else if (argument instanceof Literal && typeof argument.value === 'string') {
  14791. argument = argument.value;
  14792. }
  14793. this.dynamicImports.push({ argument, id: null, node, resolution: null });
  14794. }
  14795. addExport(node) {
  14796. if (node instanceof ExportDefaultDeclaration) {
  14797. // export default foo;
  14798. this.exports.set('default', {
  14799. identifier: node.variable.getAssignedVariableName(),
  14800. localName: 'default'
  14801. });
  14802. }
  14803. else if (node instanceof ExportAllDeclaration) {
  14804. const source = node.source.value;
  14805. this.addSource(source, node);
  14806. if (node.exported) {
  14807. // export * as name from './other'
  14808. const name = node.exported.name;
  14809. this.reexportDescriptions.set(name, {
  14810. localName: '*',
  14811. module: null,
  14812. source,
  14813. start: node.start
  14814. });
  14815. }
  14816. else {
  14817. // export * from './other'
  14818. this.exportAllSources.add(source);
  14819. }
  14820. }
  14821. else if (node.source instanceof Literal) {
  14822. // export { name } from './other'
  14823. const source = node.source.value;
  14824. this.addSource(source, node);
  14825. for (const { exported, local, start } of node.specifiers) {
  14826. const name = exported instanceof Literal ? exported.value : exported.name;
  14827. this.reexportDescriptions.set(name, {
  14828. localName: local instanceof Literal ? local.value : local.name,
  14829. module: null,
  14830. source,
  14831. start
  14832. });
  14833. }
  14834. }
  14835. else if (node.declaration) {
  14836. const declaration = node.declaration;
  14837. if (declaration instanceof VariableDeclaration) {
  14838. // export var { foo, bar } = ...
  14839. // export var foo = 1, bar = 2;
  14840. for (const declarator of declaration.declarations) {
  14841. for (const localName of extractAssignedNames(declarator.id)) {
  14842. this.exports.set(localName, { identifier: null, localName });
  14843. }
  14844. }
  14845. }
  14846. else {
  14847. // export function foo () {}
  14848. const localName = declaration.id.name;
  14849. this.exports.set(localName, { identifier: null, localName });
  14850. }
  14851. }
  14852. else {
  14853. // export { foo, bar, baz }
  14854. for (const { local, exported } of node.specifiers) {
  14855. // except for reexports, local must be an Identifier
  14856. const localName = local.name;
  14857. const exportedName = exported instanceof Identifier ? exported.name : exported.value;
  14858. this.exports.set(exportedName, { identifier: null, localName });
  14859. }
  14860. }
  14861. }
  14862. addImport(node) {
  14863. const source = node.source.value;
  14864. this.addSource(source, node);
  14865. for (const specifier of node.specifiers) {
  14866. const name = specifier instanceof ImportDefaultSpecifier
  14867. ? 'default'
  14868. : specifier instanceof ImportNamespaceSpecifier
  14869. ? '*'
  14870. : specifier.imported instanceof Identifier
  14871. ? specifier.imported.name
  14872. : specifier.imported.value;
  14873. this.importDescriptions.set(specifier.local.name, {
  14874. module: null,
  14875. name,
  14876. source,
  14877. start: specifier.start
  14878. });
  14879. }
  14880. }
  14881. addImportMeta(node) {
  14882. this.importMetas.push(node);
  14883. }
  14884. addLocationToLogProps(properties, pos) {
  14885. properties.id = this.id;
  14886. properties.pos = pos;
  14887. let code = this.info.code;
  14888. const location = locate(code, pos, { offsetLine: 1 });
  14889. if (location) {
  14890. let { column, line } = location;
  14891. try {
  14892. ({ column, line } = getOriginalLocation(this.sourcemapChain, { column, line }));
  14893. code = this.originalCode;
  14894. }
  14895. catch (error_) {
  14896. this.options.onLog(LOGLEVEL_WARN, logInvalidSourcemapForError(error_, this.id, column, line, pos));
  14897. }
  14898. augmentCodeLocation(properties, { column, line }, code, this.id);
  14899. }
  14900. }
  14901. addModulesToImportDescriptions(importDescription) {
  14902. for (const specifier of importDescription.values()) {
  14903. const { id } = this.resolvedIds[specifier.source];
  14904. specifier.module = this.graph.modulesById.get(id);
  14905. }
  14906. }
  14907. addRelevantSideEffectDependencies(relevantDependencies, necessaryDependencies, alwaysCheckedDependencies) {
  14908. const handledDependencies = new Set();
  14909. const addSideEffectDependencies = (possibleDependencies) => {
  14910. for (const dependency of possibleDependencies) {
  14911. if (handledDependencies.has(dependency)) {
  14912. continue;
  14913. }
  14914. handledDependencies.add(dependency);
  14915. if (necessaryDependencies.has(dependency)) {
  14916. relevantDependencies.add(dependency);
  14917. continue;
  14918. }
  14919. if (!(dependency.info.moduleSideEffects || alwaysCheckedDependencies.has(dependency))) {
  14920. continue;
  14921. }
  14922. if (dependency instanceof ExternalModule || dependency.hasEffects()) {
  14923. relevantDependencies.add(dependency);
  14924. continue;
  14925. }
  14926. addSideEffectDependencies(dependency.dependencies);
  14927. }
  14928. };
  14929. addSideEffectDependencies(this.dependencies);
  14930. addSideEffectDependencies(alwaysCheckedDependencies);
  14931. }
  14932. addSource(source, declaration) {
  14933. const parsedAssertions = getAssertionsFromImportExportDeclaration(declaration.assertions);
  14934. const existingAssertions = this.sourcesWithAssertions.get(source);
  14935. if (existingAssertions) {
  14936. if (doAssertionsDiffer(existingAssertions, parsedAssertions)) {
  14937. this.log(LOGLEVEL_WARN, logInconsistentImportAssertions(existingAssertions, parsedAssertions, source, this.id), declaration.start);
  14938. }
  14939. }
  14940. else {
  14941. this.sourcesWithAssertions.set(source, parsedAssertions);
  14942. }
  14943. }
  14944. getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules) {
  14945. let foundSyntheticDeclaration = null;
  14946. const foundInternalDeclarations = new Map();
  14947. const foundExternalDeclarations = new Set();
  14948. for (const module of this.exportAllModules) {
  14949. // Synthetic namespaces should not hide "regular" exports of the same name
  14950. if (module.info.syntheticNamedExports === name) {
  14951. continue;
  14952. }
  14953. const [variable, indirectExternal] = getVariableForExportNameRecursive(module, name, importerForSideEffects, true,
  14954. // We are creating a copy to handle the case where the same binding is
  14955. // imported through different namespace reexports gracefully
  14956. copyNameToModulesMap(searchedNamesAndModules));
  14957. if (module instanceof ExternalModule || indirectExternal) {
  14958. foundExternalDeclarations.add(variable);
  14959. }
  14960. else if (variable instanceof SyntheticNamedExportVariable) {
  14961. if (!foundSyntheticDeclaration) {
  14962. foundSyntheticDeclaration = variable;
  14963. }
  14964. }
  14965. else if (variable) {
  14966. foundInternalDeclarations.set(variable, module);
  14967. }
  14968. }
  14969. if (foundInternalDeclarations.size > 0) {
  14970. const foundDeclarationList = [...foundInternalDeclarations];
  14971. const usedDeclaration = foundDeclarationList[0][0];
  14972. if (foundDeclarationList.length === 1) {
  14973. return [usedDeclaration];
  14974. }
  14975. this.options.onLog(LOGLEVEL_WARN, logNamespaceConflict(name, this.id, foundDeclarationList.map(([, module]) => module.id)));
  14976. // TODO we are pretending it was not found while it should behave like "undefined"
  14977. return [null];
  14978. }
  14979. if (foundExternalDeclarations.size > 0) {
  14980. const foundDeclarationList = [...foundExternalDeclarations];
  14981. const usedDeclaration = foundDeclarationList[0];
  14982. if (foundDeclarationList.length > 1) {
  14983. this.options.onLog(LOGLEVEL_WARN, logAmbiguousExternalNamespaces(name, this.id, usedDeclaration.module.id, foundDeclarationList.map(declaration => declaration.module.id)));
  14984. }
  14985. return [usedDeclaration, true];
  14986. }
  14987. if (foundSyntheticDeclaration) {
  14988. return [foundSyntheticDeclaration];
  14989. }
  14990. return [null];
  14991. }
  14992. includeAndGetAdditionalMergedNamespaces() {
  14993. const externalNamespaces = new Set();
  14994. const syntheticNamespaces = new Set();
  14995. for (const module of [this, ...this.exportAllModules]) {
  14996. if (module instanceof ExternalModule) {
  14997. const [externalVariable] = module.getVariableForExportName('*');
  14998. externalVariable.include();
  14999. this.includedImports.add(externalVariable);
  15000. externalNamespaces.add(externalVariable);
  15001. }
  15002. else if (module.info.syntheticNamedExports) {
  15003. const syntheticNamespace = module.getSyntheticNamespace();
  15004. syntheticNamespace.include();
  15005. this.includedImports.add(syntheticNamespace);
  15006. syntheticNamespaces.add(syntheticNamespace);
  15007. }
  15008. }
  15009. return [...syntheticNamespaces, ...externalNamespaces];
  15010. }
  15011. includeDynamicImport(node) {
  15012. const resolution = this.dynamicImports.find(dynamicImport => dynamicImport.node === node).resolution;
  15013. if (resolution instanceof Module) {
  15014. resolution.includedDynamicImporters.push(this);
  15015. const importedNames = this.options.treeshake
  15016. ? node.getDeterministicImportedNames()
  15017. : undefined;
  15018. if (importedNames) {
  15019. resolution.includeExportsByNames(importedNames);
  15020. }
  15021. else {
  15022. resolution.includeAllExports(true);
  15023. }
  15024. }
  15025. }
  15026. includeVariable(variable) {
  15027. const variableModule = variable.module;
  15028. if (variable.included) {
  15029. if (variableModule instanceof Module && variableModule !== this) {
  15030. getAndExtendSideEffectModules(variable, this);
  15031. }
  15032. }
  15033. else {
  15034. variable.include();
  15035. this.graph.needsTreeshakingPass = true;
  15036. if (variableModule instanceof Module) {
  15037. if (!variableModule.isExecuted) {
  15038. markModuleAndImpureDependenciesAsExecuted(variableModule);
  15039. }
  15040. if (variableModule !== this) {
  15041. const sideEffectModules = getAndExtendSideEffectModules(variable, this);
  15042. for (const module of sideEffectModules) {
  15043. if (!module.isExecuted) {
  15044. markModuleAndImpureDependenciesAsExecuted(module);
  15045. }
  15046. }
  15047. }
  15048. }
  15049. }
  15050. }
  15051. includeVariableInModule(variable) {
  15052. this.includeVariable(variable);
  15053. const variableModule = variable.module;
  15054. if (variableModule && variableModule !== this) {
  15055. this.includedImports.add(variable);
  15056. }
  15057. }
  15058. shimMissingExport(name) {
  15059. this.options.onLog(LOGLEVEL_WARN, logShimmedExport(this.id, name));
  15060. this.exports.set(name, MISSING_EXPORT_SHIM_DESCRIPTION);
  15061. }
  15062. tryParse() {
  15063. try {
  15064. return this.graph.contextParse(this.info.code);
  15065. }
  15066. catch (error_) {
  15067. return this.error(logParseError(error_, this.id), error_.pos);
  15068. }
  15069. }
  15070. }
  15071. // if there is a cyclic import in the reexport chain, we should not
  15072. // import from the original module but from the cyclic module to not
  15073. // mess up execution order.
  15074. function setAlternativeExporterIfCyclic(variable, importer, reexporter) {
  15075. if (variable.module instanceof Module && variable.module !== reexporter) {
  15076. const exporterCycles = variable.module.cycles;
  15077. if (exporterCycles.size > 0) {
  15078. const importerCycles = reexporter.cycles;
  15079. for (const cycleSymbol of importerCycles) {
  15080. if (exporterCycles.has(cycleSymbol)) {
  15081. importer.alternativeReexportModules.set(variable, reexporter);
  15082. break;
  15083. }
  15084. }
  15085. }
  15086. }
  15087. }
  15088. const copyNameToModulesMap = (searchedNamesAndModules) => searchedNamesAndModules &&
  15089. // eslint-disable-next-line unicorn/prefer-spread
  15090. new Map(Array.from(searchedNamesAndModules, ([name, modules]) => [name, new Set(modules)]));
  15091. function removeJsExtension(name) {
  15092. return name.endsWith('.js') ? name.slice(0, -3) : name;
  15093. }
  15094. function getCompleteAmdId(options, chunkId) {
  15095. if (options.autoId) {
  15096. return `${options.basePath ? options.basePath + '/' : ''}${removeJsExtension(chunkId)}`;
  15097. }
  15098. return options.id ?? '';
  15099. }
  15100. function getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, mechanism = 'return ') {
  15101. const { _, getDirectReturnFunction, getFunctionIntro, getPropertyAccess, n, s } = snippets;
  15102. if (!namedExportsMode) {
  15103. return `${n}${n}${mechanism}${getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings, getPropertyAccess)};`;
  15104. }
  15105. let exportBlock = '';
  15106. for (const { defaultVariableName, importPath, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  15107. if (reexports && namedExportsMode) {
  15108. for (const specifier of reexports) {
  15109. if (specifier.reexported !== '*') {
  15110. const importName = getReexportedImportName(name, specifier.imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, importPath, externalLiveBindings, getPropertyAccess);
  15111. if (exportBlock)
  15112. exportBlock += n;
  15113. if (specifier.imported !== '*' && specifier.needsLiveBinding) {
  15114. const [left, right] = getDirectReturnFunction([], {
  15115. functionReturn: true,
  15116. lineBreakIndent: null,
  15117. name: null
  15118. });
  15119. exportBlock +=
  15120. `Object.defineProperty(exports,${_}'${specifier.reexported}',${_}{${n}` +
  15121. `${t}enumerable:${_}true,${n}` +
  15122. `${t}get:${_}${left}${importName}${right}${n}});`;
  15123. }
  15124. else {
  15125. exportBlock += `exports${getPropertyAccess(specifier.reexported)}${_}=${_}${importName};`;
  15126. }
  15127. }
  15128. }
  15129. }
  15130. }
  15131. for (const { exported, local } of exports) {
  15132. const lhs = `exports${getPropertyAccess(exported)}`;
  15133. const rhs = local;
  15134. if (lhs !== rhs) {
  15135. if (exportBlock)
  15136. exportBlock += n;
  15137. exportBlock += `${lhs}${_}=${_}${rhs};`;
  15138. }
  15139. }
  15140. for (const { name, reexports } of dependencies) {
  15141. if (reexports && namedExportsMode) {
  15142. for (const specifier of reexports) {
  15143. if (specifier.reexported === '*') {
  15144. if (exportBlock)
  15145. exportBlock += n;
  15146. const copyPropertyIfNecessary = `{${n}${t}if${_}(k${_}!==${_}'default'${_}&&${_}!Object.prototype.hasOwnProperty.call(exports,${_}k))${_}${getDefineProperty(name, specifier.needsLiveBinding, t, snippets)}${s}${n}}`;
  15147. exportBlock += `Object.keys(${name}).forEach(${getFunctionIntro(['k'], {
  15148. isAsync: false,
  15149. name: null
  15150. })}${copyPropertyIfNecessary});`;
  15151. }
  15152. }
  15153. }
  15154. }
  15155. if (exportBlock) {
  15156. return `${n}${n}${exportBlock}`;
  15157. }
  15158. return '';
  15159. }
  15160. function getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings, getPropertyAccess) {
  15161. if (exports.length > 0) {
  15162. return exports[0].local;
  15163. }
  15164. else {
  15165. for (const { defaultVariableName, importPath, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  15166. if (reexports) {
  15167. return getReexportedImportName(name, reexports[0].imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, importPath, externalLiveBindings, getPropertyAccess);
  15168. }
  15169. }
  15170. }
  15171. }
  15172. function getReexportedImportName(moduleVariableName, imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, moduleId, externalLiveBindings, getPropertyAccess) {
  15173. if (imported === 'default') {
  15174. if (!isChunk) {
  15175. const moduleInterop = interop(moduleId);
  15176. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  15177. ? defaultVariableName
  15178. : moduleVariableName;
  15179. return isDefaultAProperty(moduleInterop, externalLiveBindings)
  15180. ? `${variableName}${getPropertyAccess('default')}`
  15181. : variableName;
  15182. }
  15183. return depNamedExportsMode
  15184. ? `${moduleVariableName}${getPropertyAccess('default')}`
  15185. : moduleVariableName;
  15186. }
  15187. if (imported === '*') {
  15188. return (isChunk ? !depNamedExportsMode : namespaceInteropHelpersByInteropType[interop(moduleId)])
  15189. ? namespaceVariableName
  15190. : moduleVariableName;
  15191. }
  15192. return `${moduleVariableName}${getPropertyAccess(imported)}`;
  15193. }
  15194. function getEsModuleValue(getObject) {
  15195. return getObject([['value', 'true']], {
  15196. lineBreakIndent: null
  15197. });
  15198. }
  15199. function getNamespaceMarkers(hasNamedExports, addEsModule, addNamespaceToStringTag, { _, getObject }) {
  15200. if (hasNamedExports) {
  15201. if (addEsModule) {
  15202. if (addNamespaceToStringTag) {
  15203. return `Object.defineProperties(exports,${_}${getObject([
  15204. ['__esModule', getEsModuleValue(getObject)],
  15205. [null, `[Symbol.toStringTag]:${_}${getToStringTagValue(getObject)}`]
  15206. ], {
  15207. lineBreakIndent: null
  15208. })});`;
  15209. }
  15210. return `Object.defineProperty(exports,${_}'__esModule',${_}${getEsModuleValue(getObject)});`;
  15211. }
  15212. if (addNamespaceToStringTag) {
  15213. return `Object.defineProperty(exports,${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)});`;
  15214. }
  15215. }
  15216. return '';
  15217. }
  15218. const getDefineProperty = (name, needsLiveBinding, t, { _, getDirectReturnFunction, n }) => {
  15219. if (needsLiveBinding) {
  15220. const [left, right] = getDirectReturnFunction([], {
  15221. functionReturn: true,
  15222. lineBreakIndent: null,
  15223. name: null
  15224. });
  15225. return (`Object.defineProperty(exports,${_}k,${_}{${n}` +
  15226. `${t}${t}enumerable:${_}true,${n}` +
  15227. `${t}${t}get:${_}${left}${name}[k]${right}${n}${t}})`);
  15228. }
  15229. return `exports[k]${_}=${_}${name}[k]`;
  15230. };
  15231. function getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, indent, snippets) {
  15232. const { _, cnst, n } = snippets;
  15233. const neededInteropHelpers = new Set();
  15234. const interopStatements = [];
  15235. const addInteropStatement = (helperVariableName, helper, dependencyVariableName) => {
  15236. neededInteropHelpers.add(helper);
  15237. interopStatements.push(`${cnst} ${helperVariableName}${_}=${_}/*#__PURE__*/${helper}(${dependencyVariableName});`);
  15238. };
  15239. for (const { defaultVariableName, imports, importPath, isChunk, name, namedExportsMode, namespaceVariableName, reexports } of dependencies) {
  15240. if (isChunk) {
  15241. for (const { imported, reexported } of [
  15242. ...(imports || []),
  15243. ...(reexports || [])
  15244. ]) {
  15245. if (imported === '*' && reexported !== '*') {
  15246. if (!namedExportsMode) {
  15247. addInteropStatement(namespaceVariableName, INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE, name);
  15248. }
  15249. break;
  15250. }
  15251. }
  15252. }
  15253. else {
  15254. const moduleInterop = interop(importPath);
  15255. let hasDefault = false;
  15256. let hasNamespace = false;
  15257. for (const { imported, reexported } of [
  15258. ...(imports || []),
  15259. ...(reexports || [])
  15260. ]) {
  15261. let helper;
  15262. let variableName;
  15263. if (imported === 'default') {
  15264. if (!hasDefault) {
  15265. hasDefault = true;
  15266. if (defaultVariableName !== namespaceVariableName) {
  15267. variableName = defaultVariableName;
  15268. helper = defaultInteropHelpersByInteropType[moduleInterop];
  15269. }
  15270. }
  15271. }
  15272. else if (imported === '*' && reexported !== '*' && !hasNamespace) {
  15273. hasNamespace = true;
  15274. helper = namespaceInteropHelpersByInteropType[moduleInterop];
  15275. variableName = namespaceVariableName;
  15276. }
  15277. if (helper) {
  15278. addInteropStatement(variableName, helper, name);
  15279. }
  15280. }
  15281. }
  15282. }
  15283. return `${getHelpersBlock(neededInteropHelpers, accessedGlobals, indent, snippets, externalLiveBindings, freeze, namespaceToStringTag)}${interopStatements.length > 0 ? `${interopStatements.join(n)}${n}${n}` : ''}`;
  15284. }
  15285. function addJsExtension(name) {
  15286. return name.endsWith('.js') ? name : name + '.js';
  15287. }
  15288. // AMD resolution will only respect the AMD baseUrl if the .js extension is omitted.
  15289. // The assumption is that this makes sense for all relative ids:
  15290. // https://requirejs.org/docs/api.html#jsfiles
  15291. function updateExtensionForRelativeAmdId(id, forceJsExtensionForImports) {
  15292. if (id[0] !== '.') {
  15293. return id;
  15294. }
  15295. return forceJsExtensionForImports ? addJsExtension(id) : removeJsExtension(id);
  15296. }
  15297. const require$$0 = [
  15298. "assert",
  15299. "async_hooks",
  15300. "buffer",
  15301. "child_process",
  15302. "cluster",
  15303. "console",
  15304. "constants",
  15305. "crypto",
  15306. "dgram",
  15307. "diagnostics_channel",
  15308. "dns",
  15309. "domain",
  15310. "events",
  15311. "fs",
  15312. "http",
  15313. "http2",
  15314. "https",
  15315. "inspector",
  15316. "module",
  15317. "net",
  15318. "os",
  15319. "path",
  15320. "perf_hooks",
  15321. "process",
  15322. "punycode",
  15323. "querystring",
  15324. "readline",
  15325. "repl",
  15326. "stream",
  15327. "string_decoder",
  15328. "timers",
  15329. "tls",
  15330. "trace_events",
  15331. "tty",
  15332. "url",
  15333. "util",
  15334. "v8",
  15335. "vm",
  15336. "wasi",
  15337. "worker_threads",
  15338. "zlib"
  15339. ];
  15340. var _static = require$$0;
  15341. const builtinModules = /*@__PURE__*/getDefaultExportFromCjs(_static);
  15342. const nodeBuiltins = new Set([
  15343. ...builtinModules,
  15344. // TODO
  15345. // remove once builtin-modules includes PR: https://github.com/sindresorhus/builtin-modules/pull/17
  15346. 'assert/strict',
  15347. 'dns/promises',
  15348. 'fs/promises',
  15349. 'path/posix',
  15350. 'path/win32',
  15351. 'readline/promises',
  15352. 'stream/consumers',
  15353. 'stream/promises',
  15354. 'stream/web',
  15355. 'timers/promises',
  15356. 'util/types'
  15357. ]);
  15358. function warnOnBuiltins(log, dependencies) {
  15359. const externalBuiltins = dependencies
  15360. .map(({ importPath }) => importPath)
  15361. .filter(importPath => nodeBuiltins.has(importPath) || importPath.startsWith('node:'));
  15362. if (externalBuiltins.length === 0)
  15363. return;
  15364. log(LOGLEVEL_WARN, logMissingNodeBuiltins(externalBuiltins));
  15365. }
  15366. function amd(magicString, { accessedGlobals, dependencies, exports, hasDefaultExport, hasExports, id, indent: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, log, outro, snippets }, { amd, esModule, externalLiveBindings, freeze, interop, namespaceToStringTag, strict }) {
  15367. warnOnBuiltins(log, dependencies);
  15368. const deps = dependencies.map(m => `'${updateExtensionForRelativeAmdId(m.importPath, amd.forceJsExtensionForImports)}'`);
  15369. const parameters = dependencies.map(m => m.name);
  15370. const { n, getNonArrowFunctionIntro, _ } = snippets;
  15371. if (namedExportsMode && hasExports) {
  15372. parameters.unshift(`exports`);
  15373. deps.unshift(`'exports'`);
  15374. }
  15375. if (accessedGlobals.has('require')) {
  15376. parameters.unshift('require');
  15377. deps.unshift(`'require'`);
  15378. }
  15379. if (accessedGlobals.has('module')) {
  15380. parameters.unshift('module');
  15381. deps.unshift(`'module'`);
  15382. }
  15383. const completeAmdId = getCompleteAmdId(amd, id);
  15384. const defineParameters = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
  15385. (deps.length > 0 ? `[${deps.join(`,${_}`)}],${_}` : ``);
  15386. const useStrict = strict ? `${_}'use strict';` : '';
  15387. magicString.prepend(`${intro}${getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets)}`);
  15388. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings);
  15389. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && (esModule === true || (esModule === 'if-default-prop' && hasDefaultExport)), isModuleFacade && namespaceToStringTag, snippets);
  15390. if (namespaceMarkers) {
  15391. namespaceMarkers = n + n + namespaceMarkers;
  15392. }
  15393. magicString
  15394. .append(`${exportBlock}${namespaceMarkers}${outro}`)
  15395. .indent(t)
  15396. // factory function should be wrapped by parentheses to avoid lazy parsing,
  15397. // cf. https://v8.dev/blog/preparser#pife
  15398. .prepend(`${amd.define}(${defineParameters}(${getNonArrowFunctionIntro(parameters, {
  15399. isAsync: false,
  15400. name: null
  15401. })}{${useStrict}${n}${n}`)
  15402. .append(`${n}${n}}));`);
  15403. }
  15404. function cjs(magicString, { accessedGlobals, dependencies, exports, hasDefaultExport, hasExports, indent: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, outro, snippets }, { compact, esModule, externalLiveBindings, freeze, interop, namespaceToStringTag, strict }) {
  15405. const { _, n } = snippets;
  15406. const useStrict = strict ? `'use strict';${n}${n}` : '';
  15407. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && (esModule === true || (esModule === 'if-default-prop' && hasDefaultExport)), isModuleFacade && namespaceToStringTag, snippets);
  15408. if (namespaceMarkers) {
  15409. namespaceMarkers += n + n;
  15410. }
  15411. const importBlock = getImportBlock$1(dependencies, snippets, compact);
  15412. const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets);
  15413. magicString.prepend(`${useStrict}${intro}${namespaceMarkers}${importBlock}${interopBlock}`);
  15414. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, `module.exports${_}=${_}`);
  15415. magicString.append(`${exportBlock}${outro}`);
  15416. }
  15417. function getImportBlock$1(dependencies, { _, cnst, n }, compact) {
  15418. let importBlock = '';
  15419. let definingVariable = false;
  15420. for (const { importPath, name, reexports, imports } of dependencies) {
  15421. if (!reexports && !imports) {
  15422. if (importBlock) {
  15423. importBlock += compact && !definingVariable ? ',' : `;${n}`;
  15424. }
  15425. definingVariable = false;
  15426. importBlock += `require('${importPath}')`;
  15427. }
  15428. else {
  15429. importBlock += compact && definingVariable ? ',' : `${importBlock ? `;${n}` : ''}${cnst} `;
  15430. definingVariable = true;
  15431. importBlock += `${name}${_}=${_}require('${importPath}')`;
  15432. }
  15433. }
  15434. if (importBlock) {
  15435. return `${importBlock};${n}${n}`;
  15436. }
  15437. return '';
  15438. }
  15439. function es(magicString, { accessedGlobals, indent: t, intro, outro, dependencies, exports, snippets }, { externalLiveBindings, freeze, namespaceToStringTag }) {
  15440. const { n } = snippets;
  15441. const importBlock = getImportBlock(dependencies, snippets);
  15442. if (importBlock.length > 0)
  15443. intro += importBlock.join(n) + n + n;
  15444. intro += getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, namespaceToStringTag);
  15445. if (intro)
  15446. magicString.prepend(intro);
  15447. const exportBlock = getExportBlock(exports, snippets);
  15448. if (exportBlock.length > 0)
  15449. magicString.append(n + n + exportBlock.join(n).trim());
  15450. if (outro)
  15451. magicString.append(outro);
  15452. magicString.trim();
  15453. }
  15454. function getImportBlock(dependencies, { _ }) {
  15455. const importBlock = [];
  15456. for (const { importPath, reexports, imports, name, assertions } of dependencies) {
  15457. const assertion = assertions ? `${_}assert${_}${assertions}` : '';
  15458. const pathWithAssertion = `'${importPath}'${assertion};`;
  15459. if (!reexports && !imports) {
  15460. importBlock.push(`import${_}${pathWithAssertion}`);
  15461. continue;
  15462. }
  15463. if (imports) {
  15464. let defaultImport = null;
  15465. let starImport = null;
  15466. const importedNames = [];
  15467. for (const specifier of imports) {
  15468. if (specifier.imported === 'default') {
  15469. defaultImport = specifier;
  15470. }
  15471. else if (specifier.imported === '*') {
  15472. starImport = specifier;
  15473. }
  15474. else {
  15475. importedNames.push(specifier);
  15476. }
  15477. }
  15478. if (starImport) {
  15479. importBlock.push(`import${_}*${_}as ${starImport.local} from${_}${pathWithAssertion}`);
  15480. }
  15481. if (defaultImport && importedNames.length === 0) {
  15482. importBlock.push(`import ${defaultImport.local} from${_}${pathWithAssertion}`);
  15483. }
  15484. else if (importedNames.length > 0) {
  15485. importBlock.push(`import ${defaultImport ? `${defaultImport.local},${_}` : ''}{${_}${importedNames
  15486. .map(specifier => specifier.imported === specifier.local
  15487. ? specifier.imported
  15488. : `${specifier.imported} as ${specifier.local}`)
  15489. .join(`,${_}`)}${_}}${_}from${_}${pathWithAssertion}`);
  15490. }
  15491. }
  15492. if (reexports) {
  15493. let starExport = null;
  15494. const namespaceReexports = [];
  15495. const namedReexports = [];
  15496. for (const specifier of reexports) {
  15497. if (specifier.reexported === '*') {
  15498. starExport = specifier;
  15499. }
  15500. else if (specifier.imported === '*') {
  15501. namespaceReexports.push(specifier);
  15502. }
  15503. else {
  15504. namedReexports.push(specifier);
  15505. }
  15506. }
  15507. if (starExport) {
  15508. importBlock.push(`export${_}*${_}from${_}${pathWithAssertion}`);
  15509. }
  15510. if (namespaceReexports.length > 0) {
  15511. if (!imports ||
  15512. !imports.some(specifier => specifier.imported === '*' && specifier.local === name)) {
  15513. importBlock.push(`import${_}*${_}as ${name} from${_}${pathWithAssertion}`);
  15514. }
  15515. for (const specifier of namespaceReexports) {
  15516. importBlock.push(`export${_}{${_}${name === specifier.reexported ? name : `${name} as ${specifier.reexported}`} };`);
  15517. }
  15518. }
  15519. if (namedReexports.length > 0) {
  15520. importBlock.push(`export${_}{${_}${namedReexports
  15521. .map(specifier => specifier.imported === specifier.reexported
  15522. ? specifier.imported
  15523. : `${specifier.imported} as ${specifier.reexported}`)
  15524. .join(`,${_}`)}${_}}${_}from${_}${pathWithAssertion}`);
  15525. }
  15526. }
  15527. }
  15528. return importBlock;
  15529. }
  15530. function getExportBlock(exports, { _, cnst }) {
  15531. const exportBlock = [];
  15532. const exportDeclaration = [];
  15533. for (const specifier of exports) {
  15534. if (specifier.expression) {
  15535. exportBlock.push(`${cnst} ${specifier.local}${_}=${_}${specifier.expression};`);
  15536. }
  15537. exportDeclaration.push(specifier.exported === specifier.local
  15538. ? specifier.local
  15539. : `${specifier.local} as ${specifier.exported}`);
  15540. }
  15541. if (exportDeclaration.length > 0) {
  15542. exportBlock.push(`export${_}{${_}${exportDeclaration.join(`,${_}`)}${_}};`);
  15543. }
  15544. return exportBlock;
  15545. }
  15546. const keypath = (keypath, getPropertyAccess) => keypath.split('.').map(getPropertyAccess).join('');
  15547. function setupNamespace(name, root, globals, { _, getPropertyAccess, s }, compact) {
  15548. const parts = name.split('.');
  15549. parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
  15550. parts.pop();
  15551. let propertyPath = root;
  15552. return (parts
  15553. .map(part => {
  15554. propertyPath += getPropertyAccess(part);
  15555. return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}${s}`;
  15556. })
  15557. .join(compact ? ',' : '\n') + (compact && parts.length > 0 ? ';' : '\n'));
  15558. }
  15559. function assignToDeepVariable(deepName, root, globals, assignment, { _, getPropertyAccess }) {
  15560. const parts = deepName.split('.');
  15561. parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
  15562. const last = parts.pop();
  15563. let propertyPath = root;
  15564. let deepAssignment = [
  15565. ...parts.map(part => {
  15566. propertyPath += getPropertyAccess(part);
  15567. return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}`;
  15568. }),
  15569. `${propertyPath}${getPropertyAccess(last)}`
  15570. ].join(`,${_}`) + `${_}=${_}${assignment}`;
  15571. if (parts.length > 0) {
  15572. deepAssignment = `(${deepAssignment})`;
  15573. }
  15574. return deepAssignment;
  15575. }
  15576. function trimEmptyImports(dependencies) {
  15577. let index = dependencies.length;
  15578. while (index--) {
  15579. const { imports, reexports } = dependencies[index];
  15580. if (imports || reexports) {
  15581. return dependencies.slice(0, index + 1);
  15582. }
  15583. }
  15584. return [];
  15585. }
  15586. function iife(magicString, { accessedGlobals, dependencies, exports, hasDefaultExport, hasExports, indent: t, intro, namedExportsMode, log, outro, snippets }, { compact, esModule, extend, freeze, externalLiveBindings, globals, interop, name, namespaceToStringTag, strict }) {
  15587. const { _, getNonArrowFunctionIntro, getPropertyAccess, n } = snippets;
  15588. const isNamespaced = name && name.includes('.');
  15589. const useVariableAssignment = !extend && !isNamespaced;
  15590. if (name && useVariableAssignment && !isLegal(name)) {
  15591. return error(logIllegalIdentifierAsName(name));
  15592. }
  15593. warnOnBuiltins(log, dependencies);
  15594. const external = trimEmptyImports(dependencies);
  15595. const deps = external.map(dep => dep.globalName || 'null');
  15596. const parameters = external.map(m => m.name);
  15597. if (hasExports && !name) {
  15598. log(LOGLEVEL_WARN, logMissingNameOptionForIifeExport());
  15599. }
  15600. if (namedExportsMode && hasExports) {
  15601. if (extend) {
  15602. deps.unshift(`this${keypath(name, getPropertyAccess)}${_}=${_}this${keypath(name, getPropertyAccess)}${_}||${_}{}`);
  15603. parameters.unshift('exports');
  15604. }
  15605. else {
  15606. deps.unshift('{}');
  15607. parameters.unshift('exports');
  15608. }
  15609. }
  15610. const useStrict = strict ? `${t}'use strict';${n}` : '';
  15611. const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets);
  15612. magicString.prepend(`${intro}${interopBlock}`);
  15613. let wrapperIntro = `(${getNonArrowFunctionIntro(parameters, {
  15614. isAsync: false,
  15615. name: null
  15616. })}{${n}${useStrict}${n}`;
  15617. if (hasExports) {
  15618. if (name && !(extend && namedExportsMode)) {
  15619. wrapperIntro =
  15620. (useVariableAssignment ? `var ${name}` : `this${keypath(name, getPropertyAccess)}`) +
  15621. `${_}=${_}${wrapperIntro}`;
  15622. }
  15623. if (isNamespaced) {
  15624. wrapperIntro = setupNamespace(name, 'this', globals, snippets, compact) + wrapperIntro;
  15625. }
  15626. }
  15627. let wrapperOutro = `${n}${n}})(${deps.join(`,${_}`)});`;
  15628. if (hasExports && !extend && namedExportsMode) {
  15629. wrapperOutro = `${n}${n}${t}return exports;${wrapperOutro}`;
  15630. }
  15631. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings);
  15632. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule === true || (esModule === 'if-default-prop' && hasDefaultExport), namespaceToStringTag, snippets);
  15633. if (namespaceMarkers) {
  15634. namespaceMarkers = n + n + namespaceMarkers;
  15635. }
  15636. magicString
  15637. .append(`${exportBlock}${namespaceMarkers}${outro}`)
  15638. .indent(t)
  15639. .prepend(wrapperIntro)
  15640. .append(wrapperOutro);
  15641. }
  15642. function system(magicString, { accessedGlobals, dependencies, exports, hasExports, indent: t, intro, snippets, outro, usesTopLevelAwait }, { externalLiveBindings, freeze, name, namespaceToStringTag, strict, systemNullSetters }) {
  15643. const { _, getFunctionIntro, getNonArrowFunctionIntro, n, s } = snippets;
  15644. const { importBindings, setters, starExcludes } = analyzeDependencies(dependencies, exports, t, snippets);
  15645. const registeredName = name ? `'${name}',${_}` : '';
  15646. const wrapperParameters = accessedGlobals.has('module')
  15647. ? ['exports', 'module']
  15648. : hasExports
  15649. ? ['exports']
  15650. : [];
  15651. // factory function should be wrapped by parentheses to avoid lazy parsing,
  15652. // cf. https://v8.dev/blog/preparser#pife
  15653. let wrapperStart = `System.register(${registeredName}[` +
  15654. dependencies.map(({ importPath }) => `'${importPath}'`).join(`,${_}`) +
  15655. `],${_}(${getNonArrowFunctionIntro(wrapperParameters, {
  15656. isAsync: false,
  15657. name: null
  15658. })}{${n}${t}${strict ? "'use strict';" : ''}` +
  15659. getStarExcludesBlock(starExcludes, t, snippets) +
  15660. getImportBindingsBlock(importBindings, t, snippets) +
  15661. `${n}${t}return${_}{${setters.length > 0
  15662. ? `${n}${t}${t}setters:${_}[${setters
  15663. .map(setter => setter
  15664. ? `${getFunctionIntro(['module'], {
  15665. isAsync: false,
  15666. name: null
  15667. })}{${n}${t}${t}${t}${setter}${n}${t}${t}}`
  15668. : systemNullSetters
  15669. ? `null`
  15670. : `${getFunctionIntro([], { isAsync: false, name: null })}{}`)
  15671. .join(`,${_}`)}],`
  15672. : ''}${n}`;
  15673. wrapperStart += `${t}${t}execute:${_}(${getNonArrowFunctionIntro([], {
  15674. isAsync: usesTopLevelAwait,
  15675. name: null
  15676. })}{${n}${n}`;
  15677. const wrapperEnd = `${t}${t}})${n}${t}}${s}${n}}));`;
  15678. magicString
  15679. .prepend(intro +
  15680. getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, namespaceToStringTag) +
  15681. getHoistedExportsBlock(exports, t, snippets))
  15682. .append(`${outro}${n}${n}` +
  15683. getSyntheticExportsBlock(exports, t, snippets) +
  15684. getMissingExportsBlock(exports, t, snippets))
  15685. .indent(`${t}${t}${t}`)
  15686. .append(wrapperEnd)
  15687. .prepend(wrapperStart);
  15688. }
  15689. function analyzeDependencies(dependencies, exports, t, { _, cnst, getObject, getPropertyAccess, n }) {
  15690. const importBindings = [];
  15691. const setters = [];
  15692. let starExcludes = null;
  15693. for (const { imports, reexports } of dependencies) {
  15694. const setter = [];
  15695. if (imports) {
  15696. for (const specifier of imports) {
  15697. importBindings.push(specifier.local);
  15698. if (specifier.imported === '*') {
  15699. setter.push(`${specifier.local}${_}=${_}module;`);
  15700. }
  15701. else {
  15702. setter.push(`${specifier.local}${_}=${_}module${getPropertyAccess(specifier.imported)};`);
  15703. }
  15704. }
  15705. }
  15706. if (reexports) {
  15707. const reexportedNames = [];
  15708. let hasStarReexport = false;
  15709. for (const { imported, reexported } of reexports) {
  15710. if (reexported === '*') {
  15711. hasStarReexport = true;
  15712. }
  15713. else {
  15714. reexportedNames.push([
  15715. reexported,
  15716. imported === '*' ? 'module' : `module${getPropertyAccess(imported)}`
  15717. ]);
  15718. }
  15719. }
  15720. if (reexportedNames.length > 1 || hasStarReexport) {
  15721. const exportMapping = getObject(reexportedNames, { lineBreakIndent: null });
  15722. if (hasStarReexport) {
  15723. if (!starExcludes) {
  15724. starExcludes = getStarExcludes({ dependencies, exports });
  15725. }
  15726. setter.push(`${cnst} setter${_}=${_}${exportMapping};`, `for${_}(${cnst} name in module)${_}{`, `${t}if${_}(!_starExcludes[name])${_}setter[name]${_}=${_}module[name];`, '}', 'exports(setter);');
  15727. }
  15728. else {
  15729. setter.push(`exports(${exportMapping});`);
  15730. }
  15731. }
  15732. else {
  15733. const [key, value] = reexportedNames[0];
  15734. setter.push(`exports('${key}',${_}${value});`);
  15735. }
  15736. }
  15737. setters.push(setter.join(`${n}${t}${t}${t}`));
  15738. }
  15739. return { importBindings, setters, starExcludes };
  15740. }
  15741. const getStarExcludes = ({ dependencies, exports }) => {
  15742. const starExcludes = new Set(exports.map(expt => expt.exported));
  15743. starExcludes.add('default');
  15744. for (const { reexports } of dependencies) {
  15745. if (reexports) {
  15746. for (const reexport of reexports) {
  15747. if (reexport.reexported !== '*')
  15748. starExcludes.add(reexport.reexported);
  15749. }
  15750. }
  15751. }
  15752. return starExcludes;
  15753. };
  15754. const getStarExcludesBlock = (starExcludes, t, { _, cnst, getObject, n }) => starExcludes
  15755. ? `${n}${t}${cnst} _starExcludes${_}=${_}${getObject([...starExcludes].map(property => [property, '1']), { lineBreakIndent: { base: t, t } })};`
  15756. : '';
  15757. const getImportBindingsBlock = (importBindings, t, { _, n }) => (importBindings.length > 0 ? `${n}${t}var ${importBindings.join(`,${_}`)};` : '');
  15758. const getHoistedExportsBlock = (exports, t, snippets) => getExportsBlock(exports.filter(expt => expt.hoisted).map(expt => ({ name: expt.exported, value: expt.local })), t, snippets);
  15759. function getExportsBlock(exports, t, { _, n }) {
  15760. if (exports.length === 0) {
  15761. return '';
  15762. }
  15763. if (exports.length === 1) {
  15764. return `exports('${exports[0].name}',${_}${exports[0].value});${n}${n}`;
  15765. }
  15766. return (`exports({${n}` +
  15767. exports.map(({ name, value }) => `${t}${name}:${_}${value}`).join(`,${n}`) +
  15768. `${n}});${n}${n}`);
  15769. }
  15770. const getSyntheticExportsBlock = (exports, t, snippets) => getExportsBlock(exports
  15771. .filter(expt => expt.expression)
  15772. .map(expt => ({ name: expt.exported, value: expt.local })), t, snippets);
  15773. const getMissingExportsBlock = (exports, t, snippets) => getExportsBlock(exports
  15774. .filter(expt => expt.local === MISSING_EXPORT_SHIM_VARIABLE)
  15775. .map(expt => ({ name: expt.exported, value: MISSING_EXPORT_SHIM_VARIABLE })), t, snippets);
  15776. function globalProperty(name, globalVariable, getPropertyAccess) {
  15777. if (!name)
  15778. return 'null';
  15779. return `${globalVariable}${keypath(name, getPropertyAccess)}`;
  15780. }
  15781. function safeAccess(name, globalVariable, { _, getPropertyAccess }) {
  15782. let propertyPath = globalVariable;
  15783. return name
  15784. .split('.')
  15785. .map(part => (propertyPath += getPropertyAccess(part)))
  15786. .join(`${_}&&${_}`);
  15787. }
  15788. function umd(magicString, { accessedGlobals, dependencies, exports, hasDefaultExport, hasExports, id, indent: t, intro, namedExportsMode, log, outro, snippets }, { amd, compact, esModule, extend, externalLiveBindings, freeze, interop, name, namespaceToStringTag, globals, noConflict, strict }) {
  15789. const { _, cnst, getFunctionIntro, getNonArrowFunctionIntro, getPropertyAccess, n, s } = snippets;
  15790. const factoryVariable = compact ? 'f' : 'factory';
  15791. const globalVariable = compact ? 'g' : 'global';
  15792. if (hasExports && !name) {
  15793. return error(logMissingNameOptionForUmdExport());
  15794. }
  15795. warnOnBuiltins(log, dependencies);
  15796. const amdDeps = dependencies.map(m => `'${updateExtensionForRelativeAmdId(m.importPath, amd.forceJsExtensionForImports)}'`);
  15797. const cjsDeps = dependencies.map(m => `require('${m.importPath}')`);
  15798. const trimmedImports = trimEmptyImports(dependencies);
  15799. const globalDeps = trimmedImports.map(module => globalProperty(module.globalName, globalVariable, getPropertyAccess));
  15800. const factoryParameters = trimmedImports.map(m => m.name);
  15801. if (namedExportsMode && (hasExports || noConflict)) {
  15802. amdDeps.unshift(`'exports'`);
  15803. cjsDeps.unshift(`exports`);
  15804. globalDeps.unshift(assignToDeepVariable(name, globalVariable, globals, `${extend ? `${globalProperty(name, globalVariable, getPropertyAccess)}${_}||${_}` : ''}{}`, snippets));
  15805. factoryParameters.unshift('exports');
  15806. }
  15807. const completeAmdId = getCompleteAmdId(amd, id);
  15808. const amdParameters = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
  15809. (amdDeps.length > 0 ? `[${amdDeps.join(`,${_}`)}],${_}` : ``);
  15810. const define = amd.define;
  15811. const cjsExport = !namedExportsMode && hasExports ? `module.exports${_}=${_}` : ``;
  15812. const useStrict = strict ? `${_}'use strict';${n}` : ``;
  15813. let iifeExport;
  15814. if (noConflict) {
  15815. const noConflictExportsVariable = compact ? 'e' : 'exports';
  15816. let factory;
  15817. if (!namedExportsMode && hasExports) {
  15818. factory = `${cnst} ${noConflictExportsVariable}${_}=${_}${assignToDeepVariable(name, globalVariable, globals, `${factoryVariable}(${globalDeps.join(`,${_}`)})`, snippets)};`;
  15819. }
  15820. else {
  15821. const module = globalDeps.shift();
  15822. factory =
  15823. `${cnst} ${noConflictExportsVariable}${_}=${_}${module};${n}` +
  15824. `${t}${t}${factoryVariable}(${[noConflictExportsVariable, ...globalDeps].join(`,${_}`)});`;
  15825. }
  15826. iifeExport =
  15827. `(${getFunctionIntro([], { isAsync: false, name: null })}{${n}` +
  15828. `${t}${t}${cnst} current${_}=${_}${safeAccess(name, globalVariable, snippets)};${n}` +
  15829. `${t}${t}${factory}${n}` +
  15830. `${t}${t}${noConflictExportsVariable}.noConflict${_}=${_}${getFunctionIntro([], {
  15831. isAsync: false,
  15832. name: null
  15833. })}{${_}` +
  15834. `${globalProperty(name, globalVariable, getPropertyAccess)}${_}=${_}current;${_}return ${noConflictExportsVariable}${s}${_}};${n}` +
  15835. `${t}})()`;
  15836. }
  15837. else {
  15838. iifeExport = `${factoryVariable}(${globalDeps.join(`,${_}`)})`;
  15839. if (!namedExportsMode && hasExports) {
  15840. iifeExport = assignToDeepVariable(name, globalVariable, globals, iifeExport, snippets);
  15841. }
  15842. }
  15843. const iifeNeedsGlobal = hasExports || (noConflict && namedExportsMode) || globalDeps.length > 0;
  15844. const wrapperParameters = [factoryVariable];
  15845. if (iifeNeedsGlobal) {
  15846. wrapperParameters.unshift(globalVariable);
  15847. }
  15848. const globalArgument = iifeNeedsGlobal ? `this,${_}` : '';
  15849. const iifeStart = iifeNeedsGlobal
  15850. ? `(${globalVariable}${_}=${_}typeof globalThis${_}!==${_}'undefined'${_}?${_}globalThis${_}:${_}${globalVariable}${_}||${_}self,${_}`
  15851. : '';
  15852. const iifeEnd = iifeNeedsGlobal ? ')' : '';
  15853. const cjsIntro = iifeNeedsGlobal
  15854. ? `${t}typeof exports${_}===${_}'object'${_}&&${_}typeof module${_}!==${_}'undefined'${_}?` +
  15855. `${_}${cjsExport}${factoryVariable}(${cjsDeps.join(`,${_}`)})${_}:${n}`
  15856. : '';
  15857. const wrapperIntro = `(${getNonArrowFunctionIntro(wrapperParameters, { isAsync: false, name: null })}{${n}` +
  15858. cjsIntro +
  15859. `${t}typeof ${define}${_}===${_}'function'${_}&&${_}${define}.amd${_}?${_}${define}(${amdParameters}${factoryVariable})${_}:${n}` +
  15860. `${t}${iifeStart}${iifeExport}${iifeEnd};${n}` +
  15861. // factory function should be wrapped by parentheses to avoid lazy parsing,
  15862. // cf. https://v8.dev/blog/preparser#pife
  15863. `})(${globalArgument}(${getNonArrowFunctionIntro(factoryParameters, {
  15864. isAsync: false,
  15865. name: null
  15866. })}{${useStrict}${n}`;
  15867. const wrapperOutro = n + n + '}));';
  15868. magicString.prepend(`${intro}${getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets)}`);
  15869. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings);
  15870. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule === true || (esModule === 'if-default-prop' && hasDefaultExport), namespaceToStringTag, snippets);
  15871. if (namespaceMarkers) {
  15872. namespaceMarkers = n + n + namespaceMarkers;
  15873. }
  15874. magicString
  15875. .append(`${exportBlock}${namespaceMarkers}${outro}`)
  15876. .trim()
  15877. .indent(t)
  15878. .append(wrapperOutro)
  15879. .prepend(wrapperIntro);
  15880. }
  15881. const finalisers = { amd, cjs, es, iife, system, umd };
  15882. const concatSeparator = (out, next) => (next ? `${out}\n${next}` : out);
  15883. const concatDblSeparator = (out, next) => (next ? `${out}\n\n${next}` : out);
  15884. async function createAddons(options, outputPluginDriver, chunk) {
  15885. try {
  15886. let [banner, footer, intro, outro] = await Promise.all([
  15887. outputPluginDriver.hookReduceValue('banner', options.banner(chunk), [chunk], concatSeparator),
  15888. outputPluginDriver.hookReduceValue('footer', options.footer(chunk), [chunk], concatSeparator),
  15889. outputPluginDriver.hookReduceValue('intro', options.intro(chunk), [chunk], concatDblSeparator),
  15890. outputPluginDriver.hookReduceValue('outro', options.outro(chunk), [chunk], concatDblSeparator)
  15891. ]);
  15892. if (intro)
  15893. intro += '\n\n';
  15894. if (outro)
  15895. outro = `\n\n${outro}`;
  15896. if (banner)
  15897. banner += '\n';
  15898. if (footer)
  15899. footer = '\n' + footer;
  15900. return { banner, footer, intro, outro };
  15901. }
  15902. catch (error_) {
  15903. return error(logAddonNotGenerated(error_.message, error_.hook, error_.plugin));
  15904. }
  15905. }
  15906. const DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT = {
  15907. amd: deconflictImportsOther,
  15908. cjs: deconflictImportsOther,
  15909. es: deconflictImportsEsmOrSystem,
  15910. iife: deconflictImportsOther,
  15911. system: deconflictImportsEsmOrSystem,
  15912. umd: deconflictImportsOther
  15913. };
  15914. function deconflictChunk(modules, dependenciesToBeDeconflicted, imports, usedNames, format, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports, exportNamesByVariable, accessedGlobalsByScope, includedNamespaces) {
  15915. const reversedModules = [...modules].reverse();
  15916. for (const module of reversedModules) {
  15917. module.scope.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
  15918. }
  15919. deconflictTopLevelVariables(usedNames, reversedModules, includedNamespaces);
  15920. DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT[format](usedNames, imports, dependenciesToBeDeconflicted, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports);
  15921. for (const module of reversedModules) {
  15922. module.scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  15923. }
  15924. }
  15925. function deconflictImportsEsmOrSystem(usedNames, imports, dependenciesToBeDeconflicted, _interop, preserveModules, _externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports) {
  15926. // This is needed for namespace reexports
  15927. for (const dependency of dependenciesToBeDeconflicted.dependencies) {
  15928. if (preserveModules || dependency instanceof ExternalChunk) {
  15929. dependency.variableName = getSafeName(dependency.suggestedVariableName, usedNames, null);
  15930. }
  15931. }
  15932. for (const variable of imports) {
  15933. const module = variable.module;
  15934. const name = variable.name;
  15935. if (variable.isNamespace && (preserveModules || module instanceof ExternalModule)) {
  15936. variable.setRenderNames(null, (module instanceof ExternalModule
  15937. ? externalChunkByModule.get(module)
  15938. : chunkByModule.get(module)).variableName);
  15939. }
  15940. else if (module instanceof ExternalModule && name === 'default') {
  15941. variable.setRenderNames(null, getSafeName([...module.exportedVariables].some(([exportedVariable, exportedName]) => exportedName === '*' && exportedVariable.included)
  15942. ? module.suggestedVariableName + '__default'
  15943. : module.suggestedVariableName, usedNames, variable.forbiddenNames));
  15944. }
  15945. else {
  15946. variable.setRenderNames(null, getSafeName(name, usedNames, variable.forbiddenNames));
  15947. }
  15948. }
  15949. for (const variable of syntheticExports) {
  15950. variable.setRenderNames(null, getSafeName(variable.name, usedNames, variable.forbiddenNames));
  15951. }
  15952. }
  15953. function deconflictImportsOther(usedNames, imports, { deconflictedDefault, deconflictedNamespace, dependencies }, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule) {
  15954. for (const chunk of dependencies) {
  15955. chunk.variableName = getSafeName(chunk.suggestedVariableName, usedNames, null);
  15956. }
  15957. for (const chunk of deconflictedNamespace) {
  15958. chunk.namespaceVariableName = getSafeName(`${chunk.suggestedVariableName}__namespace`, usedNames, null);
  15959. }
  15960. for (const externalModule of deconflictedDefault) {
  15961. externalModule.defaultVariableName =
  15962. deconflictedNamespace.has(externalModule) &&
  15963. canDefaultBeTakenFromNamespace(interop(externalModule.id), externalLiveBindings)
  15964. ? externalModule.namespaceVariableName
  15965. : getSafeName(`${externalModule.suggestedVariableName}__default`, usedNames, null);
  15966. }
  15967. for (const variable of imports) {
  15968. const module = variable.module;
  15969. if (module instanceof ExternalModule) {
  15970. const chunk = externalChunkByModule.get(module);
  15971. const name = variable.name;
  15972. if (name === 'default') {
  15973. const moduleInterop = interop(module.id);
  15974. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  15975. ? chunk.defaultVariableName
  15976. : chunk.variableName;
  15977. if (isDefaultAProperty(moduleInterop, externalLiveBindings)) {
  15978. variable.setRenderNames(variableName, 'default');
  15979. }
  15980. else {
  15981. variable.setRenderNames(null, variableName);
  15982. }
  15983. }
  15984. else if (name === '*') {
  15985. variable.setRenderNames(null, namespaceInteropHelpersByInteropType[interop(module.id)]
  15986. ? chunk.namespaceVariableName
  15987. : chunk.variableName);
  15988. }
  15989. else {
  15990. // if the second parameter is `null`, it uses its "name" for the property name
  15991. variable.setRenderNames(chunk.variableName, null);
  15992. }
  15993. }
  15994. else {
  15995. const chunk = chunkByModule.get(module);
  15996. if (preserveModules && variable.isNamespace) {
  15997. variable.setRenderNames(null, chunk.exportMode === 'default' ? chunk.namespaceVariableName : chunk.variableName);
  15998. }
  15999. else if (chunk.exportMode === 'default') {
  16000. variable.setRenderNames(null, chunk.variableName);
  16001. }
  16002. else {
  16003. variable.setRenderNames(chunk.variableName, chunk.getVariableExportName(variable));
  16004. }
  16005. }
  16006. }
  16007. }
  16008. function deconflictTopLevelVariables(usedNames, modules, includedNamespaces) {
  16009. for (const module of modules) {
  16010. for (const variable of module.scope.variables.values()) {
  16011. if (variable.included &&
  16012. // this will only happen for exports in some formats
  16013. !(variable.renderBaseName ||
  16014. (variable instanceof ExportDefaultVariable && variable.getOriginalVariable() !== variable))) {
  16015. variable.setRenderNames(null, getSafeName(variable.name, usedNames, variable.forbiddenNames));
  16016. }
  16017. }
  16018. if (includedNamespaces.has(module)) {
  16019. const namespace = module.namespace;
  16020. namespace.setRenderNames(null, getSafeName(namespace.name, usedNames, namespace.forbiddenNames));
  16021. }
  16022. }
  16023. }
  16024. function assignExportsToMangledNames(exports, exportsByName, exportNamesByVariable) {
  16025. let nameIndex = 0;
  16026. for (const variable of exports) {
  16027. let [exportName] = variable.name;
  16028. if (exportsByName.has(exportName)) {
  16029. do {
  16030. exportName = toBase64(++nameIndex);
  16031. // skip past leading number identifiers
  16032. if (exportName.charCodeAt(0) === 49 /* '1' */) {
  16033. nameIndex += 9 * 64 ** (exportName.length - 1);
  16034. exportName = toBase64(nameIndex);
  16035. }
  16036. } while (RESERVED_NAMES$1.has(exportName) || exportsByName.has(exportName));
  16037. }
  16038. exportsByName.set(exportName, variable);
  16039. exportNamesByVariable.set(variable, [exportName]);
  16040. }
  16041. }
  16042. function assignExportsToNames(exports, exportsByName, exportNamesByVariable) {
  16043. for (const variable of exports) {
  16044. let nameIndex = 0;
  16045. let exportName = variable.name;
  16046. while (exportsByName.has(exportName)) {
  16047. exportName = variable.name + '$' + ++nameIndex;
  16048. }
  16049. exportsByName.set(exportName, variable);
  16050. exportNamesByVariable.set(variable, [exportName]);
  16051. }
  16052. }
  16053. function getExportMode(chunk, { exports: exportMode, name, format }, facadeModuleId, log) {
  16054. const exportKeys = chunk.getExportNames();
  16055. if (exportMode === 'default') {
  16056. if (exportKeys.length !== 1 || exportKeys[0] !== 'default') {
  16057. return error(logIncompatibleExportOptionValue('default', exportKeys, facadeModuleId));
  16058. }
  16059. }
  16060. else if (exportMode === 'none' && exportKeys.length > 0) {
  16061. return error(logIncompatibleExportOptionValue('none', exportKeys, facadeModuleId));
  16062. }
  16063. if (exportMode === 'auto') {
  16064. if (exportKeys.length === 0) {
  16065. exportMode = 'none';
  16066. }
  16067. else if (exportKeys.length === 1 && exportKeys[0] === 'default') {
  16068. exportMode = 'default';
  16069. }
  16070. else {
  16071. if (format !== 'es' && format !== 'system' && exportKeys.includes('default')) {
  16072. log(LOGLEVEL_WARN, logMixedExport(facadeModuleId, name));
  16073. }
  16074. exportMode = 'named';
  16075. }
  16076. }
  16077. return exportMode;
  16078. }
  16079. function guessIndentString(code) {
  16080. const lines = code.split('\n');
  16081. const tabbed = lines.filter(line => /^\t+/.test(line));
  16082. const spaced = lines.filter(line => /^ {2,}/.test(line));
  16083. if (tabbed.length === 0 && spaced.length === 0) {
  16084. return null;
  16085. }
  16086. // More lines tabbed than spaced? Assume tabs, and
  16087. // default to tabs in the case of a tie (or nothing
  16088. // to go on)
  16089. if (tabbed.length >= spaced.length) {
  16090. return '\t';
  16091. }
  16092. // Otherwise, we need to guess the multiple
  16093. const min = spaced.reduce((previous, current) => {
  16094. const numberSpaces = /^ +/.exec(current)[0].length;
  16095. return Math.min(numberSpaces, previous);
  16096. }, Infinity);
  16097. return ' '.repeat(min);
  16098. }
  16099. function getIndentString(modules, options) {
  16100. if (options.indent !== true)
  16101. return options.indent;
  16102. for (const module of modules) {
  16103. const indent = guessIndentString(module.originalCode);
  16104. if (indent !== null)
  16105. return indent;
  16106. }
  16107. return '\t';
  16108. }
  16109. function getStaticDependencies(chunk, orderedModules, chunkByModule, externalChunkByModule) {
  16110. const staticDependencyBlocks = [];
  16111. const handledDependencies = new Set();
  16112. for (let modulePos = orderedModules.length - 1; modulePos >= 0; modulePos--) {
  16113. const module = orderedModules[modulePos];
  16114. if (!handledDependencies.has(module)) {
  16115. const staticDependencies = [];
  16116. addStaticDependencies(module, staticDependencies, handledDependencies, chunk, chunkByModule, externalChunkByModule);
  16117. staticDependencyBlocks.unshift(staticDependencies);
  16118. }
  16119. }
  16120. const dependencies = new Set();
  16121. for (const block of staticDependencyBlocks) {
  16122. for (const dependency of block) {
  16123. dependencies.add(dependency);
  16124. }
  16125. }
  16126. return dependencies;
  16127. }
  16128. function addStaticDependencies(module, staticDependencies, handledModules, chunk, chunkByModule, externalChunkByModule) {
  16129. const dependencies = module.getDependenciesToBeIncluded();
  16130. for (const dependency of dependencies) {
  16131. if (dependency instanceof ExternalModule) {
  16132. staticDependencies.push(externalChunkByModule.get(dependency));
  16133. continue;
  16134. }
  16135. const dependencyChunk = chunkByModule.get(dependency);
  16136. if (dependencyChunk !== chunk) {
  16137. staticDependencies.push(dependencyChunk);
  16138. continue;
  16139. }
  16140. if (!handledModules.has(dependency)) {
  16141. handledModules.add(dependency);
  16142. addStaticDependencies(dependency, staticDependencies, handledModules, chunk, chunkByModule, externalChunkByModule);
  16143. }
  16144. }
  16145. }
  16146. const NON_ASSET_EXTENSIONS = new Set([
  16147. '.js',
  16148. '.jsx',
  16149. '.ts',
  16150. '.tsx',
  16151. '.mjs',
  16152. '.mts',
  16153. '.cjs',
  16154. '.cts'
  16155. ]);
  16156. function getGlobalName(chunk, globals, hasExports, log) {
  16157. const globalName = typeof globals === 'function' ? globals(chunk.id) : globals[chunk.id];
  16158. if (globalName) {
  16159. return globalName;
  16160. }
  16161. if (hasExports) {
  16162. log(LOGLEVEL_WARN, logMissingGlobalName(chunk.id, chunk.variableName));
  16163. return chunk.variableName;
  16164. }
  16165. }
  16166. class Chunk {
  16167. constructor(orderedModules, inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, manualChunkAlias, getPlaceholder, bundle, inputBase, snippets) {
  16168. this.orderedModules = orderedModules;
  16169. this.inputOptions = inputOptions;
  16170. this.outputOptions = outputOptions;
  16171. this.unsetOptions = unsetOptions;
  16172. this.pluginDriver = pluginDriver;
  16173. this.modulesById = modulesById;
  16174. this.chunkByModule = chunkByModule;
  16175. this.externalChunkByModule = externalChunkByModule;
  16176. this.facadeChunkByModule = facadeChunkByModule;
  16177. this.includedNamespaces = includedNamespaces;
  16178. this.manualChunkAlias = manualChunkAlias;
  16179. this.getPlaceholder = getPlaceholder;
  16180. this.bundle = bundle;
  16181. this.inputBase = inputBase;
  16182. this.snippets = snippets;
  16183. this.entryModules = [];
  16184. this.exportMode = 'named';
  16185. this.facadeModule = null;
  16186. this.namespaceVariableName = '';
  16187. this.variableName = '';
  16188. this.accessedGlobalsByScope = new Map();
  16189. this.dependencies = new Set();
  16190. this.dynamicEntryModules = [];
  16191. this.dynamicName = null;
  16192. this.exportNamesByVariable = new Map();
  16193. this.exports = new Set();
  16194. this.exportsByName = new Map();
  16195. this.fileName = null;
  16196. this.implicitEntryModules = [];
  16197. this.implicitlyLoadedBefore = new Set();
  16198. this.imports = new Set();
  16199. this.includedDynamicImports = null;
  16200. this.includedReexportsByModule = new Map();
  16201. // This may be updated in the constructor
  16202. this.isEmpty = true;
  16203. this.name = null;
  16204. this.needsExportsShim = false;
  16205. this.preRenderedChunkInfo = null;
  16206. this.preliminaryFileName = null;
  16207. this.preliminarySourcemapFileName = null;
  16208. this.renderedChunkInfo = null;
  16209. this.renderedDependencies = null;
  16210. this.renderedModules = Object.create(null);
  16211. this.sortedExportNames = null;
  16212. this.strictFacade = false;
  16213. this.execIndex = orderedModules.length > 0 ? orderedModules[0].execIndex : Infinity;
  16214. const chunkModules = new Set(orderedModules);
  16215. for (const module of orderedModules) {
  16216. chunkByModule.set(module, this);
  16217. if (module.namespace.included && !outputOptions.preserveModules) {
  16218. includedNamespaces.add(module);
  16219. }
  16220. if (this.isEmpty && module.isIncluded()) {
  16221. this.isEmpty = false;
  16222. }
  16223. if (module.info.isEntry || outputOptions.preserveModules) {
  16224. this.entryModules.push(module);
  16225. }
  16226. for (const importer of module.includedDynamicImporters) {
  16227. if (!chunkModules.has(importer)) {
  16228. this.dynamicEntryModules.push(module);
  16229. // Modules with synthetic exports need an artificial namespace for dynamic imports
  16230. if (module.info.syntheticNamedExports) {
  16231. includedNamespaces.add(module);
  16232. this.exports.add(module.namespace);
  16233. }
  16234. }
  16235. }
  16236. if (module.implicitlyLoadedAfter.size > 0) {
  16237. this.implicitEntryModules.push(module);
  16238. }
  16239. }
  16240. this.suggestedVariableName = makeLegal(this.generateVariableName());
  16241. }
  16242. static generateFacade(inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, facadedModule, facadeName, getPlaceholder, bundle, inputBase, snippets) {
  16243. const chunk = new Chunk([], inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, null, getPlaceholder, bundle, inputBase, snippets);
  16244. chunk.assignFacadeName(facadeName, facadedModule);
  16245. if (!facadeChunkByModule.has(facadedModule)) {
  16246. facadeChunkByModule.set(facadedModule, chunk);
  16247. }
  16248. for (const dependency of facadedModule.getDependenciesToBeIncluded()) {
  16249. chunk.dependencies.add(dependency instanceof Module
  16250. ? chunkByModule.get(dependency)
  16251. : externalChunkByModule.get(dependency));
  16252. }
  16253. if (!chunk.dependencies.has(chunkByModule.get(facadedModule)) &&
  16254. facadedModule.info.moduleSideEffects &&
  16255. facadedModule.hasEffects()) {
  16256. chunk.dependencies.add(chunkByModule.get(facadedModule));
  16257. }
  16258. chunk.ensureReexportsAreAvailableForModule(facadedModule);
  16259. chunk.facadeModule = facadedModule;
  16260. chunk.strictFacade = true;
  16261. return chunk;
  16262. }
  16263. canModuleBeFacade(module, exposedVariables) {
  16264. const moduleExportNamesByVariable = module.getExportNamesByVariable();
  16265. // All exports of this chunk need to be exposed by the candidate module
  16266. for (const exposedVariable of this.exports) {
  16267. if (!moduleExportNamesByVariable.has(exposedVariable)) {
  16268. return false;
  16269. }
  16270. }
  16271. // Additionally, we need to expose namespaces of dynamic entries that are not the facade module and exports from other entry modules
  16272. for (const exposedVariable of exposedVariables) {
  16273. if (!(exposedVariable.module === module ||
  16274. moduleExportNamesByVariable.has(exposedVariable) ||
  16275. (exposedVariable instanceof SyntheticNamedExportVariable &&
  16276. moduleExportNamesByVariable.has(exposedVariable.getBaseVariable())))) {
  16277. return false;
  16278. }
  16279. }
  16280. return true;
  16281. }
  16282. finalizeChunk(code, map, sourcemapFileName, hashesByPlaceholder) {
  16283. const renderedChunkInfo = this.getRenderedChunkInfo();
  16284. const finalize = (code) => replacePlaceholders(code, hashesByPlaceholder);
  16285. const preliminaryFileName = renderedChunkInfo.fileName;
  16286. const fileName = (this.fileName = finalize(preliminaryFileName));
  16287. return {
  16288. ...renderedChunkInfo,
  16289. code,
  16290. dynamicImports: renderedChunkInfo.dynamicImports.map(finalize),
  16291. fileName,
  16292. implicitlyLoadedBefore: renderedChunkInfo.implicitlyLoadedBefore.map(finalize),
  16293. importedBindings: Object.fromEntries(Object.entries(renderedChunkInfo.importedBindings).map(([fileName, bindings]) => [
  16294. finalize(fileName),
  16295. bindings
  16296. ])),
  16297. imports: renderedChunkInfo.imports.map(finalize),
  16298. map,
  16299. preliminaryFileName,
  16300. referencedFiles: renderedChunkInfo.referencedFiles.map(finalize),
  16301. sourcemapFileName
  16302. };
  16303. }
  16304. generateExports() {
  16305. this.sortedExportNames = null;
  16306. const remainingExports = new Set(this.exports);
  16307. if (this.facadeModule !== null &&
  16308. (this.facadeModule.preserveSignature !== false || this.strictFacade)) {
  16309. const exportNamesByVariable = this.facadeModule.getExportNamesByVariable();
  16310. for (const [variable, exportNames] of exportNamesByVariable) {
  16311. this.exportNamesByVariable.set(variable, [...exportNames]);
  16312. for (const exportName of exportNames) {
  16313. this.exportsByName.set(exportName, variable);
  16314. }
  16315. remainingExports.delete(variable);
  16316. }
  16317. }
  16318. if (this.outputOptions.minifyInternalExports) {
  16319. assignExportsToMangledNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  16320. }
  16321. else {
  16322. assignExportsToNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  16323. }
  16324. if (this.outputOptions.preserveModules || (this.facadeModule && this.facadeModule.info.isEntry))
  16325. this.exportMode = getExportMode(this, this.outputOptions, this.facadeModule.id, this.inputOptions.onLog);
  16326. }
  16327. generateFacades() {
  16328. const facades = [];
  16329. const entryModules = new Set([...this.entryModules, ...this.implicitEntryModules]);
  16330. const exposedVariables = new Set(this.dynamicEntryModules.map(({ namespace }) => namespace));
  16331. for (const module of entryModules) {
  16332. if (module.preserveSignature) {
  16333. for (const exportedVariable of module.getExportNamesByVariable().keys()) {
  16334. // We need to expose all entry exports from this chunk
  16335. if (this.chunkByModule.get(exportedVariable.module) === this) {
  16336. exposedVariables.add(exportedVariable);
  16337. }
  16338. }
  16339. }
  16340. }
  16341. for (const module of entryModules) {
  16342. // eslint-disable-next-line unicorn/prefer-spread
  16343. const requiredFacades = Array.from(new Set(module.chunkNames.filter(({ isUserDefined }) => isUserDefined).map(({ name }) => name)),
  16344. // mapping must run after Set 'name' dedupe
  16345. name => ({
  16346. name
  16347. }));
  16348. if (requiredFacades.length === 0 && module.isUserDefinedEntryPoint) {
  16349. requiredFacades.push({});
  16350. }
  16351. // eslint-disable-next-line unicorn/prefer-spread
  16352. requiredFacades.push(...Array.from(module.chunkFileNames, fileName => ({ fileName })));
  16353. if (requiredFacades.length === 0) {
  16354. requiredFacades.push({});
  16355. }
  16356. if (!this.facadeModule) {
  16357. const needsStrictFacade = !this.outputOptions.preserveModules &&
  16358. (module.preserveSignature === 'strict' ||
  16359. (module.preserveSignature === 'exports-only' &&
  16360. module.getExportNamesByVariable().size > 0));
  16361. if (!needsStrictFacade || this.canModuleBeFacade(module, exposedVariables)) {
  16362. this.facadeModule = module;
  16363. this.facadeChunkByModule.set(module, this);
  16364. if (module.preserveSignature) {
  16365. this.strictFacade = needsStrictFacade;
  16366. }
  16367. this.assignFacadeName(requiredFacades.shift(), module, this.outputOptions.preserveModules);
  16368. }
  16369. }
  16370. for (const facadeName of requiredFacades) {
  16371. facades.push(Chunk.generateFacade(this.inputOptions, this.outputOptions, this.unsetOptions, this.pluginDriver, this.modulesById, this.chunkByModule, this.externalChunkByModule, this.facadeChunkByModule, this.includedNamespaces, module, facadeName, this.getPlaceholder, this.bundle, this.inputBase, this.snippets));
  16372. }
  16373. }
  16374. for (const module of this.dynamicEntryModules) {
  16375. if (module.info.syntheticNamedExports)
  16376. continue;
  16377. if (!this.facadeModule && this.canModuleBeFacade(module, exposedVariables)) {
  16378. this.facadeModule = module;
  16379. this.facadeChunkByModule.set(module, this);
  16380. this.strictFacade = true;
  16381. this.dynamicName = getChunkNameFromModule(module);
  16382. }
  16383. else if (this.facadeModule === module &&
  16384. !this.strictFacade &&
  16385. this.canModuleBeFacade(module, exposedVariables)) {
  16386. this.strictFacade = true;
  16387. }
  16388. else if (!this.facadeChunkByModule.get(module)?.strictFacade) {
  16389. this.includedNamespaces.add(module);
  16390. this.exports.add(module.namespace);
  16391. }
  16392. }
  16393. if (!this.outputOptions.preserveModules) {
  16394. this.addNecessaryImportsForFacades();
  16395. }
  16396. return facades;
  16397. }
  16398. getChunkName() {
  16399. return (this.name ?? (this.name = this.outputOptions.sanitizeFileName(this.getFallbackChunkName())));
  16400. }
  16401. getExportNames() {
  16402. return (this.sortedExportNames ?? (this.sortedExportNames = [...this.exportsByName.keys()].sort()));
  16403. }
  16404. getFileName() {
  16405. return this.fileName || this.getPreliminaryFileName().fileName;
  16406. }
  16407. getImportPath(importer) {
  16408. return escapeId(getImportPath(importer, this.getFileName(), this.outputOptions.format === 'amd' && !this.outputOptions.amd.forceJsExtensionForImports, true));
  16409. }
  16410. getPreliminaryFileName() {
  16411. if (this.preliminaryFileName) {
  16412. return this.preliminaryFileName;
  16413. }
  16414. let fileName;
  16415. let hashPlaceholder = null;
  16416. const { chunkFileNames, entryFileNames, file, format, preserveModules } = this.outputOptions;
  16417. if (file) {
  16418. fileName = node_path.basename(file);
  16419. }
  16420. else if (this.fileName === null) {
  16421. const [pattern, patternName] = preserveModules || this.facadeModule?.isUserDefinedEntryPoint
  16422. ? [entryFileNames, 'output.entryFileNames']
  16423. : [chunkFileNames, 'output.chunkFileNames'];
  16424. fileName = renderNamePattern(typeof pattern === 'function' ? pattern(this.getPreRenderedChunkInfo()) : pattern, patternName, {
  16425. format: () => format,
  16426. hash: size => hashPlaceholder || (hashPlaceholder = this.getPlaceholder(patternName, size)),
  16427. name: () => this.getChunkName()
  16428. });
  16429. if (!hashPlaceholder) {
  16430. fileName = makeUnique(fileName, this.bundle);
  16431. }
  16432. }
  16433. else {
  16434. fileName = this.fileName;
  16435. }
  16436. if (!hashPlaceholder) {
  16437. this.bundle[fileName] = FILE_PLACEHOLDER;
  16438. }
  16439. // Caching is essential to not conflict with the file name reservation above
  16440. return (this.preliminaryFileName = { fileName, hashPlaceholder });
  16441. }
  16442. getPreliminarySourcemapFileName() {
  16443. if (this.preliminarySourcemapFileName) {
  16444. return this.preliminarySourcemapFileName;
  16445. }
  16446. let sourcemapFileName = null;
  16447. let hashPlaceholder = null;
  16448. const { sourcemapFileNames, format } = this.outputOptions;
  16449. if (sourcemapFileNames) {
  16450. const [pattern, patternName] = [sourcemapFileNames, 'output.sourcemapFileNames'];
  16451. sourcemapFileName = renderNamePattern(typeof pattern === 'function' ? pattern(this.getPreRenderedChunkInfo()) : pattern, patternName, {
  16452. chunkhash: () => this.getPreliminaryFileName().hashPlaceholder || '',
  16453. format: () => format,
  16454. hash: size => hashPlaceholder || (hashPlaceholder = this.getPlaceholder(patternName, size)),
  16455. name: () => this.getChunkName()
  16456. });
  16457. if (!hashPlaceholder) {
  16458. sourcemapFileName = makeUnique(sourcemapFileName, this.bundle);
  16459. }
  16460. }
  16461. else {
  16462. return null;
  16463. }
  16464. return (this.preliminarySourcemapFileName = { fileName: sourcemapFileName, hashPlaceholder });
  16465. }
  16466. getRenderedChunkInfo() {
  16467. if (this.renderedChunkInfo) {
  16468. return this.renderedChunkInfo;
  16469. }
  16470. return (this.renderedChunkInfo = {
  16471. ...this.getPreRenderedChunkInfo(),
  16472. dynamicImports: this.getDynamicDependencies().map(resolveFileName),
  16473. fileName: this.getFileName(),
  16474. // eslint-disable-next-line unicorn/prefer-spread
  16475. implicitlyLoadedBefore: Array.from(this.implicitlyLoadedBefore, resolveFileName),
  16476. importedBindings: getImportedBindingsPerDependency(this.getRenderedDependencies(), resolveFileName),
  16477. // eslint-disable-next-line unicorn/prefer-spread
  16478. imports: Array.from(this.dependencies, resolveFileName),
  16479. modules: this.renderedModules,
  16480. referencedFiles: this.getReferencedFiles()
  16481. });
  16482. }
  16483. getVariableExportName(variable) {
  16484. if (this.outputOptions.preserveModules && variable instanceof NamespaceVariable) {
  16485. return '*';
  16486. }
  16487. return this.exportNamesByVariable.get(variable)[0];
  16488. }
  16489. link() {
  16490. this.dependencies = getStaticDependencies(this, this.orderedModules, this.chunkByModule, this.externalChunkByModule);
  16491. for (const module of this.orderedModules) {
  16492. this.addImplicitlyLoadedBeforeFromModule(module);
  16493. this.setUpChunkImportsAndExportsForModule(module);
  16494. }
  16495. }
  16496. async render() {
  16497. const { dependencies, exportMode, facadeModule, inputOptions: { onLog }, outputOptions, pluginDriver, snippets } = this;
  16498. const { format, hoistTransitiveImports, preserveModules } = outputOptions;
  16499. // for static and dynamic entry points, add transitive dependencies to this
  16500. // chunk's dependencies to avoid loading latency
  16501. if (hoistTransitiveImports && !preserveModules && facadeModule !== null) {
  16502. for (const dep of dependencies) {
  16503. if (dep instanceof Chunk)
  16504. this.inlineChunkDependencies(dep);
  16505. }
  16506. }
  16507. const preliminaryFileName = this.getPreliminaryFileName();
  16508. const preliminarySourcemapFileName = this.getPreliminarySourcemapFileName();
  16509. const { accessedGlobals, indent, magicString, renderedSource, usedModules, usesTopLevelAwait } = this.renderModules(preliminaryFileName.fileName);
  16510. const renderedDependencies = [...this.getRenderedDependencies().values()];
  16511. const renderedExports = exportMode === 'none' ? [] : this.getChunkExportDeclarations(format);
  16512. let hasExports = renderedExports.length > 0;
  16513. let hasDefaultExport = false;
  16514. for (const renderedDependence of renderedDependencies) {
  16515. const { reexports } = renderedDependence;
  16516. if (reexports?.length) {
  16517. hasExports = true;
  16518. if (!hasDefaultExport && reexports.some(reexport => reexport.reexported === 'default')) {
  16519. hasDefaultExport = true;
  16520. }
  16521. if (format === 'es') {
  16522. renderedDependence.reexports = reexports.filter(
  16523. // eslint-disable-next-line unicorn/prefer-array-some
  16524. ({ reexported }) => !renderedExports.find(({ exported }) => exported === reexported));
  16525. }
  16526. }
  16527. }
  16528. if (!hasDefaultExport) {
  16529. for (const { exported } of renderedExports) {
  16530. if (exported === 'default') {
  16531. hasDefaultExport = true;
  16532. break;
  16533. }
  16534. }
  16535. }
  16536. const { intro, outro, banner, footer } = await createAddons(outputOptions, pluginDriver, this.getRenderedChunkInfo());
  16537. finalisers[format](renderedSource, {
  16538. accessedGlobals,
  16539. dependencies: renderedDependencies,
  16540. exports: renderedExports,
  16541. hasDefaultExport,
  16542. hasExports,
  16543. id: preliminaryFileName.fileName,
  16544. indent,
  16545. intro,
  16546. isEntryFacade: preserveModules || (facadeModule !== null && facadeModule.info.isEntry),
  16547. isModuleFacade: facadeModule !== null,
  16548. log: onLog,
  16549. namedExportsMode: exportMode !== 'default',
  16550. outro,
  16551. snippets,
  16552. usesTopLevelAwait
  16553. }, outputOptions);
  16554. if (banner)
  16555. magicString.prepend(banner);
  16556. if (footer)
  16557. magicString.append(footer);
  16558. return {
  16559. chunk: this,
  16560. magicString,
  16561. preliminaryFileName,
  16562. preliminarySourcemapFileName,
  16563. usedModules
  16564. };
  16565. }
  16566. addImplicitlyLoadedBeforeFromModule(baseModule) {
  16567. const { chunkByModule, implicitlyLoadedBefore } = this;
  16568. for (const module of baseModule.implicitlyLoadedBefore) {
  16569. const chunk = chunkByModule.get(module);
  16570. if (chunk && chunk !== this) {
  16571. implicitlyLoadedBefore.add(chunk);
  16572. }
  16573. }
  16574. }
  16575. addNecessaryImportsForFacades() {
  16576. for (const [module, variables] of this.includedReexportsByModule) {
  16577. if (this.includedNamespaces.has(module)) {
  16578. for (const variable of variables) {
  16579. this.imports.add(variable);
  16580. }
  16581. }
  16582. }
  16583. }
  16584. assignFacadeName({ fileName, name }, facadedModule, preservePath) {
  16585. if (fileName) {
  16586. this.fileName = fileName;
  16587. }
  16588. else {
  16589. this.name = this.outputOptions.sanitizeFileName(name ||
  16590. (preservePath
  16591. ? this.getPreserveModulesChunkNameFromModule(facadedModule)
  16592. : getChunkNameFromModule(facadedModule)));
  16593. }
  16594. }
  16595. checkCircularDependencyImport(variable, importingModule) {
  16596. const variableModule = variable.module;
  16597. if (variableModule instanceof Module) {
  16598. const exportChunk = this.chunkByModule.get(variableModule);
  16599. let alternativeReexportModule;
  16600. do {
  16601. alternativeReexportModule = importingModule.alternativeReexportModules.get(variable);
  16602. if (alternativeReexportModule) {
  16603. const exportingChunk = this.chunkByModule.get(alternativeReexportModule);
  16604. if (exportingChunk !== exportChunk) {
  16605. this.inputOptions.onLog(LOGLEVEL_WARN, logCyclicCrossChunkReexport(
  16606. // Namespaces do not have an export name
  16607. variableModule.getExportNamesByVariable().get(variable)?.[0] || '*', variableModule.id, alternativeReexportModule.id, importingModule.id, this.outputOptions.preserveModules));
  16608. }
  16609. importingModule = alternativeReexportModule;
  16610. }
  16611. } while (alternativeReexportModule);
  16612. }
  16613. }
  16614. ensureReexportsAreAvailableForModule(module) {
  16615. const includedReexports = [];
  16616. const map = module.getExportNamesByVariable();
  16617. for (const exportedVariable of map.keys()) {
  16618. const isSynthetic = exportedVariable instanceof SyntheticNamedExportVariable;
  16619. const importedVariable = isSynthetic ? exportedVariable.getBaseVariable() : exportedVariable;
  16620. this.checkCircularDependencyImport(importedVariable, module);
  16621. // When preserving modules, we do not create namespace objects but directly
  16622. // use the actual namespaces, which would be broken by this logic.
  16623. if (!(importedVariable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
  16624. const exportingModule = importedVariable.module;
  16625. if (exportingModule instanceof Module) {
  16626. const chunk = this.chunkByModule.get(exportingModule);
  16627. if (chunk && chunk !== this) {
  16628. chunk.exports.add(importedVariable);
  16629. includedReexports.push(importedVariable);
  16630. if (isSynthetic) {
  16631. this.imports.add(importedVariable);
  16632. }
  16633. }
  16634. }
  16635. }
  16636. }
  16637. if (includedReexports.length > 0) {
  16638. this.includedReexportsByModule.set(module, includedReexports);
  16639. }
  16640. }
  16641. generateVariableName() {
  16642. if (this.manualChunkAlias) {
  16643. return this.manualChunkAlias;
  16644. }
  16645. const moduleForNaming = this.entryModules[0] ||
  16646. this.implicitEntryModules[0] ||
  16647. this.dynamicEntryModules[0] ||
  16648. this.orderedModules[this.orderedModules.length - 1];
  16649. if (moduleForNaming) {
  16650. return getChunkNameFromModule(moduleForNaming);
  16651. }
  16652. return 'chunk';
  16653. }
  16654. getChunkExportDeclarations(format) {
  16655. const exports = [];
  16656. for (const exportName of this.getExportNames()) {
  16657. if (exportName[0] === '*')
  16658. continue;
  16659. const variable = this.exportsByName.get(exportName);
  16660. if (!(variable instanceof SyntheticNamedExportVariable)) {
  16661. const module = variable.module;
  16662. if (module) {
  16663. const chunk = this.chunkByModule.get(module);
  16664. if (chunk !== this) {
  16665. if (!chunk || format !== 'es') {
  16666. continue;
  16667. }
  16668. const chunkDep = this.renderedDependencies.get(chunk);
  16669. if (!chunkDep) {
  16670. continue;
  16671. }
  16672. const { imports, reexports } = chunkDep;
  16673. const importedByReexported = reexports?.find(({ reexported }) => reexported === exportName);
  16674. const isImported = imports?.find(({ imported }) => imported === importedByReexported?.imported);
  16675. if (!isImported) {
  16676. continue;
  16677. }
  16678. }
  16679. }
  16680. }
  16681. let expression = null;
  16682. let hoisted = false;
  16683. let local = variable.getName(this.snippets.getPropertyAccess);
  16684. if (variable instanceof LocalVariable) {
  16685. for (const declaration of variable.declarations) {
  16686. if (declaration.parent instanceof FunctionDeclaration ||
  16687. (declaration instanceof ExportDefaultDeclaration &&
  16688. declaration.declaration instanceof FunctionDeclaration)) {
  16689. hoisted = true;
  16690. break;
  16691. }
  16692. }
  16693. }
  16694. else if (variable instanceof SyntheticNamedExportVariable) {
  16695. expression = local;
  16696. if (format === 'es') {
  16697. local = variable.renderName;
  16698. }
  16699. }
  16700. exports.push({
  16701. exported: exportName,
  16702. expression,
  16703. hoisted,
  16704. local
  16705. });
  16706. }
  16707. return exports;
  16708. }
  16709. getDependenciesToBeDeconflicted(addNonNamespacesAndInteropHelpers, addDependenciesWithoutBindings, interop) {
  16710. const dependencies = new Set();
  16711. const deconflictedDefault = new Set();
  16712. const deconflictedNamespace = new Set();
  16713. for (const variable of [...this.exportNamesByVariable.keys(), ...this.imports]) {
  16714. if (addNonNamespacesAndInteropHelpers || variable.isNamespace) {
  16715. const module = variable.module;
  16716. if (module instanceof ExternalModule) {
  16717. const chunk = this.externalChunkByModule.get(module);
  16718. dependencies.add(chunk);
  16719. if (addNonNamespacesAndInteropHelpers) {
  16720. if (variable.name === 'default') {
  16721. if (defaultInteropHelpersByInteropType[interop(module.id)]) {
  16722. deconflictedDefault.add(chunk);
  16723. }
  16724. }
  16725. else if (variable.name === '*' &&
  16726. namespaceInteropHelpersByInteropType[interop(module.id)]) {
  16727. deconflictedNamespace.add(chunk);
  16728. }
  16729. }
  16730. }
  16731. else {
  16732. const chunk = this.chunkByModule.get(module);
  16733. if (chunk !== this) {
  16734. dependencies.add(chunk);
  16735. if (addNonNamespacesAndInteropHelpers &&
  16736. chunk.exportMode === 'default' &&
  16737. variable.isNamespace) {
  16738. deconflictedNamespace.add(chunk);
  16739. }
  16740. }
  16741. }
  16742. }
  16743. }
  16744. if (addDependenciesWithoutBindings) {
  16745. for (const dependency of this.dependencies) {
  16746. dependencies.add(dependency);
  16747. }
  16748. }
  16749. return { deconflictedDefault, deconflictedNamespace, dependencies };
  16750. }
  16751. getDynamicDependencies() {
  16752. return this.getIncludedDynamicImports()
  16753. .map(resolvedDynamicImport => resolvedDynamicImport.facadeChunk ||
  16754. resolvedDynamicImport.chunk ||
  16755. resolvedDynamicImport.externalChunk ||
  16756. resolvedDynamicImport.resolution)
  16757. .filter((resolution) => resolution !== this &&
  16758. (resolution instanceof Chunk || resolution instanceof ExternalChunk));
  16759. }
  16760. getDynamicImportStringAndAssertions(resolution, fileName) {
  16761. if (resolution instanceof ExternalModule) {
  16762. const chunk = this.externalChunkByModule.get(resolution);
  16763. return [`'${chunk.getImportPath(fileName)}'`, chunk.getImportAssertions(this.snippets)];
  16764. }
  16765. return [
  16766. resolution || '',
  16767. (this.outputOptions.format === 'es' && this.outputOptions.externalImportAssertions) || null
  16768. ];
  16769. }
  16770. getFallbackChunkName() {
  16771. if (this.manualChunkAlias) {
  16772. return this.manualChunkAlias;
  16773. }
  16774. if (this.dynamicName) {
  16775. return this.dynamicName;
  16776. }
  16777. if (this.fileName) {
  16778. return getAliasName(this.fileName);
  16779. }
  16780. return getAliasName(this.orderedModules[this.orderedModules.length - 1].id);
  16781. }
  16782. getImportSpecifiers() {
  16783. const { interop } = this.outputOptions;
  16784. const importsByDependency = new Map();
  16785. for (const variable of this.imports) {
  16786. const module = variable.module;
  16787. let dependency;
  16788. let imported;
  16789. if (module instanceof ExternalModule) {
  16790. dependency = this.externalChunkByModule.get(module);
  16791. imported = variable.name;
  16792. if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
  16793. return error(logUnexpectedNamedImport(module.id, imported, false));
  16794. }
  16795. }
  16796. else {
  16797. dependency = this.chunkByModule.get(module);
  16798. imported = dependency.getVariableExportName(variable);
  16799. }
  16800. getOrCreate(importsByDependency, dependency, getNewArray).push({
  16801. imported,
  16802. local: variable.getName(this.snippets.getPropertyAccess)
  16803. });
  16804. }
  16805. return importsByDependency;
  16806. }
  16807. getIncludedDynamicImports() {
  16808. if (this.includedDynamicImports) {
  16809. return this.includedDynamicImports;
  16810. }
  16811. const includedDynamicImports = [];
  16812. for (const module of this.orderedModules) {
  16813. for (const { node, resolution } of module.dynamicImports) {
  16814. if (!node.included) {
  16815. continue;
  16816. }
  16817. includedDynamicImports.push(resolution instanceof Module
  16818. ? {
  16819. chunk: this.chunkByModule.get(resolution),
  16820. externalChunk: null,
  16821. facadeChunk: this.facadeChunkByModule.get(resolution),
  16822. node,
  16823. resolution
  16824. }
  16825. : resolution instanceof ExternalModule
  16826. ? {
  16827. chunk: null,
  16828. externalChunk: this.externalChunkByModule.get(resolution),
  16829. facadeChunk: null,
  16830. node,
  16831. resolution
  16832. }
  16833. : { chunk: null, externalChunk: null, facadeChunk: null, node, resolution });
  16834. }
  16835. }
  16836. return (this.includedDynamicImports = includedDynamicImports);
  16837. }
  16838. getPreRenderedChunkInfo() {
  16839. if (this.preRenderedChunkInfo) {
  16840. return this.preRenderedChunkInfo;
  16841. }
  16842. const { dynamicEntryModules, facadeModule, implicitEntryModules, orderedModules } = this;
  16843. return (this.preRenderedChunkInfo = {
  16844. exports: this.getExportNames(),
  16845. facadeModuleId: facadeModule && facadeModule.id,
  16846. isDynamicEntry: dynamicEntryModules.length > 0,
  16847. isEntry: !!facadeModule?.info.isEntry,
  16848. isImplicitEntry: implicitEntryModules.length > 0,
  16849. moduleIds: orderedModules.map(({ id }) => id),
  16850. name: this.getChunkName(),
  16851. type: 'chunk'
  16852. });
  16853. }
  16854. getPreserveModulesChunkNameFromModule(module) {
  16855. const predefinedChunkName = getPredefinedChunkNameFromModule(module);
  16856. if (predefinedChunkName)
  16857. return predefinedChunkName;
  16858. const { preserveModulesRoot, sanitizeFileName } = this.outputOptions;
  16859. const sanitizedId = sanitizeFileName(normalize(module.id.split(QUERY_HASH_REGEX, 1)[0]));
  16860. const extensionName = node_path.extname(sanitizedId);
  16861. const idWithoutExtension = NON_ASSET_EXTENSIONS.has(extensionName)
  16862. ? sanitizedId.slice(0, -extensionName.length)
  16863. : sanitizedId;
  16864. if (isAbsolute(idWithoutExtension)) {
  16865. return preserveModulesRoot && node_path.resolve(idWithoutExtension).startsWith(preserveModulesRoot)
  16866. ? idWithoutExtension.slice(preserveModulesRoot.length).replace(/^[/\\]/, '')
  16867. : relative(this.inputBase, idWithoutExtension);
  16868. }
  16869. else {
  16870. return `_virtual/${node_path.basename(idWithoutExtension)}`;
  16871. }
  16872. }
  16873. getReexportSpecifiers() {
  16874. const { externalLiveBindings, interop } = this.outputOptions;
  16875. const reexportSpecifiers = new Map();
  16876. for (let exportName of this.getExportNames()) {
  16877. let dependency;
  16878. let imported;
  16879. let needsLiveBinding = false;
  16880. if (exportName[0] === '*') {
  16881. const id = exportName.slice(1);
  16882. if (interop(id) === 'defaultOnly') {
  16883. this.inputOptions.onLog(LOGLEVEL_WARN, logUnexpectedNamespaceReexport(id));
  16884. }
  16885. needsLiveBinding = externalLiveBindings;
  16886. dependency = this.externalChunkByModule.get(this.modulesById.get(id));
  16887. imported = exportName = '*';
  16888. }
  16889. else {
  16890. const variable = this.exportsByName.get(exportName);
  16891. if (variable instanceof SyntheticNamedExportVariable)
  16892. continue;
  16893. const module = variable.module;
  16894. if (module instanceof Module) {
  16895. dependency = this.chunkByModule.get(module);
  16896. if (dependency === this)
  16897. continue;
  16898. imported = dependency.getVariableExportName(variable);
  16899. needsLiveBinding = variable.isReassigned;
  16900. }
  16901. else {
  16902. dependency = this.externalChunkByModule.get(module);
  16903. imported = variable.name;
  16904. if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
  16905. return error(logUnexpectedNamedImport(module.id, imported, true));
  16906. }
  16907. needsLiveBinding =
  16908. externalLiveBindings &&
  16909. (imported !== 'default' || isDefaultAProperty(interop(module.id), true));
  16910. }
  16911. }
  16912. getOrCreate(reexportSpecifiers, dependency, getNewArray).push({
  16913. imported,
  16914. needsLiveBinding,
  16915. reexported: exportName
  16916. });
  16917. }
  16918. return reexportSpecifiers;
  16919. }
  16920. getReferencedFiles() {
  16921. const referencedFiles = new Set();
  16922. for (const module of this.orderedModules) {
  16923. for (const meta of module.importMetas) {
  16924. const fileName = meta.getReferencedFileName(this.pluginDriver);
  16925. if (fileName) {
  16926. referencedFiles.add(fileName);
  16927. }
  16928. }
  16929. }
  16930. return [...referencedFiles];
  16931. }
  16932. getRenderedDependencies() {
  16933. if (this.renderedDependencies) {
  16934. return this.renderedDependencies;
  16935. }
  16936. const importSpecifiers = this.getImportSpecifiers();
  16937. const reexportSpecifiers = this.getReexportSpecifiers();
  16938. const renderedDependencies = new Map();
  16939. const fileName = this.getFileName();
  16940. for (const dep of this.dependencies) {
  16941. const imports = importSpecifiers.get(dep) || null;
  16942. const reexports = reexportSpecifiers.get(dep) || null;
  16943. const namedExportsMode = dep instanceof ExternalChunk || dep.exportMode !== 'default';
  16944. const importPath = dep.getImportPath(fileName);
  16945. renderedDependencies.set(dep, {
  16946. assertions: dep instanceof ExternalChunk ? dep.getImportAssertions(this.snippets) : null,
  16947. defaultVariableName: dep.defaultVariableName,
  16948. globalName: dep instanceof ExternalChunk &&
  16949. (this.outputOptions.format === 'umd' || this.outputOptions.format === 'iife') &&
  16950. getGlobalName(dep, this.outputOptions.globals, (imports || reexports) !== null, this.inputOptions.onLog),
  16951. importPath,
  16952. imports,
  16953. isChunk: dep instanceof Chunk,
  16954. name: dep.variableName,
  16955. namedExportsMode,
  16956. namespaceVariableName: dep.namespaceVariableName,
  16957. reexports
  16958. });
  16959. }
  16960. return (this.renderedDependencies = renderedDependencies);
  16961. }
  16962. inlineChunkDependencies(chunk) {
  16963. for (const dep of chunk.dependencies) {
  16964. if (this.dependencies.has(dep))
  16965. continue;
  16966. this.dependencies.add(dep);
  16967. if (dep instanceof Chunk) {
  16968. this.inlineChunkDependencies(dep);
  16969. }
  16970. }
  16971. }
  16972. // This method changes properties on the AST before rendering and must not be async
  16973. renderModules(fileName) {
  16974. const { accessedGlobalsByScope, dependencies, exportNamesByVariable, includedNamespaces, inputOptions: { onLog }, isEmpty, orderedModules, outputOptions, pluginDriver, renderedModules, snippets } = this;
  16975. const { compact, dynamicImportFunction, format, freeze, namespaceToStringTag } = outputOptions;
  16976. const { _, cnst, n } = snippets;
  16977. this.setDynamicImportResolutions(fileName);
  16978. this.setImportMetaResolutions(fileName);
  16979. this.setIdentifierRenderResolutions();
  16980. const magicString = new Bundle$1({ separator: `${n}${n}` });
  16981. const indent = getIndentString(orderedModules, outputOptions);
  16982. const usedModules = [];
  16983. let hoistedSource = '';
  16984. const accessedGlobals = new Set();
  16985. const renderedModuleSources = new Map();
  16986. const renderOptions = {
  16987. accessedDocumentCurrentScript: false,
  16988. dynamicImportFunction,
  16989. exportNamesByVariable,
  16990. format,
  16991. freeze,
  16992. indent,
  16993. namespaceToStringTag,
  16994. pluginDriver,
  16995. snippets,
  16996. useOriginalName: null
  16997. };
  16998. let usesTopLevelAwait = false;
  16999. for (const module of orderedModules) {
  17000. let renderedLength = 0;
  17001. let source;
  17002. if (module.isIncluded() || includedNamespaces.has(module)) {
  17003. const rendered = module.render(renderOptions);
  17004. if (!renderOptions.accessedDocumentCurrentScript &&
  17005. formatsMaybeAccessDocumentCurrentScript.includes(format)) {
  17006. // eslint-disable-next-line unicorn/consistent-destructuring
  17007. this.accessedGlobalsByScope.get(module.scope)?.delete(DOCUMENT_CURRENT_SCRIPT);
  17008. }
  17009. renderOptions.accessedDocumentCurrentScript = false;
  17010. ({ source } = rendered);
  17011. usesTopLevelAwait || (usesTopLevelAwait = rendered.usesTopLevelAwait);
  17012. renderedLength = source.length();
  17013. if (renderedLength) {
  17014. if (compact && source.lastLine().includes('//'))
  17015. source.append('\n');
  17016. renderedModuleSources.set(module, source);
  17017. magicString.addSource(source);
  17018. usedModules.push(module);
  17019. }
  17020. const namespace = module.namespace;
  17021. if (includedNamespaces.has(module)) {
  17022. const rendered = namespace.renderBlock(renderOptions);
  17023. if (namespace.renderFirst())
  17024. hoistedSource += n + rendered;
  17025. else
  17026. magicString.addSource(new MagicString(rendered));
  17027. }
  17028. const accessedGlobalVariables = accessedGlobalsByScope.get(module.scope);
  17029. if (accessedGlobalVariables) {
  17030. for (const name of accessedGlobalVariables) {
  17031. accessedGlobals.add(name);
  17032. }
  17033. }
  17034. }
  17035. const { renderedExports, removedExports } = module.getRenderedExports();
  17036. renderedModules[module.id] = {
  17037. get code() {
  17038. return source?.toString() ?? null;
  17039. },
  17040. originalLength: module.originalCode.length,
  17041. removedExports,
  17042. renderedExports,
  17043. renderedLength
  17044. };
  17045. }
  17046. if (hoistedSource)
  17047. magicString.prepend(hoistedSource + n + n);
  17048. // eslint-disable-next-line unicorn/consistent-destructuring
  17049. if (this.needsExportsShim) {
  17050. magicString.prepend(`${n}${cnst} ${MISSING_EXPORT_SHIM_VARIABLE}${_}=${_}void 0;${n}${n}`);
  17051. }
  17052. const renderedSource = compact ? magicString : magicString.trim();
  17053. if (isEmpty && this.getExportNames().length === 0 && dependencies.size === 0) {
  17054. onLog(LOGLEVEL_WARN, logEmptyChunk(this.getChunkName()));
  17055. }
  17056. return { accessedGlobals, indent, magicString, renderedSource, usedModules, usesTopLevelAwait };
  17057. }
  17058. setDynamicImportResolutions(fileName) {
  17059. const { accessedGlobalsByScope, outputOptions, pluginDriver, snippets } = this;
  17060. for (const resolvedDynamicImport of this.getIncludedDynamicImports()) {
  17061. if (resolvedDynamicImport.chunk) {
  17062. const { chunk, facadeChunk, node, resolution } = resolvedDynamicImport;
  17063. if (chunk === this) {
  17064. node.setInternalResolution(resolution.namespace);
  17065. }
  17066. else {
  17067. node.setExternalResolution((facadeChunk || chunk).exportMode, resolution, outputOptions, snippets, pluginDriver, accessedGlobalsByScope, `'${(facadeChunk || chunk).getImportPath(fileName)}'`, !facadeChunk?.strictFacade && chunk.exportNamesByVariable.get(resolution.namespace)[0], null);
  17068. }
  17069. }
  17070. else {
  17071. const { node, resolution } = resolvedDynamicImport;
  17072. const [resolutionString, assertions] = this.getDynamicImportStringAndAssertions(resolution, fileName);
  17073. node.setExternalResolution('external', resolution, outputOptions, snippets, pluginDriver, accessedGlobalsByScope, resolutionString, false, assertions);
  17074. }
  17075. }
  17076. }
  17077. setIdentifierRenderResolutions() {
  17078. const { format, interop, namespaceToStringTag, preserveModules, externalLiveBindings } = this.outputOptions;
  17079. const syntheticExports = new Set();
  17080. for (const exportName of this.getExportNames()) {
  17081. const exportVariable = this.exportsByName.get(exportName);
  17082. if (format !== 'es' &&
  17083. format !== 'system' &&
  17084. exportVariable.isReassigned &&
  17085. !exportVariable.isId) {
  17086. exportVariable.setRenderNames('exports', exportName);
  17087. }
  17088. else if (exportVariable instanceof SyntheticNamedExportVariable) {
  17089. syntheticExports.add(exportVariable);
  17090. }
  17091. else {
  17092. exportVariable.setRenderNames(null, null);
  17093. }
  17094. }
  17095. for (const module of this.orderedModules) {
  17096. if (module.needsExportShim) {
  17097. this.needsExportsShim = true;
  17098. break;
  17099. }
  17100. }
  17101. const usedNames = new Set(['Object', 'Promise']);
  17102. if (this.needsExportsShim) {
  17103. usedNames.add(MISSING_EXPORT_SHIM_VARIABLE);
  17104. }
  17105. if (namespaceToStringTag) {
  17106. usedNames.add('Symbol');
  17107. }
  17108. switch (format) {
  17109. case 'system': {
  17110. usedNames.add('module').add('exports');
  17111. break;
  17112. }
  17113. case 'es': {
  17114. break;
  17115. }
  17116. case 'cjs': {
  17117. usedNames.add('module').add('require').add('__filename').add('__dirname');
  17118. }
  17119. // fallthrough
  17120. default: {
  17121. usedNames.add('exports');
  17122. for (const helper of HELPER_NAMES) {
  17123. usedNames.add(helper);
  17124. }
  17125. }
  17126. }
  17127. deconflictChunk(this.orderedModules, this.getDependenciesToBeDeconflicted(format !== 'es' && format !== 'system', format === 'amd' || format === 'umd' || format === 'iife', interop), this.imports, usedNames, format, interop, preserveModules, externalLiveBindings, this.chunkByModule, this.externalChunkByModule, syntheticExports, this.exportNamesByVariable, this.accessedGlobalsByScope, this.includedNamespaces);
  17128. }
  17129. setImportMetaResolutions(fileName) {
  17130. const { accessedGlobalsByScope, includedNamespaces, orderedModules, outputOptions: { format } } = this;
  17131. for (const module of orderedModules) {
  17132. for (const importMeta of module.importMetas) {
  17133. importMeta.setResolution(format, accessedGlobalsByScope, fileName);
  17134. }
  17135. if (includedNamespaces.has(module)) {
  17136. module.namespace.prepare(accessedGlobalsByScope);
  17137. }
  17138. }
  17139. }
  17140. setUpChunkImportsAndExportsForModule(module) {
  17141. const moduleImports = new Set(module.includedImports);
  17142. // when we are not preserving modules, we need to make all namespace variables available for
  17143. // rendering the namespace object
  17144. if (!this.outputOptions.preserveModules && this.includedNamespaces.has(module)) {
  17145. const memberVariables = module.namespace.getMemberVariables();
  17146. for (const variable of Object.values(memberVariables)) {
  17147. if (variable.included) {
  17148. moduleImports.add(variable);
  17149. }
  17150. }
  17151. }
  17152. for (let variable of moduleImports) {
  17153. if (variable instanceof ExportDefaultVariable) {
  17154. variable = variable.getOriginalVariable();
  17155. }
  17156. if (variable instanceof SyntheticNamedExportVariable) {
  17157. variable = variable.getBaseVariable();
  17158. }
  17159. const chunk = this.chunkByModule.get(variable.module);
  17160. if (chunk !== this) {
  17161. this.imports.add(variable);
  17162. if (variable.module instanceof Module) {
  17163. this.checkCircularDependencyImport(variable, module);
  17164. // When preserving modules, we do not create namespace objects but directly
  17165. // use the actual namespaces, which would be broken by this logic.
  17166. if (!(variable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
  17167. chunk.exports.add(variable);
  17168. }
  17169. }
  17170. }
  17171. }
  17172. if (this.includedNamespaces.has(module) ||
  17173. (module.info.isEntry && module.preserveSignature !== false) ||
  17174. module.includedDynamicImporters.some(importer => this.chunkByModule.get(importer) !== this)) {
  17175. this.ensureReexportsAreAvailableForModule(module);
  17176. }
  17177. for (const { node, resolution } of module.dynamicImports) {
  17178. if (node.included &&
  17179. resolution instanceof Module &&
  17180. this.chunkByModule.get(resolution) === this &&
  17181. !this.includedNamespaces.has(resolution)) {
  17182. this.includedNamespaces.add(resolution);
  17183. this.ensureReexportsAreAvailableForModule(resolution);
  17184. }
  17185. }
  17186. }
  17187. }
  17188. function getChunkNameFromModule(module) {
  17189. return getPredefinedChunkNameFromModule(module) ?? getAliasName(module.id);
  17190. }
  17191. function getPredefinedChunkNameFromModule(module) {
  17192. return (module.chunkNames.find(({ isUserDefined }) => isUserDefined)?.name ?? module.chunkNames[0]?.name);
  17193. }
  17194. function getImportedBindingsPerDependency(renderedDependencies, resolveFileName) {
  17195. const importedBindingsPerDependency = {};
  17196. for (const [dependency, declaration] of renderedDependencies) {
  17197. const specifiers = new Set();
  17198. if (declaration.imports) {
  17199. for (const { imported } of declaration.imports) {
  17200. specifiers.add(imported);
  17201. }
  17202. }
  17203. if (declaration.reexports) {
  17204. for (const { imported } of declaration.reexports) {
  17205. specifiers.add(imported);
  17206. }
  17207. }
  17208. importedBindingsPerDependency[resolveFileName(dependency)] = [...specifiers];
  17209. }
  17210. return importedBindingsPerDependency;
  17211. }
  17212. const QUERY_HASH_REGEX = /[#?]/;
  17213. const resolveFileName = (dependency) => dependency.getFileName();
  17214. /**
  17215. * Concatenate a number of iterables to a new iterable without fully evaluating
  17216. * their iterators. Useful when e.g. working with large sets or lists and when
  17217. * there is a chance that the iterators will not be fully exhausted.
  17218. */
  17219. function* concatLazy(iterables) {
  17220. for (const iterable of iterables) {
  17221. yield* iterable;
  17222. }
  17223. }
  17224. /**
  17225. * At its core, the algorithm first starts from each static or dynamic entry
  17226. * point and then assigns that entry point to all modules than can be reached
  17227. * via static imports. We call this the *dependent entry points* of that
  17228. * module.
  17229. *
  17230. * Then we group all modules with the same dependent entry points into chunks
  17231. * as those modules will always be loaded together.
  17232. *
  17233. * One non-trivial optimization we can apply is that dynamic entries are
  17234. * different from static entries in so far as when a dynamic import occurs,
  17235. * some
  17236. * modules are already in memory. If some of these modules are also
  17237. * dependencies
  17238. * of the dynamic entry, then it does not make sense to create a separate chunk
  17239. * for them. Instead, the dynamic import target can load them from the
  17240. * importing
  17241. * chunk.
  17242. *
  17243. * With regard to chunking, if B is implicitly loaded after A, then this can be
  17244. * handled the same way as if there was a dynamic import A => B.
  17245. *
  17246. * Example:
  17247. * Assume A -> B (A imports B), A => C (A dynamically imports C) and C -> B.
  17248. * Then the initial algorithm would assign A into the A chunk, C into the C
  17249. * chunk and B into the AC chunk, i.e. the chunk with the dependent entry
  17250. * points
  17251. * A and C.
  17252. * However we know that C can only be loaded from A, so A and its dependency B
  17253. * must already be in memory when C is loaded. So it is enough to create only
  17254. * two chunks A containing [AB] and C containing [C].
  17255. *
  17256. * So we do not assign the dynamic entry C as dependent entry point to modules
  17257. * that are already loaded.
  17258. *
  17259. * In a more complex example, let us assume that we have entry points X and Y.
  17260. * Further, let us assume
  17261. * X -> A, X -> B, X -> C,
  17262. * Y -> A, Y -> B,
  17263. * A => D,
  17264. * D -> B, D -> C
  17265. * So without dynamic import optimization, the dependent entry points are
  17266. * A: XY, B: DXY, C: DX, D: D, X: X, Y: Y,
  17267. * so we would for now create six chunks.
  17268. *
  17269. * Now D is loaded only after A is loaded. But A is loaded if either X is
  17270. * loaded
  17271. * or Y is loaded. So the modules that are already in memory when D is loaded
  17272. * are the intersection of all modules that X depends on with all modules that
  17273. * Y
  17274. * depends on, which in this case are the modules A and B.
  17275. * We could also say they are all modules that have both X and Y as dependent
  17276. * entry points.
  17277. *
  17278. * So we can remove D as dependent entry point from A and B, which means they
  17279. * both now have only XY as dependent entry points and can be merged into the
  17280. * same chunk.
  17281. *
  17282. * Now let us extend this to the most general case where we have several
  17283. * dynamic
  17284. * importers for one dynamic entry point.
  17285. *
  17286. * In the most general form, it works like this:
  17287. * For each dynamic entry point, we have a number of dynamic importers, which
  17288. * are the modules importing it. Using the previous ideas, we can determine
  17289. * the modules already in memory for each dynamic importer by looking for all
  17290. * modules that have all the dependent entry points of the dynamic importer as
  17291. * dependent entry points.
  17292. * So the modules that are guaranteed to be in memory when the dynamic entry
  17293. * point is loaded are the intersection of the modules already in memory for
  17294. * each dynamic importer.
  17295. *
  17296. * Assuming that A => D and B => D and A has dependent entry points XY and B
  17297. * has
  17298. * dependent entry points YZ, then the modules guaranteed to be in memory are
  17299. * all modules that have at least XYZ as dependent entry points.
  17300. * We call XYZ the *dynamically dependent entry points* of D.
  17301. *
  17302. * Now there is one last case to consider: If one of the dynamically dependent
  17303. * entries is itself a dynamic entry, then any module is in memory that either
  17304. * is a dependency of that dynamic entry or again has the dynamic dependent
  17305. * entries of that dynamic entry as dependent entry points.
  17306. *
  17307. * A naive algorithm for this proved to be costly as it contained an O(n^3)
  17308. * complexity with regard to dynamic entries that blew up for very large
  17309. * projects.
  17310. *
  17311. * If we have an efficient way to do Set operations, an alternative approach
  17312. * would be to instead collect already loaded modules per dynamic entry. And as
  17313. * all chunks from the initial grouping would behave the same, we can instead
  17314. * collect already loaded chunks for a performance improvement.
  17315. *
  17316. * To do that efficiently, need
  17317. * - a Map of dynamic imports per dynamic entry, which contains all dynamic
  17318. * imports that can be triggered by a dynamic entry
  17319. * - a Map of static dependencies per entry
  17320. * - a Map of already loaded chunks per entry that we initially populate with
  17321. * empty Sets for static entries and Sets containing all entries for dynamic
  17322. * entries
  17323. *
  17324. * For efficient operations, we assign each entry a numerical index and
  17325. * represent Sets of Chunks as BigInt values where each chunk corresponds to a
  17326. * bit index. Then thw last two maps can be represented as arrays of BigInt
  17327. * values.
  17328. *
  17329. * Then we iterate through each dynamic entry. We set the already loaded modules
  17330. * to the intersection of the previously already loaded modules with the union
  17331. * of the already loaded modules of that chunk with its static dependencies.
  17332. *
  17333. * If the already loaded modules changed, then we use the Map of dynamic imports
  17334. * per dynamic entry to marks all dynamic entry dependencies as "dirty" and put
  17335. * them back into the iteration. As an additional optimization, we note for
  17336. * each dynamic entry which dynamic dependent entries have changed and only
  17337. * intersect those entries again on subsequent interations.
  17338. *
  17339. * Then we remove the dynamic entries from the list of dependent entries for
  17340. * those chunks that are already loaded for that dynamic entry and create
  17341. * another round of chunks.
  17342. */
  17343. function getChunkAssignments(entries, manualChunkAliasByEntry, minChunkSize, log) {
  17344. const { chunkDefinitions, modulesInManualChunks } = getChunkDefinitionsFromManualChunks(manualChunkAliasByEntry);
  17345. const { allEntries, dependentEntriesByModule, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry } = analyzeModuleGraph(entries);
  17346. // Each chunk is identified by its position in this array
  17347. const initialChunks = getChunksFromDependentEntries(getModulesWithDependentEntries(dependentEntriesByModule, modulesInManualChunks));
  17348. // This mutates initialChunks but also clears
  17349. // dynamicallyDependentEntriesByDynamicEntry as side effect
  17350. removeUnnecessaryDependentEntries(initialChunks, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry, allEntries);
  17351. chunkDefinitions.push(...getOptimizedChunks(getChunksFromDependentEntries(initialChunks), allEntries.length, minChunkSize, log).map(({ modules }) => ({
  17352. alias: null,
  17353. modules
  17354. })));
  17355. return chunkDefinitions;
  17356. }
  17357. function getChunkDefinitionsFromManualChunks(manualChunkAliasByEntry) {
  17358. const chunkDefinitions = [];
  17359. const modulesInManualChunks = new Set(manualChunkAliasByEntry.keys());
  17360. const manualChunkModulesByAlias = Object.create(null);
  17361. for (const [entry, alias] of manualChunkAliasByEntry) {
  17362. addStaticDependenciesToManualChunk(entry, (manualChunkModulesByAlias[alias] || (manualChunkModulesByAlias[alias] = [])), modulesInManualChunks);
  17363. }
  17364. for (const [alias, modules] of Object.entries(manualChunkModulesByAlias)) {
  17365. chunkDefinitions.push({ alias, modules });
  17366. }
  17367. return { chunkDefinitions, modulesInManualChunks };
  17368. }
  17369. function addStaticDependenciesToManualChunk(entry, manualChunkModules, modulesInManualChunks) {
  17370. const modulesToHandle = new Set([entry]);
  17371. for (const module of modulesToHandle) {
  17372. modulesInManualChunks.add(module);
  17373. manualChunkModules.push(module);
  17374. for (const dependency of module.dependencies) {
  17375. if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
  17376. modulesToHandle.add(dependency);
  17377. }
  17378. }
  17379. }
  17380. }
  17381. function analyzeModuleGraph(entries) {
  17382. const dynamicEntryModules = new Set();
  17383. const dependentEntriesByModule = new Map();
  17384. const dynamicImportModulesByEntry = [];
  17385. const allEntriesSet = new Set(entries);
  17386. let entryIndex = 0;
  17387. for (const currentEntry of allEntriesSet) {
  17388. const dynamicImportsForCurrentEntry = new Set();
  17389. dynamicImportModulesByEntry.push(dynamicImportsForCurrentEntry);
  17390. const modulesToHandle = new Set([currentEntry]);
  17391. for (const module of modulesToHandle) {
  17392. getOrCreate(dependentEntriesByModule, module, (getNewSet)).add(entryIndex);
  17393. for (const dependency of module.getDependenciesToBeIncluded()) {
  17394. if (!(dependency instanceof ExternalModule)) {
  17395. modulesToHandle.add(dependency);
  17396. }
  17397. }
  17398. for (const { resolution } of module.dynamicImports) {
  17399. if (resolution instanceof Module &&
  17400. resolution.includedDynamicImporters.length > 0 &&
  17401. !allEntriesSet.has(resolution)) {
  17402. dynamicEntryModules.add(resolution);
  17403. allEntriesSet.add(resolution);
  17404. dynamicImportsForCurrentEntry.add(resolution);
  17405. }
  17406. }
  17407. for (const dependency of module.implicitlyLoadedBefore) {
  17408. if (!allEntriesSet.has(dependency)) {
  17409. dynamicEntryModules.add(dependency);
  17410. allEntriesSet.add(dependency);
  17411. }
  17412. }
  17413. }
  17414. entryIndex++;
  17415. }
  17416. const allEntries = [...allEntriesSet];
  17417. const { dynamicEntries, dynamicImportsByEntry } = getDynamicEntries(allEntries, dynamicEntryModules, dynamicImportModulesByEntry);
  17418. return {
  17419. allEntries,
  17420. dependentEntriesByModule,
  17421. dynamicallyDependentEntriesByDynamicEntry: getDynamicallyDependentEntriesByDynamicEntry(dependentEntriesByModule, dynamicEntries, allEntries),
  17422. dynamicImportsByEntry
  17423. };
  17424. }
  17425. function getDynamicEntries(allEntries, dynamicEntryModules, dynamicImportModulesByEntry) {
  17426. const entryIndexByModule = new Map();
  17427. const dynamicEntries = new Set();
  17428. for (const [entryIndex, entry] of allEntries.entries()) {
  17429. entryIndexByModule.set(entry, entryIndex);
  17430. if (dynamicEntryModules.has(entry)) {
  17431. dynamicEntries.add(entryIndex);
  17432. }
  17433. }
  17434. const dynamicImportsByEntry = [];
  17435. for (const dynamicImportModules of dynamicImportModulesByEntry) {
  17436. const dynamicImports = new Set();
  17437. for (const dynamicEntry of dynamicImportModules) {
  17438. dynamicImports.add(entryIndexByModule.get(dynamicEntry));
  17439. }
  17440. dynamicImportsByEntry.push(dynamicImports);
  17441. }
  17442. return { dynamicEntries, dynamicImportsByEntry };
  17443. }
  17444. function getDynamicallyDependentEntriesByDynamicEntry(dependentEntriesByModule, dynamicEntries, allEntries) {
  17445. const dynamicallyDependentEntriesByDynamicEntry = new Map();
  17446. for (const dynamicEntryIndex of dynamicEntries) {
  17447. const dynamicallyDependentEntries = getOrCreate(dynamicallyDependentEntriesByDynamicEntry, dynamicEntryIndex, (getNewSet));
  17448. const dynamicEntry = allEntries[dynamicEntryIndex];
  17449. for (const importer of concatLazy([
  17450. dynamicEntry.includedDynamicImporters,
  17451. dynamicEntry.implicitlyLoadedAfter
  17452. ])) {
  17453. for (const entry of dependentEntriesByModule.get(importer)) {
  17454. dynamicallyDependentEntries.add(entry);
  17455. }
  17456. }
  17457. }
  17458. return dynamicallyDependentEntriesByDynamicEntry;
  17459. }
  17460. function getChunksFromDependentEntries(modulesWithDependentEntries) {
  17461. var _a;
  17462. const chunkModules = Object.create(null);
  17463. for (const { dependentEntries, modules } of modulesWithDependentEntries) {
  17464. let chunkSignature = 0n;
  17465. for (const entryIndex of dependentEntries) {
  17466. chunkSignature |= 1n << BigInt(entryIndex);
  17467. }
  17468. (chunkModules[_a = String(chunkSignature)] || (chunkModules[_a] = {
  17469. dependentEntries: new Set(dependentEntries),
  17470. modules: []
  17471. })).modules.push(...modules);
  17472. }
  17473. return Object.values(chunkModules);
  17474. }
  17475. function* getModulesWithDependentEntries(dependentEntriesByModule, modulesInManualChunks) {
  17476. for (const [module, dependentEntries] of dependentEntriesByModule) {
  17477. if (!modulesInManualChunks.has(module)) {
  17478. yield { dependentEntries, modules: [module] };
  17479. }
  17480. }
  17481. }
  17482. /**
  17483. * This removes all unnecessary dynamic entries from the dependenEntries in its
  17484. * first argument. It will also consume its second argument, so if
  17485. * dynamicallyDependentEntriesByDynamicEntry is ever needed after this, we
  17486. * should make a copy.
  17487. */
  17488. function removeUnnecessaryDependentEntries(chunks, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry, allEntries) {
  17489. // The indices correspond to the indices in allEntries. The chunks correspond
  17490. // to bits in the bigint values where chunk 0 is the lowest bit.
  17491. const staticDependenciesPerEntry = allEntries.map(() => 0n);
  17492. const alreadyLoadedChunksPerEntry = allEntries.map((_entry, entryIndex) => dynamicallyDependentEntriesByDynamicEntry.has(entryIndex) ? -1n : 0n);
  17493. // This toggles the bits for each chunk that is a dependency of an entry
  17494. let chunkMask = 1n;
  17495. for (const { dependentEntries } of chunks) {
  17496. for (const entryIndex of dependentEntries) {
  17497. staticDependenciesPerEntry[entryIndex] |= chunkMask;
  17498. }
  17499. chunkMask <<= 1n;
  17500. }
  17501. // Warning: This will consume dynamicallyDependentEntriesByDynamicEntry.
  17502. // If we no longer want this, we should make a copy here.
  17503. const updatedDynamicallyDependentEntriesByDynamicEntry = dynamicallyDependentEntriesByDynamicEntry;
  17504. for (const [dynamicEntryIndex, updatedDynamicallyDependentEntries] of updatedDynamicallyDependentEntriesByDynamicEntry) {
  17505. updatedDynamicallyDependentEntriesByDynamicEntry.delete(dynamicEntryIndex);
  17506. const previousLoadedModules = alreadyLoadedChunksPerEntry[dynamicEntryIndex];
  17507. let newLoadedModules = previousLoadedModules;
  17508. for (const entryIndex of updatedDynamicallyDependentEntries) {
  17509. newLoadedModules &=
  17510. staticDependenciesPerEntry[entryIndex] | alreadyLoadedChunksPerEntry[entryIndex];
  17511. }
  17512. if (newLoadedModules !== previousLoadedModules) {
  17513. alreadyLoadedChunksPerEntry[dynamicEntryIndex] = newLoadedModules;
  17514. for (const dynamicImport of dynamicImportsByEntry[dynamicEntryIndex]) {
  17515. getOrCreate(updatedDynamicallyDependentEntriesByDynamicEntry, dynamicImport, (getNewSet)).add(dynamicEntryIndex);
  17516. }
  17517. }
  17518. }
  17519. // Remove entries from dependent entries if a chunk is already loaded without
  17520. // that entry.
  17521. chunkMask = 1n;
  17522. for (const { dependentEntries } of chunks) {
  17523. for (const entryIndex of dependentEntries) {
  17524. if ((alreadyLoadedChunksPerEntry[entryIndex] & chunkMask) === chunkMask) {
  17525. dependentEntries.delete(entryIndex);
  17526. }
  17527. }
  17528. chunkMask <<= 1n;
  17529. }
  17530. }
  17531. /**
  17532. * This function tries to get rid of small chunks by merging them with other
  17533. * chunks.
  17534. *
  17535. * We can only merge chunks safely if after the merge, loading any entry point
  17536. * in any allowed order will not trigger side effects that should not have been
  17537. * triggered. While side effects are usually things like global function calls,
  17538. * global variable mutations or potentially thrown errors, details do not
  17539. * matter here, and we just discern chunks without side effects (pure chunks)
  17540. * from other chunks.
  17541. *
  17542. * As a first step, we assign each pre-generated chunk with side effects a
  17543. * label. I.e. we have side effect "A" if the non-pure chunk "A" is loaded.
  17544. *
  17545. * Now to determine the side effects of loading a chunk, one also has to take
  17546. * the side effects of its dependencies into account. So if A depends on B
  17547. * (A -> B) and both have side effects, loading A triggers effects AB.
  17548. *
  17549. * Now from the previous step we know that each chunk is uniquely determine by
  17550. * the entry points that depend on it and cause it to load, which we will call
  17551. * its dependent entry points.
  17552. *
  17553. * E.g. if X -> A and Y -> A, then the dependent entry points of A are XY.
  17554. * Starting from that idea, we can determine a set of chunks—and thus a set
  17555. * of side effects—that must have been triggered if a certain chunk has been
  17556. * loaded. Basically, it is the intersection of all chunks loaded by the
  17557. * dependent entry points of a given chunk. We call the corresponding side
  17558. * effects the correlated side effects of that chunk.
  17559. *
  17560. * Example:
  17561. * X -> ABC, Y -> ADE, A-> F, B -> D
  17562. * Then taking dependencies into account, X -> ABCDF, Y -> ADEF
  17563. * The intersection is ADF. So we know that when A is loaded, D and F must also
  17564. * be in memory even though neither D nor A is a dependency of the other.
  17565. * If all have side effects, we call ADF the correlated side effects of A. The
  17566. * correlated side effects need to remain constant when merging chunks.
  17567. *
  17568. * In contrast, we have the dependency side effects of A, which represents
  17569. * the side effects we trigger if we directly load A. In this example, the
  17570. * dependency side effects are AF.
  17571. * For entry chunks, dependency and correlated side effects are the same.
  17572. *
  17573. * With these concepts, merging chunks is allowed if the correlated side
  17574. * effects of each entry do not change. Thus, we are allowed to merge two
  17575. * chunks if
  17576. *
  17577. * a) the dependency side effects of each chunk are a subset of the correlated
  17578. * side effects of the other chunk, so no additional side effects are
  17579. * triggered for any entry, or
  17580. * b) The dependent entry points of chunk A are a subset of the dependent entry
  17581. * points of chunk B while the dependency side effects of A are a subset of
  17582. * the correlated side effects of B. Because in that scenario, whenever A is
  17583. * loaded, B is loaded as well. But there are cases when B is loaded where A
  17584. * is not loaded. So if we merge the chunks, all dependency side effects of
  17585. * A will be added to the correlated side effects of B, and as the latter is
  17586. * not allowed to change, the former need to be a subset of the latter.
  17587. *
  17588. * Another consideration when merging small chunks into other chunks is to
  17589. * avoid
  17590. * that too much additional code is loaded. This is achieved when the dependent
  17591. * entries of the small chunk are a subset of the dependent entries of the
  17592. * other
  17593. * chunk. Because then when the small chunk is loaded, the other chunk was
  17594. * loaded/in memory anyway, so at most when the other chunk is loaded, the
  17595. * additional size of the small chunk is loaded unnecessarily.
  17596. *
  17597. * So the algorithm performs merges in two passes:
  17598. *
  17599. * 1. First we try to merge small chunks A only into other chunks B if the
  17600. * dependent entries of A are a subset of the dependent entries of B and the
  17601. * dependency side effects of A are a subset of the correlated side effects
  17602. * of B.
  17603. * 2. Only then for all remaining small chunks, we look for arbitrary merges
  17604. * following the rule (a), starting with the smallest chunks to look for
  17605. * possible merge targets.
  17606. */
  17607. function getOptimizedChunks(initialChunks, numberOfEntries, minChunkSize, log) {
  17608. timeStart('optimize chunks', 3);
  17609. const chunkPartition = getPartitionedChunks(initialChunks, numberOfEntries, minChunkSize);
  17610. if (!chunkPartition) {
  17611. timeEnd('optimize chunks', 3);
  17612. return initialChunks; // the actual modules
  17613. }
  17614. minChunkSize > 1 &&
  17615. log('info', logOptimizeChunkStatus(initialChunks.length, chunkPartition.small.size, 'Initially'));
  17616. mergeChunks(chunkPartition, minChunkSize);
  17617. minChunkSize > 1 &&
  17618. log('info', logOptimizeChunkStatus(chunkPartition.small.size + chunkPartition.big.size, chunkPartition.small.size, 'After merging chunks'));
  17619. timeEnd('optimize chunks', 3);
  17620. return [...chunkPartition.small, ...chunkPartition.big];
  17621. }
  17622. function getPartitionedChunks(initialChunks, numberOfEntries, minChunkSize) {
  17623. const smallChunks = [];
  17624. const bigChunks = [];
  17625. const chunkByModule = new Map();
  17626. const sizeByAtom = [];
  17627. let sideEffectAtoms = 0n;
  17628. let containedAtoms = 1n;
  17629. for (const { dependentEntries, modules } of initialChunks) {
  17630. const chunkDescription = {
  17631. containedAtoms,
  17632. correlatedAtoms: 0n,
  17633. dependencies: new Set(),
  17634. dependentChunks: new Set(),
  17635. dependentEntries,
  17636. modules,
  17637. pure: true,
  17638. size: 0
  17639. };
  17640. let size = 0;
  17641. let pure = true;
  17642. for (const module of modules) {
  17643. chunkByModule.set(module, chunkDescription);
  17644. // Unfortunately, we cannot take tree-shaking into account here because
  17645. // rendering did not happen yet, but we can detect empty modules
  17646. if (module.isIncluded()) {
  17647. pure && (pure = !module.hasEffects());
  17648. // we use a trivial size for the default minChunkSize to improve
  17649. // performance
  17650. size += minChunkSize > 1 ? module.estimateSize() : 1;
  17651. }
  17652. }
  17653. chunkDescription.pure = pure;
  17654. chunkDescription.size = size;
  17655. sizeByAtom.push(size);
  17656. if (!pure) {
  17657. sideEffectAtoms |= containedAtoms;
  17658. }
  17659. (size < minChunkSize ? smallChunks : bigChunks).push(chunkDescription);
  17660. containedAtoms <<= 1n;
  17661. }
  17662. // If there are no small chunks, we will not optimize
  17663. if (smallChunks.length === 0) {
  17664. return null;
  17665. }
  17666. sideEffectAtoms |= addChunkDependenciesAndAtomsAndGetSideEffectAtoms([bigChunks, smallChunks], chunkByModule, numberOfEntries, containedAtoms);
  17667. return {
  17668. big: new Set(bigChunks),
  17669. sideEffectAtoms,
  17670. sizeByAtom,
  17671. small: new Set(smallChunks)
  17672. };
  17673. }
  17674. function mergeChunks(chunkPartition, minChunkSize) {
  17675. const { small } = chunkPartition;
  17676. for (const mergedChunk of small) {
  17677. const bestTargetChunk = findBestMergeTarget(mergedChunk, chunkPartition,
  17678. // In the default case, we do not accept size increases
  17679. minChunkSize <= 1 ? 1 : Infinity);
  17680. if (bestTargetChunk) {
  17681. const { containedAtoms, correlatedAtoms, modules, pure, size } = mergedChunk;
  17682. small.delete(mergedChunk);
  17683. getChunksInPartition(bestTargetChunk, minChunkSize, chunkPartition).delete(bestTargetChunk);
  17684. bestTargetChunk.modules.push(...modules);
  17685. bestTargetChunk.size += size;
  17686. bestTargetChunk.pure && (bestTargetChunk.pure = pure);
  17687. const { dependencies, dependentChunks, dependentEntries } = bestTargetChunk;
  17688. bestTargetChunk.correlatedAtoms &= correlatedAtoms;
  17689. bestTargetChunk.containedAtoms |= containedAtoms;
  17690. for (const entry of mergedChunk.dependentEntries) {
  17691. dependentEntries.add(entry);
  17692. }
  17693. for (const dependency of mergedChunk.dependencies) {
  17694. dependencies.add(dependency);
  17695. dependency.dependentChunks.delete(mergedChunk);
  17696. dependency.dependentChunks.add(bestTargetChunk);
  17697. }
  17698. for (const dependentChunk of mergedChunk.dependentChunks) {
  17699. dependentChunks.add(dependentChunk);
  17700. dependentChunk.dependencies.delete(mergedChunk);
  17701. dependentChunk.dependencies.add(bestTargetChunk);
  17702. }
  17703. dependencies.delete(bestTargetChunk);
  17704. dependentChunks.delete(bestTargetChunk);
  17705. getChunksInPartition(bestTargetChunk, minChunkSize, chunkPartition).add(bestTargetChunk);
  17706. }
  17707. }
  17708. }
  17709. function addChunkDependenciesAndAtomsAndGetSideEffectAtoms(chunkLists, chunkByModule, numberOfEntries, nextAtomSignature) {
  17710. const signatureByExternalModule = new Map();
  17711. let sideEffectAtoms = 0n;
  17712. const atomsByEntry = [];
  17713. for (let index = 0; index < numberOfEntries; index++) {
  17714. atomsByEntry.push(0n);
  17715. }
  17716. for (const chunks of chunkLists) {
  17717. chunks.sort(compareChunkSize);
  17718. for (const chunk of chunks) {
  17719. const { dependencies, dependentEntries, modules } = chunk;
  17720. for (const module of modules) {
  17721. for (const dependency of module.getDependenciesToBeIncluded()) {
  17722. if (dependency instanceof ExternalModule) {
  17723. if (dependency.info.moduleSideEffects) {
  17724. chunk.containedAtoms |= getOrCreate(signatureByExternalModule, dependency, () => {
  17725. const signature = nextAtomSignature;
  17726. nextAtomSignature <<= 1n;
  17727. sideEffectAtoms |= signature;
  17728. return signature;
  17729. });
  17730. }
  17731. }
  17732. else {
  17733. const dependencyChunk = chunkByModule.get(dependency);
  17734. if (dependencyChunk && dependencyChunk !== chunk) {
  17735. dependencies.add(dependencyChunk);
  17736. dependencyChunk.dependentChunks.add(chunk);
  17737. }
  17738. }
  17739. }
  17740. }
  17741. const { containedAtoms } = chunk;
  17742. for (const entryIndex of dependentEntries) {
  17743. atomsByEntry[entryIndex] |= containedAtoms;
  17744. }
  17745. }
  17746. }
  17747. for (const chunks of chunkLists) {
  17748. for (const chunk of chunks) {
  17749. const { dependentEntries } = chunk;
  17750. // Correlated atoms are the intersection of all entry atoms
  17751. chunk.correlatedAtoms = -1n;
  17752. for (const entryIndex of dependentEntries) {
  17753. chunk.correlatedAtoms &= atomsByEntry[entryIndex];
  17754. }
  17755. }
  17756. }
  17757. return sideEffectAtoms;
  17758. }
  17759. function findBestMergeTarget(mergedChunk, { big, sideEffectAtoms, sizeByAtom, small }, smallestAdditionalSize) {
  17760. let bestTargetChunk = null;
  17761. // In the default case, we do not accept size increases
  17762. for (const targetChunk of concatLazy([small, big])) {
  17763. if (mergedChunk === targetChunk)
  17764. continue;
  17765. const additionalSizeAfterMerge = getAdditionalSizeAfterMerge(mergedChunk, targetChunk, smallestAdditionalSize, sideEffectAtoms, sizeByAtom);
  17766. if (additionalSizeAfterMerge < smallestAdditionalSize) {
  17767. bestTargetChunk = targetChunk;
  17768. if (additionalSizeAfterMerge === 0)
  17769. break;
  17770. smallestAdditionalSize = additionalSizeAfterMerge;
  17771. }
  17772. }
  17773. return bestTargetChunk;
  17774. }
  17775. function getChunksInPartition(chunk, minChunkSize, chunkPartition) {
  17776. return chunk.size < minChunkSize ? chunkPartition.small : chunkPartition.big;
  17777. }
  17778. function compareChunkSize({ size: sizeA }, { size: sizeB }) {
  17779. return sizeA - sizeB;
  17780. }
  17781. /**
  17782. * Determine the additional unused code size that would be added by merging the
  17783. * two chunks. This is not an exact measurement but rather an upper bound. If
  17784. * the merge produces cycles or adds non-correlated side effects, `Infinity`
  17785. * is returned.
  17786. * Merging will not produce cycles if none of the direct non-merged
  17787. * dependencies of a chunk have the other chunk as a transitive dependency.
  17788. */
  17789. function getAdditionalSizeAfterMerge(mergedChunk, targetChunk,
  17790. // The maximum additional unused code size allowed to be added by the merge,
  17791. // taking dependencies into account, needs to be below this number
  17792. currentAdditionalSize, sideEffectAtoms, sizeByAtom) {
  17793. const firstSize = getAdditionalSizeIfNoTransitiveDependencyOrNonCorrelatedSideEffect(mergedChunk, targetChunk, currentAdditionalSize, sideEffectAtoms, sizeByAtom);
  17794. return firstSize < currentAdditionalSize
  17795. ? firstSize +
  17796. getAdditionalSizeIfNoTransitiveDependencyOrNonCorrelatedSideEffect(targetChunk, mergedChunk, currentAdditionalSize - firstSize, sideEffectAtoms, sizeByAtom)
  17797. : Infinity;
  17798. }
  17799. function getAdditionalSizeIfNoTransitiveDependencyOrNonCorrelatedSideEffect(dependentChunk, dependencyChunk, currentAdditionalSize, sideEffectAtoms, sizeByAtom) {
  17800. const { correlatedAtoms } = dependencyChunk;
  17801. let dependencyAtoms = dependentChunk.containedAtoms;
  17802. const dependentContainedSideEffects = dependencyAtoms & sideEffectAtoms;
  17803. if ((correlatedAtoms & dependentContainedSideEffects) !== dependentContainedSideEffects) {
  17804. return Infinity;
  17805. }
  17806. const chunksToCheck = new Set(dependentChunk.dependencies);
  17807. for (const { dependencies, containedAtoms } of chunksToCheck) {
  17808. dependencyAtoms |= containedAtoms;
  17809. const containedSideEffects = containedAtoms & sideEffectAtoms;
  17810. if ((correlatedAtoms & containedSideEffects) !== containedSideEffects) {
  17811. return Infinity;
  17812. }
  17813. for (const dependency of dependencies) {
  17814. if (dependency === dependencyChunk) {
  17815. return Infinity;
  17816. }
  17817. chunksToCheck.add(dependency);
  17818. }
  17819. }
  17820. return getAtomsSizeIfBelowLimit(dependencyAtoms & ~correlatedAtoms, currentAdditionalSize, sizeByAtom);
  17821. }
  17822. function getAtomsSizeIfBelowLimit(atoms, currentAdditionalSize, sizeByAtom) {
  17823. let size = 0;
  17824. let atomIndex = 0;
  17825. let atomSignature = 1n;
  17826. const { length } = sizeByAtom;
  17827. for (; atomIndex < length; atomIndex++) {
  17828. if ((atoms & atomSignature) === atomSignature) {
  17829. size += sizeByAtom[atomIndex];
  17830. }
  17831. atomSignature <<= 1n;
  17832. if (size >= currentAdditionalSize) {
  17833. return Infinity;
  17834. }
  17835. }
  17836. return size;
  17837. }
  17838. // ported from https://github.com/substack/node-commondir
  17839. function commondir(files) {
  17840. if (files.length === 0)
  17841. return '/';
  17842. if (files.length === 1)
  17843. return node_path.dirname(files[0]);
  17844. const commonSegments = files.slice(1).reduce((commonSegments, file) => {
  17845. const pathSegements = file.split(/\/+|\\+/);
  17846. let index;
  17847. for (index = 0; commonSegments[index] === pathSegements[index] &&
  17848. index < Math.min(commonSegments.length, pathSegements.length); index++)
  17849. ;
  17850. return commonSegments.slice(0, index);
  17851. }, files[0].split(/\/+|\\+/));
  17852. // Windows correctly handles paths with forward-slashes
  17853. return commonSegments.length > 1 ? commonSegments.join('/') : '/';
  17854. }
  17855. const compareExecIndex = (unitA, unitB) => unitA.execIndex > unitB.execIndex ? 1 : -1;
  17856. function sortByExecutionOrder(units) {
  17857. units.sort(compareExecIndex);
  17858. }
  17859. function analyseModuleExecution(entryModules) {
  17860. let nextExecIndex = 0;
  17861. const cyclePaths = [];
  17862. const analysedModules = new Set();
  17863. const dynamicImports = new Set();
  17864. const parents = new Map();
  17865. const orderedModules = [];
  17866. const analyseModule = (module) => {
  17867. if (module instanceof Module) {
  17868. for (const dependency of module.dependencies) {
  17869. if (parents.has(dependency)) {
  17870. if (!analysedModules.has(dependency)) {
  17871. cyclePaths.push(getCyclePath(dependency, module, parents));
  17872. }
  17873. continue;
  17874. }
  17875. parents.set(dependency, module);
  17876. analyseModule(dependency);
  17877. }
  17878. for (const dependency of module.implicitlyLoadedBefore) {
  17879. dynamicImports.add(dependency);
  17880. }
  17881. for (const { resolution } of module.dynamicImports) {
  17882. if (resolution instanceof Module) {
  17883. dynamicImports.add(resolution);
  17884. }
  17885. }
  17886. orderedModules.push(module);
  17887. }
  17888. module.execIndex = nextExecIndex++;
  17889. analysedModules.add(module);
  17890. };
  17891. for (const currentEntry of entryModules) {
  17892. if (!parents.has(currentEntry)) {
  17893. parents.set(currentEntry, null);
  17894. analyseModule(currentEntry);
  17895. }
  17896. }
  17897. for (const currentEntry of dynamicImports) {
  17898. if (!parents.has(currentEntry)) {
  17899. parents.set(currentEntry, null);
  17900. analyseModule(currentEntry);
  17901. }
  17902. }
  17903. return { cyclePaths, orderedModules };
  17904. }
  17905. function getCyclePath(module, parent, parents) {
  17906. const cycleSymbol = Symbol(module.id);
  17907. const path = [module.id];
  17908. let nextModule = parent;
  17909. module.cycles.add(cycleSymbol);
  17910. while (nextModule !== module) {
  17911. nextModule.cycles.add(cycleSymbol);
  17912. path.push(nextModule.id);
  17913. nextModule = parents.get(nextModule);
  17914. }
  17915. path.push(path[0]);
  17916. path.reverse();
  17917. return path;
  17918. }
  17919. function getGenerateCodeSnippets({ compact, generatedCode: { arrowFunctions, constBindings, objectShorthand, reservedNamesAsProps } }) {
  17920. const { _, n, s } = compact ? { _: '', n: '', s: '' } : { _: ' ', n: '\n', s: ';' };
  17921. const cnst = constBindings ? 'const' : 'var';
  17922. const getNonArrowFunctionIntro = (parameters, { isAsync, name }) => `${isAsync ? `async ` : ''}function${name ? ` ${name}` : ''}${_}(${parameters.join(`,${_}`)})${_}`;
  17923. const getFunctionIntro = arrowFunctions
  17924. ? (parameters, { isAsync, name }) => {
  17925. const singleParameter = parameters.length === 1;
  17926. const asyncString = isAsync ? `async${singleParameter ? ' ' : _}` : '';
  17927. return `${name ? `${cnst} ${name}${_}=${_}` : ''}${asyncString}${singleParameter ? parameters[0] : `(${parameters.join(`,${_}`)})`}${_}=>${_}`;
  17928. }
  17929. : getNonArrowFunctionIntro;
  17930. const getDirectReturnFunction = (parameters, { functionReturn, lineBreakIndent, name }) => [
  17931. `${getFunctionIntro(parameters, {
  17932. isAsync: false,
  17933. name
  17934. })}${arrowFunctions
  17935. ? lineBreakIndent
  17936. ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}`
  17937. : ''
  17938. : `{${lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _}${functionReturn ? 'return ' : ''}`}`,
  17939. arrowFunctions
  17940. ? `${name ? ';' : ''}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : ''}`
  17941. : `${s}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`
  17942. ];
  17943. const isValidPropertyName = reservedNamesAsProps
  17944. ? (name) => validPropertyName.test(name)
  17945. : (name) => !RESERVED_NAMES$1.has(name) && validPropertyName.test(name);
  17946. return {
  17947. _,
  17948. cnst,
  17949. getDirectReturnFunction,
  17950. getDirectReturnIifeLeft: (parameters, returned, { needsArrowReturnParens, needsWrappedFunction }) => {
  17951. const [left, right] = getDirectReturnFunction(parameters, {
  17952. functionReturn: true,
  17953. lineBreakIndent: null,
  17954. name: null
  17955. });
  17956. return `${wrapIfNeeded(`${left}${wrapIfNeeded(returned, arrowFunctions && needsArrowReturnParens)}${right}`, arrowFunctions || needsWrappedFunction)}(`;
  17957. },
  17958. getFunctionIntro,
  17959. getNonArrowFunctionIntro,
  17960. getObject(fields, { lineBreakIndent }) {
  17961. const prefix = lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _;
  17962. return `{${fields
  17963. .map(([key, value]) => {
  17964. if (key === null)
  17965. return `${prefix}${value}`;
  17966. const needsQuotes = !isValidPropertyName(key);
  17967. return key === value && objectShorthand && !needsQuotes
  17968. ? prefix + key
  17969. : `${prefix}${needsQuotes ? `'${key}'` : key}:${_}${value}`;
  17970. })
  17971. .join(`,`)}${fields.length === 0 ? '' : lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`;
  17972. },
  17973. getPropertyAccess: (name) => isValidPropertyName(name) ? `.${name}` : `[${JSON.stringify(name)}]`,
  17974. n,
  17975. s
  17976. };
  17977. }
  17978. const wrapIfNeeded = (code, needsParens) => needsParens ? `(${code})` : code;
  17979. const validPropertyName = /^(?!\d)[\w$]+$/;
  17980. class Source {
  17981. constructor(filename, content) {
  17982. this.isOriginal = true;
  17983. this.filename = filename;
  17984. this.content = content;
  17985. }
  17986. traceSegment(line, column, name) {
  17987. return { column, line, name, source: this };
  17988. }
  17989. }
  17990. class Link {
  17991. constructor(map, sources) {
  17992. this.sources = sources;
  17993. this.names = map.names;
  17994. this.mappings = map.mappings;
  17995. }
  17996. traceMappings() {
  17997. const sources = [];
  17998. const sourceIndexMap = new Map();
  17999. const sourcesContent = [];
  18000. const names = [];
  18001. const nameIndexMap = new Map();
  18002. const mappings = [];
  18003. for (const line of this.mappings) {
  18004. const tracedLine = [];
  18005. for (const segment of line) {
  18006. if (segment.length === 1)
  18007. continue;
  18008. const source = this.sources[segment[1]];
  18009. if (!source)
  18010. continue;
  18011. const traced = source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : '');
  18012. if (traced) {
  18013. const { column, line, name, source: { content, filename } } = traced;
  18014. let sourceIndex = sourceIndexMap.get(filename);
  18015. if (sourceIndex === undefined) {
  18016. sourceIndex = sources.length;
  18017. sources.push(filename);
  18018. sourceIndexMap.set(filename, sourceIndex);
  18019. sourcesContent[sourceIndex] = content;
  18020. }
  18021. else if (sourcesContent[sourceIndex] == null) {
  18022. sourcesContent[sourceIndex] = content;
  18023. }
  18024. else if (content != null && sourcesContent[sourceIndex] !== content) {
  18025. return error(logConflictingSourcemapSources(filename));
  18026. }
  18027. const tracedSegment = [segment[0], sourceIndex, line, column];
  18028. if (name) {
  18029. let nameIndex = nameIndexMap.get(name);
  18030. if (nameIndex === undefined) {
  18031. nameIndex = names.length;
  18032. names.push(name);
  18033. nameIndexMap.set(name, nameIndex);
  18034. }
  18035. tracedSegment[4] = nameIndex;
  18036. }
  18037. tracedLine.push(tracedSegment);
  18038. }
  18039. }
  18040. mappings.push(tracedLine);
  18041. }
  18042. return { mappings, names, sources, sourcesContent };
  18043. }
  18044. traceSegment(line, column, name) {
  18045. const segments = this.mappings[line];
  18046. if (!segments)
  18047. return null;
  18048. // binary search through segments for the given column
  18049. let searchStart = 0;
  18050. let searchEnd = segments.length - 1;
  18051. while (searchStart <= searchEnd) {
  18052. const m = (searchStart + searchEnd) >> 1;
  18053. const segment = segments[m];
  18054. // If a sourcemap does not have sufficient resolution to contain a
  18055. // necessary mapping, e.g. because it only contains line information, we
  18056. // use the best approximation we could find
  18057. if (segment[0] === column || searchStart === searchEnd) {
  18058. if (segment.length == 1)
  18059. return null;
  18060. const source = this.sources[segment[1]];
  18061. if (!source)
  18062. return null;
  18063. return source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : name);
  18064. }
  18065. if (segment[0] > column) {
  18066. searchEnd = m - 1;
  18067. }
  18068. else {
  18069. searchStart = m + 1;
  18070. }
  18071. }
  18072. return null;
  18073. }
  18074. }
  18075. function getLinkMap(log) {
  18076. return function linkMap(source, map) {
  18077. if (!map.missing) {
  18078. return new Link(map, [source]);
  18079. }
  18080. log(LOGLEVEL_WARN, logSourcemapBroken(map.plugin));
  18081. return new Link({
  18082. mappings: [],
  18083. names: []
  18084. }, [source]);
  18085. };
  18086. }
  18087. function getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, linkMap) {
  18088. let source;
  18089. if (originalSourcemap) {
  18090. const sources = originalSourcemap.sources;
  18091. const sourcesContent = originalSourcemap.sourcesContent || [];
  18092. const directory = node_path.dirname(id) || '.';
  18093. const sourceRoot = originalSourcemap.sourceRoot || '.';
  18094. const baseSources = sources.map((source, index) => new Source(node_path.resolve(directory, sourceRoot, source), sourcesContent[index]));
  18095. source = new Link(originalSourcemap, baseSources);
  18096. }
  18097. else {
  18098. source = new Source(id, originalCode);
  18099. }
  18100. return sourcemapChain.reduce(linkMap, source);
  18101. }
  18102. function collapseSourcemaps(file, map, modules, bundleSourcemapChain, excludeContent, log) {
  18103. const linkMap = getLinkMap(log);
  18104. const moduleSources = modules
  18105. .filter(module => !module.excludeFromSourcemap)
  18106. .map(module => getCollapsedSourcemap(module.id, module.originalCode, module.originalSourcemap, module.sourcemapChain, linkMap));
  18107. const link = new Link(map, moduleSources);
  18108. const source = bundleSourcemapChain.reduce(linkMap, link);
  18109. let { sources, sourcesContent, names, mappings } = source.traceMappings();
  18110. if (file) {
  18111. const directory = node_path.dirname(file);
  18112. sources = sources.map((source) => node_path.relative(directory, source));
  18113. file = node_path.basename(file);
  18114. }
  18115. sourcesContent = (excludeContent ? null : sourcesContent);
  18116. for (const module of modules) {
  18117. resetSourcemapCache(module.originalSourcemap, module.sourcemapChain);
  18118. }
  18119. return new SourceMap({ file, mappings, names, sources, sourcesContent });
  18120. }
  18121. function collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, log) {
  18122. if (sourcemapChain.length === 0) {
  18123. return originalSourcemap;
  18124. }
  18125. const source = getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, getLinkMap(log));
  18126. const map = source.traceMappings();
  18127. return decodedSourcemap({ version: 3, ...map });
  18128. }
  18129. async function renderChunks(chunks, bundle, pluginDriver, outputOptions, log) {
  18130. timeStart('render chunks', 2);
  18131. reserveEntryChunksInBundle(chunks);
  18132. const renderedChunks = await Promise.all(chunks.map(chunk => chunk.render()));
  18133. timeEnd('render chunks', 2);
  18134. timeStart('transform chunks', 2);
  18135. const chunkGraph = getChunkGraph(chunks);
  18136. const { initialHashesByPlaceholder, nonHashedChunksWithPlaceholders, renderedChunksByPlaceholder, hashDependenciesByPlaceholder } = await transformChunksAndGenerateContentHashes(renderedChunks, chunkGraph, outputOptions, pluginDriver, log);
  18137. const hashesByPlaceholder = generateFinalHashes(renderedChunksByPlaceholder, hashDependenciesByPlaceholder, initialHashesByPlaceholder, bundle);
  18138. addChunksToBundle(renderedChunksByPlaceholder, hashesByPlaceholder, bundle, nonHashedChunksWithPlaceholders, pluginDriver, outputOptions);
  18139. timeEnd('transform chunks', 2);
  18140. }
  18141. function reserveEntryChunksInBundle(chunks) {
  18142. for (const chunk of chunks) {
  18143. if (chunk.facadeModule && chunk.facadeModule.isUserDefinedEntryPoint) {
  18144. // reserves name in bundle as side effect if it does not contain a hash
  18145. chunk.getPreliminaryFileName();
  18146. }
  18147. }
  18148. }
  18149. function getChunkGraph(chunks) {
  18150. return Object.fromEntries(chunks.map(chunk => {
  18151. const renderedChunkInfo = chunk.getRenderedChunkInfo();
  18152. return [renderedChunkInfo.fileName, renderedChunkInfo];
  18153. }));
  18154. }
  18155. async function transformChunk(magicString, fileName, usedModules, chunkGraph, options, outputPluginDriver, log) {
  18156. let map = null;
  18157. const sourcemapChain = [];
  18158. let code = await outputPluginDriver.hookReduceArg0('renderChunk', [magicString.toString(), chunkGraph[fileName], options, { chunks: chunkGraph }], (code, result, plugin) => {
  18159. if (result == null)
  18160. return code;
  18161. if (typeof result === 'string')
  18162. result = {
  18163. code: result,
  18164. map: undefined
  18165. };
  18166. // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning
  18167. if (result.map !== null) {
  18168. const map = decodedSourcemap(result.map);
  18169. sourcemapChain.push(map || { missing: true, plugin: plugin.name });
  18170. }
  18171. return result.code;
  18172. });
  18173. const { compact, dir, file, sourcemap, sourcemapExcludeSources, sourcemapFile, sourcemapPathTransform, sourcemapIgnoreList } = options;
  18174. if (!compact && code[code.length - 1] !== '\n')
  18175. code += '\n';
  18176. if (sourcemap) {
  18177. timeStart('sourcemaps', 3);
  18178. let resultingFile;
  18179. if (file)
  18180. resultingFile = node_path.resolve(sourcemapFile || file);
  18181. else if (dir)
  18182. resultingFile = node_path.resolve(dir, fileName);
  18183. else
  18184. resultingFile = node_path.resolve(fileName);
  18185. const decodedMap = magicString.generateDecodedMap({});
  18186. map = collapseSourcemaps(resultingFile, decodedMap, usedModules, sourcemapChain, sourcemapExcludeSources, log);
  18187. for (let sourcesIndex = 0; sourcesIndex < map.sources.length; ++sourcesIndex) {
  18188. let sourcePath = map.sources[sourcesIndex];
  18189. const sourcemapPath = `${resultingFile}.map`;
  18190. const ignoreList = sourcemapIgnoreList(sourcePath, sourcemapPath);
  18191. if (typeof ignoreList !== 'boolean') {
  18192. error(logFailedValidation('sourcemapIgnoreList function must return a boolean.'));
  18193. }
  18194. if (ignoreList) {
  18195. if (map.x_google_ignoreList === undefined) {
  18196. map.x_google_ignoreList = [];
  18197. }
  18198. if (!map.x_google_ignoreList.includes(sourcesIndex)) {
  18199. map.x_google_ignoreList.push(sourcesIndex);
  18200. }
  18201. }
  18202. if (sourcemapPathTransform) {
  18203. sourcePath = sourcemapPathTransform(sourcePath, sourcemapPath);
  18204. if (typeof sourcePath !== 'string') {
  18205. error(logFailedValidation(`sourcemapPathTransform function must return a string.`));
  18206. }
  18207. }
  18208. map.sources[sourcesIndex] = normalize(sourcePath);
  18209. }
  18210. timeEnd('sourcemaps', 3);
  18211. }
  18212. return {
  18213. code,
  18214. map
  18215. };
  18216. }
  18217. async function transformChunksAndGenerateContentHashes(renderedChunks, chunkGraph, outputOptions, pluginDriver, log) {
  18218. const nonHashedChunksWithPlaceholders = [];
  18219. const renderedChunksByPlaceholder = new Map();
  18220. const hashDependenciesByPlaceholder = new Map();
  18221. const initialHashesByPlaceholder = new Map();
  18222. const placeholders = new Set();
  18223. for (const { preliminaryFileName: { hashPlaceholder } } of renderedChunks) {
  18224. if (hashPlaceholder)
  18225. placeholders.add(hashPlaceholder);
  18226. }
  18227. await Promise.all(renderedChunks.map(async ({ chunk, preliminaryFileName: { fileName, hashPlaceholder }, preliminarySourcemapFileName, magicString, usedModules }) => {
  18228. const transformedChunk = {
  18229. chunk,
  18230. fileName,
  18231. sourcemapFileName: preliminarySourcemapFileName?.fileName ?? null,
  18232. ...(await transformChunk(magicString, fileName, usedModules, chunkGraph, outputOptions, pluginDriver, log))
  18233. };
  18234. const { code, map } = transformedChunk;
  18235. if (hashPlaceholder) {
  18236. // To create a reproducible content-only hash, all placeholders are
  18237. // replaced with the same value before hashing
  18238. const { containedPlaceholders, transformedCode } = replacePlaceholdersWithDefaultAndGetContainedPlaceholders(code, placeholders);
  18239. const hash = createHash().update(transformedCode);
  18240. const hashAugmentation = pluginDriver.hookReduceValueSync('augmentChunkHash', '', [chunk.getRenderedChunkInfo()], (augmentation, pluginHash) => {
  18241. if (pluginHash) {
  18242. augmentation += pluginHash;
  18243. }
  18244. return augmentation;
  18245. });
  18246. if (hashAugmentation) {
  18247. hash.update(hashAugmentation);
  18248. }
  18249. renderedChunksByPlaceholder.set(hashPlaceholder, transformedChunk);
  18250. hashDependenciesByPlaceholder.set(hashPlaceholder, {
  18251. containedPlaceholders,
  18252. contentHash: hash.digest('hex')
  18253. });
  18254. }
  18255. else {
  18256. nonHashedChunksWithPlaceholders.push(transformedChunk);
  18257. }
  18258. const sourcemapHashPlaceholder = preliminarySourcemapFileName?.hashPlaceholder;
  18259. if (map && sourcemapHashPlaceholder) {
  18260. initialHashesByPlaceholder.set(preliminarySourcemapFileName.hashPlaceholder, createHash()
  18261. .update(map.toString())
  18262. .digest('hex')
  18263. .slice(0, preliminarySourcemapFileName.hashPlaceholder.length));
  18264. }
  18265. }));
  18266. return {
  18267. hashDependenciesByPlaceholder,
  18268. initialHashesByPlaceholder,
  18269. nonHashedChunksWithPlaceholders,
  18270. renderedChunksByPlaceholder
  18271. };
  18272. }
  18273. function generateFinalHashes(renderedChunksByPlaceholder, hashDependenciesByPlaceholder, initialHashesByPlaceholder, bundle) {
  18274. const hashesByPlaceholder = new Map(initialHashesByPlaceholder);
  18275. for (const [placeholder, { fileName }] of renderedChunksByPlaceholder) {
  18276. let hash = createHash();
  18277. const hashDependencyPlaceholders = new Set([placeholder]);
  18278. for (const dependencyPlaceholder of hashDependencyPlaceholders) {
  18279. const { containedPlaceholders, contentHash } = hashDependenciesByPlaceholder.get(dependencyPlaceholder);
  18280. hash.update(contentHash);
  18281. for (const containedPlaceholder of containedPlaceholders) {
  18282. // When looping over a map, setting an entry only causes a new iteration if the key is new
  18283. hashDependencyPlaceholders.add(containedPlaceholder);
  18284. }
  18285. }
  18286. let finalFileName;
  18287. let finalHash;
  18288. do {
  18289. // In case of a hash collision, create a hash of the hash
  18290. if (finalHash) {
  18291. hash = createHash().update(finalHash);
  18292. }
  18293. finalHash = hash.digest('hex').slice(0, placeholder.length);
  18294. finalFileName = replaceSinglePlaceholder(fileName, placeholder, finalHash);
  18295. } while (bundle[lowercaseBundleKeys].has(finalFileName.toLowerCase()));
  18296. bundle[finalFileName] = FILE_PLACEHOLDER;
  18297. hashesByPlaceholder.set(placeholder, finalHash);
  18298. }
  18299. return hashesByPlaceholder;
  18300. }
  18301. function addChunksToBundle(renderedChunksByPlaceholder, hashesByPlaceholder, bundle, nonHashedChunksWithPlaceholders, pluginDriver, options) {
  18302. for (const { chunk, code, fileName, sourcemapFileName, map } of renderedChunksByPlaceholder.values()) {
  18303. let updatedCode = replacePlaceholders(code, hashesByPlaceholder);
  18304. const finalFileName = replacePlaceholders(fileName, hashesByPlaceholder);
  18305. let finalSourcemapFileName = null;
  18306. if (map) {
  18307. finalSourcemapFileName = sourcemapFileName
  18308. ? replacePlaceholders(sourcemapFileName, hashesByPlaceholder)
  18309. : `${finalFileName}.map`;
  18310. map.file = replacePlaceholders(map.file, hashesByPlaceholder);
  18311. updatedCode += emitSourceMapAndGetComment(finalSourcemapFileName, map, pluginDriver, options);
  18312. }
  18313. bundle[finalFileName] = chunk.finalizeChunk(updatedCode, map, finalSourcemapFileName, hashesByPlaceholder);
  18314. }
  18315. for (const { chunk, code, fileName, sourcemapFileName, map } of nonHashedChunksWithPlaceholders) {
  18316. let updatedCode = hashesByPlaceholder.size > 0 ? replacePlaceholders(code, hashesByPlaceholder) : code;
  18317. let finalSourcemapFileName = null;
  18318. if (map) {
  18319. finalSourcemapFileName = sourcemapFileName
  18320. ? replacePlaceholders(sourcemapFileName, hashesByPlaceholder)
  18321. : `${fileName}.map`;
  18322. updatedCode += emitSourceMapAndGetComment(finalSourcemapFileName, map, pluginDriver, options);
  18323. }
  18324. bundle[fileName] = chunk.finalizeChunk(updatedCode, map, finalSourcemapFileName, hashesByPlaceholder);
  18325. }
  18326. }
  18327. function emitSourceMapAndGetComment(fileName, map, pluginDriver, { sourcemap, sourcemapBaseUrl }) {
  18328. let url;
  18329. if (sourcemap === 'inline') {
  18330. url = map.toUrl();
  18331. }
  18332. else {
  18333. const sourcemapFileName = node_path.basename(fileName);
  18334. url = sourcemapBaseUrl
  18335. ? new URL(sourcemapFileName, sourcemapBaseUrl).toString()
  18336. : sourcemapFileName;
  18337. pluginDriver.emitFile({ fileName, source: map.toString(), type: 'asset' });
  18338. }
  18339. return sourcemap === 'hidden' ? '' : `//# ${SOURCEMAPPING_URL}=${url}\n`;
  18340. }
  18341. class Bundle {
  18342. constructor(outputOptions, unsetOptions, inputOptions, pluginDriver, graph) {
  18343. this.outputOptions = outputOptions;
  18344. this.unsetOptions = unsetOptions;
  18345. this.inputOptions = inputOptions;
  18346. this.pluginDriver = pluginDriver;
  18347. this.graph = graph;
  18348. this.facadeChunkByModule = new Map();
  18349. this.includedNamespaces = new Set();
  18350. }
  18351. async generate(isWrite) {
  18352. timeStart('GENERATE', 1);
  18353. const outputBundleBase = Object.create(null);
  18354. const outputBundle = getOutputBundle(outputBundleBase);
  18355. this.pluginDriver.setOutputBundle(outputBundle, this.outputOptions);
  18356. try {
  18357. timeStart('initialize render', 2);
  18358. await this.pluginDriver.hookParallel('renderStart', [this.outputOptions, this.inputOptions]);
  18359. timeEnd('initialize render', 2);
  18360. timeStart('generate chunks', 2);
  18361. const getHashPlaceholder = getHashPlaceholderGenerator();
  18362. const chunks = await this.generateChunks(outputBundle, getHashPlaceholder);
  18363. if (chunks.length > 1) {
  18364. validateOptionsForMultiChunkOutput(this.outputOptions, this.inputOptions.onLog);
  18365. }
  18366. this.pluginDriver.setChunkInformation(this.facadeChunkByModule);
  18367. for (const chunk of chunks) {
  18368. chunk.generateExports();
  18369. }
  18370. timeEnd('generate chunks', 2);
  18371. await renderChunks(chunks, outputBundle, this.pluginDriver, this.outputOptions, this.inputOptions.onLog);
  18372. }
  18373. catch (error_) {
  18374. await this.pluginDriver.hookParallel('renderError', [error_]);
  18375. throw error_;
  18376. }
  18377. removeUnreferencedAssets(outputBundle);
  18378. timeStart('generate bundle', 2);
  18379. await this.pluginDriver.hookSeq('generateBundle', [
  18380. this.outputOptions,
  18381. outputBundle,
  18382. isWrite
  18383. ]);
  18384. this.finaliseAssets(outputBundle);
  18385. timeEnd('generate bundle', 2);
  18386. timeEnd('GENERATE', 1);
  18387. return outputBundleBase;
  18388. }
  18389. async addManualChunks(manualChunks) {
  18390. const manualChunkAliasByEntry = new Map();
  18391. const chunkEntries = await Promise.all(Object.entries(manualChunks).map(async ([alias, files]) => ({
  18392. alias,
  18393. entries: await this.graph.moduleLoader.addAdditionalModules(files, true)
  18394. })));
  18395. for (const { alias, entries } of chunkEntries) {
  18396. for (const entry of entries) {
  18397. addModuleToManualChunk(alias, entry, manualChunkAliasByEntry);
  18398. }
  18399. }
  18400. return manualChunkAliasByEntry;
  18401. }
  18402. assignManualChunks(getManualChunk) {
  18403. // eslint-disable-next-line unicorn/prefer-module
  18404. const manualChunkAliasesWithEntry = [];
  18405. const manualChunksApi = {
  18406. getModuleIds: () => this.graph.modulesById.keys(),
  18407. getModuleInfo: this.graph.getModuleInfo
  18408. };
  18409. for (const module of this.graph.modulesById.values()) {
  18410. if (module instanceof Module) {
  18411. const manualChunkAlias = getManualChunk(module.id, manualChunksApi);
  18412. if (typeof manualChunkAlias === 'string') {
  18413. manualChunkAliasesWithEntry.push([manualChunkAlias, module]);
  18414. }
  18415. }
  18416. }
  18417. manualChunkAliasesWithEntry.sort(([aliasA], [aliasB]) => aliasA > aliasB ? 1 : aliasA < aliasB ? -1 : 0);
  18418. const manualChunkAliasByEntry = new Map();
  18419. for (const [alias, module] of manualChunkAliasesWithEntry) {
  18420. addModuleToManualChunk(alias, module, manualChunkAliasByEntry);
  18421. }
  18422. return manualChunkAliasByEntry;
  18423. }
  18424. finaliseAssets(bundle) {
  18425. if (this.outputOptions.validate) {
  18426. for (const file of Object.values(bundle)) {
  18427. if ('code' in file) {
  18428. try {
  18429. this.graph.contextParse(file.code, {
  18430. ecmaVersion: 'latest'
  18431. });
  18432. }
  18433. catch (error_) {
  18434. this.inputOptions.onLog(LOGLEVEL_WARN, logChunkInvalid(file, error_));
  18435. }
  18436. }
  18437. }
  18438. }
  18439. this.pluginDriver.finaliseAssets();
  18440. }
  18441. async generateChunks(bundle, getHashPlaceholder) {
  18442. const { experimentalMinChunkSize, inlineDynamicImports, manualChunks, preserveModules } = this.outputOptions;
  18443. const manualChunkAliasByEntry = typeof manualChunks === 'object'
  18444. ? await this.addManualChunks(manualChunks)
  18445. : this.assignManualChunks(manualChunks);
  18446. const snippets = getGenerateCodeSnippets(this.outputOptions);
  18447. const includedModules = getIncludedModules(this.graph.modulesById);
  18448. const inputBase = commondir(getAbsoluteEntryModulePaths(includedModules, preserveModules));
  18449. const externalChunkByModule = getExternalChunkByModule(this.graph.modulesById, this.outputOptions, inputBase);
  18450. const chunks = [];
  18451. const chunkByModule = new Map();
  18452. for (const { alias, modules } of inlineDynamicImports
  18453. ? [{ alias: null, modules: includedModules }]
  18454. : preserveModules
  18455. ? includedModules.map(module => ({ alias: null, modules: [module] }))
  18456. : getChunkAssignments(this.graph.entryModules, manualChunkAliasByEntry, experimentalMinChunkSize, this.inputOptions.onLog)) {
  18457. sortByExecutionOrder(modules);
  18458. const chunk = new Chunk(modules, this.inputOptions, this.outputOptions, this.unsetOptions, this.pluginDriver, this.graph.modulesById, chunkByModule, externalChunkByModule, this.facadeChunkByModule, this.includedNamespaces, alias, getHashPlaceholder, bundle, inputBase, snippets);
  18459. chunks.push(chunk);
  18460. }
  18461. for (const chunk of chunks) {
  18462. chunk.link();
  18463. }
  18464. const facades = [];
  18465. for (const chunk of chunks) {
  18466. facades.push(...chunk.generateFacades());
  18467. }
  18468. return [...chunks, ...facades];
  18469. }
  18470. }
  18471. function validateOptionsForMultiChunkOutput(outputOptions, log) {
  18472. if (outputOptions.format === 'umd' || outputOptions.format === 'iife')
  18473. return error(logInvalidOption('output.format', URL_OUTPUT_FORMAT, 'UMD and IIFE output formats are not supported for code-splitting builds', outputOptions.format));
  18474. if (typeof outputOptions.file === 'string')
  18475. return error(logInvalidOption('output.file', URL_OUTPUT_DIR, 'when building multiple chunks, the "output.dir" option must be used, not "output.file". To inline dynamic imports, set the "inlineDynamicImports" option'));
  18476. if (outputOptions.sourcemapFile)
  18477. return error(logInvalidOption('output.sourcemapFile', URL_OUTPUT_SOURCEMAPFILE, '"output.sourcemapFile" is only supported for single-file builds'));
  18478. if (!outputOptions.amd.autoId && outputOptions.amd.id)
  18479. log(LOGLEVEL_WARN, logInvalidOption('output.amd.id', URL_OUTPUT_AMD_ID, 'this option is only properly supported for single-file builds. Use "output.amd.autoId" and "output.amd.basePath" instead'));
  18480. }
  18481. function getIncludedModules(modulesById) {
  18482. const includedModules = [];
  18483. for (const module of modulesById.values()) {
  18484. if (module instanceof Module &&
  18485. (module.isIncluded() || module.info.isEntry || module.includedDynamicImporters.length > 0)) {
  18486. includedModules.push(module);
  18487. }
  18488. }
  18489. return includedModules;
  18490. }
  18491. function getAbsoluteEntryModulePaths(includedModules, preserveModules) {
  18492. const absoluteEntryModulePaths = [];
  18493. for (const module of includedModules) {
  18494. if ((module.info.isEntry || preserveModules) && isAbsolute(module.id)) {
  18495. absoluteEntryModulePaths.push(module.id);
  18496. }
  18497. }
  18498. return absoluteEntryModulePaths;
  18499. }
  18500. function getExternalChunkByModule(modulesById, outputOptions, inputBase) {
  18501. const externalChunkByModule = new Map();
  18502. for (const module of modulesById.values()) {
  18503. if (module instanceof ExternalModule) {
  18504. externalChunkByModule.set(module, new ExternalChunk(module, outputOptions, inputBase));
  18505. }
  18506. }
  18507. return externalChunkByModule;
  18508. }
  18509. function addModuleToManualChunk(alias, module, manualChunkAliasByEntry) {
  18510. const existingAlias = manualChunkAliasByEntry.get(module);
  18511. if (typeof existingAlias === 'string' && existingAlias !== alias) {
  18512. return error(logCannotAssignModuleToChunk(module.id, alias, existingAlias));
  18513. }
  18514. manualChunkAliasByEntry.set(module, alias);
  18515. }
  18516. // This file was generated. Do not modify manually!
  18517. var astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 370, 1, 81, 2, 71, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 3, 0, 158, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 10, 1, 2, 0, 49, 6, 4, 4, 14, 9, 5351, 0, 7, 14, 13835, 9, 87, 9, 39, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4706, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 983, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];
  18518. // This file was generated. Do not modify manually!
  18519. var astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 68, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 20, 1, 64, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 4026, 582, 8634, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8936, 3, 2, 6, 2, 1, 2, 290, 16, 0, 30, 2, 3, 0, 15, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 757, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4153, 7, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938, 6, 4191];
  18520. // This file was generated. Do not modify manually!
  18521. var nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0898-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0cf3\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ece\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f";
  18522. // This file was generated. Do not modify manually!
  18523. var nonASCIIidentifierStartChars = "\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\u0560-\u0588\u05d0-\u05ea\u05ef-\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\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\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\u09fc\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\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\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-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\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-\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-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7ca\ua7d0\ua7d1\ua7d3\ua7d5-\ua7d9\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\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-\uab69\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";
  18524. // These are a run-length and offset encoded representation of the
  18525. // >0xffff code points that are a valid part of identifiers. The
  18526. // offset starts at 0x10000, and each pair of numbers represents an
  18527. // offset to the next range, and then a size of the range.
  18528. // Reserved word lists for various dialects of the language
  18529. var reservedWords = {
  18530. 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",
  18531. 5: "class enum extends super const export import",
  18532. 6: "enum",
  18533. strict: "implements interface let package private protected public static yield",
  18534. strictBind: "eval arguments"
  18535. };
  18536. // And the keywords
  18537. var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";
  18538. var keywords$1 = {
  18539. 5: ecma5AndLessKeywords,
  18540. "5module": ecma5AndLessKeywords + " export import",
  18541. 6: ecma5AndLessKeywords + " const class extends export import super"
  18542. };
  18543. var keywordRelationalOperator = /^in(stanceof)?$/;
  18544. // ## Character categories
  18545. var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  18546. var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  18547. // This has a complexity linear to the value of the code. The
  18548. // assumption is that looking up astral identifier characters is
  18549. // rare.
  18550. function isInAstralSet(code, set) {
  18551. var pos = 0x10000;
  18552. for (var i = 0; i < set.length; i += 2) {
  18553. pos += set[i];
  18554. if (pos > code) { return false }
  18555. pos += set[i + 1];
  18556. if (pos >= code) { return true }
  18557. }
  18558. return false
  18559. }
  18560. // Test whether a given character code starts an identifier.
  18561. function isIdentifierStart(code, astral) {
  18562. if (code < 65) { return code === 36 }
  18563. if (code < 91) { return true }
  18564. if (code < 97) { return code === 95 }
  18565. if (code < 123) { return true }
  18566. if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) }
  18567. if (astral === false) { return false }
  18568. return isInAstralSet(code, astralIdentifierStartCodes)
  18569. }
  18570. // Test whether a given character is part of an identifier.
  18571. function isIdentifierChar(code, astral) {
  18572. if (code < 48) { return code === 36 }
  18573. if (code < 58) { return true }
  18574. if (code < 65) { return false }
  18575. if (code < 91) { return true }
  18576. if (code < 97) { return code === 95 }
  18577. if (code < 123) { return true }
  18578. if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) }
  18579. if (astral === false) { return false }
  18580. return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes)
  18581. }
  18582. // ## Token types
  18583. // The assignment of fine-grained, information-carrying type objects
  18584. // allows the tokenizer to store the information it has about a
  18585. // token in a way that is very cheap for the parser to look up.
  18586. // All token type variables start with an underscore, to make them
  18587. // easy to recognize.
  18588. // The `beforeExpr` property is used to disambiguate between regular
  18589. // expressions and divisions. It is set on all token types that can
  18590. // be followed by an expression (thus, a slash after them would be a
  18591. // regular expression).
  18592. //
  18593. // The `startsExpr` property is used to check if the token ends a
  18594. // `yield` expression. It is set on all token types that either can
  18595. // directly start an expression (like a quotation mark) or can
  18596. // continue an expression (like the body of a string).
  18597. //
  18598. // `isLoop` marks a keyword as starting a loop, which is important
  18599. // to know when parsing a label, in order to allow or disallow
  18600. // continue jumps to that label.
  18601. var TokenType = function TokenType(label, conf) {
  18602. if ( conf === void 0 ) conf = {};
  18603. this.label = label;
  18604. this.keyword = conf.keyword;
  18605. this.beforeExpr = !!conf.beforeExpr;
  18606. this.startsExpr = !!conf.startsExpr;
  18607. this.isLoop = !!conf.isLoop;
  18608. this.isAssign = !!conf.isAssign;
  18609. this.prefix = !!conf.prefix;
  18610. this.postfix = !!conf.postfix;
  18611. this.binop = conf.binop || null;
  18612. this.updateContext = null;
  18613. };
  18614. function binop(name, prec) {
  18615. return new TokenType(name, {beforeExpr: true, binop: prec})
  18616. }
  18617. var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true};
  18618. // Map keyword names to token types.
  18619. var keywords = {};
  18620. // Succinct definitions of keyword token types
  18621. function kw(name, options) {
  18622. if ( options === void 0 ) options = {};
  18623. options.keyword = name;
  18624. return keywords[name] = new TokenType(name, options)
  18625. }
  18626. var types$1 = {
  18627. num: new TokenType("num", startsExpr),
  18628. regexp: new TokenType("regexp", startsExpr),
  18629. string: new TokenType("string", startsExpr),
  18630. name: new TokenType("name", startsExpr),
  18631. privateId: new TokenType("privateId", startsExpr),
  18632. eof: new TokenType("eof"),
  18633. // Punctuation token types.
  18634. bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}),
  18635. bracketR: new TokenType("]"),
  18636. braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}),
  18637. braceR: new TokenType("}"),
  18638. parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}),
  18639. parenR: new TokenType(")"),
  18640. comma: new TokenType(",", beforeExpr),
  18641. semi: new TokenType(";", beforeExpr),
  18642. colon: new TokenType(":", beforeExpr),
  18643. dot: new TokenType("."),
  18644. question: new TokenType("?", beforeExpr),
  18645. questionDot: new TokenType("?."),
  18646. arrow: new TokenType("=>", beforeExpr),
  18647. template: new TokenType("template"),
  18648. invalidTemplate: new TokenType("invalidTemplate"),
  18649. ellipsis: new TokenType("...", beforeExpr),
  18650. backQuote: new TokenType("`", startsExpr),
  18651. dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}),
  18652. // Operators. These carry several kinds of properties to help the
  18653. // parser use them properly (the presence of these properties is
  18654. // what categorizes them as operators).
  18655. //
  18656. // `binop`, when present, specifies that this operator is a binary
  18657. // operator, and will refer to its precedence.
  18658. //
  18659. // `prefix` and `postfix` mark the operator as a prefix or postfix
  18660. // unary operator.
  18661. //
  18662. // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
  18663. // binary operators with a very low precedence, that should result
  18664. // in AssignmentExpression nodes.
  18665. eq: new TokenType("=", {beforeExpr: true, isAssign: true}),
  18666. assign: new TokenType("_=", {beforeExpr: true, isAssign: true}),
  18667. incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}),
  18668. prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}),
  18669. logicalOR: binop("||", 1),
  18670. logicalAND: binop("&&", 2),
  18671. bitwiseOR: binop("|", 3),
  18672. bitwiseXOR: binop("^", 4),
  18673. bitwiseAND: binop("&", 5),
  18674. equality: binop("==/!=/===/!==", 6),
  18675. relational: binop("</>/<=/>=", 7),
  18676. bitShift: binop("<</>>/>>>", 8),
  18677. plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}),
  18678. modulo: binop("%", 10),
  18679. star: binop("*", 10),
  18680. slash: binop("/", 10),
  18681. starstar: new TokenType("**", {beforeExpr: true}),
  18682. coalesce: binop("??", 1),
  18683. // Keyword token types.
  18684. _break: kw("break"),
  18685. _case: kw("case", beforeExpr),
  18686. _catch: kw("catch"),
  18687. _continue: kw("continue"),
  18688. _debugger: kw("debugger"),
  18689. _default: kw("default", beforeExpr),
  18690. _do: kw("do", {isLoop: true, beforeExpr: true}),
  18691. _else: kw("else", beforeExpr),
  18692. _finally: kw("finally"),
  18693. _for: kw("for", {isLoop: true}),
  18694. _function: kw("function", startsExpr),
  18695. _if: kw("if"),
  18696. _return: kw("return", beforeExpr),
  18697. _switch: kw("switch"),
  18698. _throw: kw("throw", beforeExpr),
  18699. _try: kw("try"),
  18700. _var: kw("var"),
  18701. _const: kw("const"),
  18702. _while: kw("while", {isLoop: true}),
  18703. _with: kw("with"),
  18704. _new: kw("new", {beforeExpr: true, startsExpr: true}),
  18705. _this: kw("this", startsExpr),
  18706. _super: kw("super", startsExpr),
  18707. _class: kw("class", startsExpr),
  18708. _extends: kw("extends", beforeExpr),
  18709. _export: kw("export"),
  18710. _import: kw("import", startsExpr),
  18711. _null: kw("null", startsExpr),
  18712. _true: kw("true", startsExpr),
  18713. _false: kw("false", startsExpr),
  18714. _in: kw("in", {beforeExpr: true, binop: 7}),
  18715. _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}),
  18716. _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}),
  18717. _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}),
  18718. _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true})
  18719. };
  18720. // Matches a whole line break (where CRLF is considered a single
  18721. // line break). Used to count lines.
  18722. var lineBreak = /\r\n?|\n|\u2028|\u2029/;
  18723. var lineBreakG = new RegExp(lineBreak.source, "g");
  18724. function isNewLine(code) {
  18725. return code === 10 || code === 13 || code === 0x2028 || code === 0x2029
  18726. }
  18727. function nextLineBreak(code, from, end) {
  18728. if ( end === void 0 ) end = code.length;
  18729. for (var i = from; i < end; i++) {
  18730. var next = code.charCodeAt(i);
  18731. if (isNewLine(next))
  18732. { return i < end - 1 && next === 13 && code.charCodeAt(i + 1) === 10 ? i + 2 : i + 1 }
  18733. }
  18734. return -1
  18735. }
  18736. var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
  18737. var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
  18738. var ref = Object.prototype;
  18739. var hasOwnProperty = ref.hasOwnProperty;
  18740. var toString = ref.toString;
  18741. var hasOwn = Object.hasOwn || (function (obj, propName) { return (
  18742. hasOwnProperty.call(obj, propName)
  18743. ); });
  18744. var isArray = Array.isArray || (function (obj) { return (
  18745. toString.call(obj) === "[object Array]"
  18746. ); });
  18747. function wordsRegexp(words) {
  18748. return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$")
  18749. }
  18750. function codePointToString(code) {
  18751. // UTF-16 Decoding
  18752. if (code <= 0xFFFF) { return String.fromCharCode(code) }
  18753. code -= 0x10000;
  18754. return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00)
  18755. }
  18756. var loneSurrogate = /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/;
  18757. // These are used when `options.locations` is on, for the
  18758. // `startLoc` and `endLoc` properties.
  18759. var Position = function Position(line, col) {
  18760. this.line = line;
  18761. this.column = col;
  18762. };
  18763. Position.prototype.offset = function offset (n) {
  18764. return new Position(this.line, this.column + n)
  18765. };
  18766. var SourceLocation = function SourceLocation(p, start, end) {
  18767. this.start = start;
  18768. this.end = end;
  18769. if (p.sourceFile !== null) { this.source = p.sourceFile; }
  18770. };
  18771. // The `getLineInfo` function is mostly useful when the
  18772. // `locations` option is off (for performance reasons) and you
  18773. // want to find the line/column position for a given character
  18774. // offset. `input` should be the code string that the offset refers
  18775. // into.
  18776. function getLineInfo(input, offset) {
  18777. for (var line = 1, cur = 0;;) {
  18778. var nextBreak = nextLineBreak(input, cur, offset);
  18779. if (nextBreak < 0) { return new Position(line, offset - cur) }
  18780. ++line;
  18781. cur = nextBreak;
  18782. }
  18783. }
  18784. // A second argument must be given to configure the parser process.
  18785. // These options are recognized (only `ecmaVersion` is required):
  18786. var defaultOptions = {
  18787. // `ecmaVersion` indicates the ECMAScript version to parse. Must be
  18788. // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10
  18789. // (2019), 11 (2020), 12 (2021), 13 (2022), 14 (2023), or `"latest"`
  18790. // (the latest version the library supports). This influences
  18791. // support for strict mode, the set of reserved words, and support
  18792. // for new syntax features.
  18793. ecmaVersion: null,
  18794. // `sourceType` indicates the mode the code should be parsed in.
  18795. // Can be either `"script"` or `"module"`. This influences global
  18796. // strict mode and parsing of `import` and `export` declarations.
  18797. sourceType: "script",
  18798. // `onInsertedSemicolon` can be a callback that will be called
  18799. // when a semicolon is automatically inserted. It will be passed
  18800. // the position of the comma as an offset, and if `locations` is
  18801. // enabled, it is given the location as a `{line, column}` object
  18802. // as second argument.
  18803. onInsertedSemicolon: null,
  18804. // `onTrailingComma` is similar to `onInsertedSemicolon`, but for
  18805. // trailing commas.
  18806. onTrailingComma: null,
  18807. // By default, reserved words are only enforced if ecmaVersion >= 5.
  18808. // Set `allowReserved` to a boolean value to explicitly turn this on
  18809. // an off. When this option has the value "never", reserved words
  18810. // and keywords can also not be used as property names.
  18811. allowReserved: null,
  18812. // When enabled, a return at the top level is not considered an
  18813. // error.
  18814. allowReturnOutsideFunction: false,
  18815. // When enabled, import/export statements are not constrained to
  18816. // appearing at the top of the program, and an import.meta expression
  18817. // in a script isn't considered an error.
  18818. allowImportExportEverywhere: false,
  18819. // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022.
  18820. // When enabled, await identifiers are allowed to appear at the top-level scope,
  18821. // but they are still not allowed in non-async functions.
  18822. allowAwaitOutsideFunction: null,
  18823. // When enabled, super identifiers are not constrained to
  18824. // appearing in methods and do not raise an error when they appear elsewhere.
  18825. allowSuperOutsideMethod: null,
  18826. // When enabled, hashbang directive in the beginning of file is
  18827. // allowed and treated as a line comment. Enabled by default when
  18828. // `ecmaVersion` >= 2023.
  18829. allowHashBang: false,
  18830. // By default, the parser will verify that private properties are
  18831. // only used in places where they are valid and have been declared.
  18832. // Set this to false to turn such checks off.
  18833. checkPrivateFields: true,
  18834. // When `locations` is on, `loc` properties holding objects with
  18835. // `start` and `end` properties in `{line, column}` form (with
  18836. // line being 1-based and column 0-based) will be attached to the
  18837. // nodes.
  18838. locations: false,
  18839. // A function can be passed as `onToken` option, which will
  18840. // cause Acorn to call that function with object in the same
  18841. // format as tokens returned from `tokenizer().getToken()`. Note
  18842. // that you are not allowed to call the parser from the
  18843. // callback—that will corrupt its internal state.
  18844. onToken: null,
  18845. // A function can be passed as `onComment` option, which will
  18846. // cause Acorn to call that function with `(block, text, start,
  18847. // end)` parameters whenever a comment is skipped. `block` is a
  18848. // boolean indicating whether this is a block (`/* */`) comment,
  18849. // `text` is the content of the comment, and `start` and `end` are
  18850. // character offsets that denote the start and end of the comment.
  18851. // When the `locations` option is on, two more parameters are
  18852. // passed, the full `{line, column}` locations of the start and
  18853. // end of the comments. Note that you are not allowed to call the
  18854. // parser from the callback—that will corrupt its internal state.
  18855. onComment: null,
  18856. // Nodes have their start and end characters offsets recorded in
  18857. // `start` and `end` properties (directly on the node, rather than
  18858. // the `loc` object, which holds line/column data. To also add a
  18859. // [semi-standardized][range] `range` property holding a `[start,
  18860. // end]` array with the same numbers, set the `ranges` option to
  18861. // `true`.
  18862. //
  18863. // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
  18864. ranges: false,
  18865. // It is possible to parse multiple files into a single AST by
  18866. // passing the tree produced by parsing the first file as
  18867. // `program` option in subsequent parses. This will add the
  18868. // toplevel forms of the parsed file to the `Program` (top) node
  18869. // of an existing parse tree.
  18870. program: null,
  18871. // When `locations` is on, you can pass this to record the source
  18872. // file in every node's `loc` object.
  18873. sourceFile: null,
  18874. // This value, if given, is stored in every node, whether
  18875. // `locations` is on or off.
  18876. directSourceFile: null,
  18877. // When enabled, parenthesized expressions are represented by
  18878. // (non-standard) ParenthesizedExpression nodes
  18879. preserveParens: false
  18880. };
  18881. // Interpret and default an options object
  18882. var warnedAboutEcmaVersion = false;
  18883. function getOptions(opts) {
  18884. var options = {};
  18885. for (var opt in defaultOptions)
  18886. { options[opt] = opts && hasOwn(opts, opt) ? opts[opt] : defaultOptions[opt]; }
  18887. if (options.ecmaVersion === "latest") {
  18888. options.ecmaVersion = 1e8;
  18889. } else if (options.ecmaVersion == null) {
  18890. if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) {
  18891. warnedAboutEcmaVersion = true;
  18892. console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.");
  18893. }
  18894. options.ecmaVersion = 11;
  18895. } else if (options.ecmaVersion >= 2015) {
  18896. options.ecmaVersion -= 2009;
  18897. }
  18898. if (options.allowReserved == null)
  18899. { options.allowReserved = options.ecmaVersion < 5; }
  18900. if (!opts || opts.allowHashBang == null)
  18901. { options.allowHashBang = options.ecmaVersion >= 14; }
  18902. if (isArray(options.onToken)) {
  18903. var tokens = options.onToken;
  18904. options.onToken = function (token) { return tokens.push(token); };
  18905. }
  18906. if (isArray(options.onComment))
  18907. { options.onComment = pushComment(options, options.onComment); }
  18908. return options
  18909. }
  18910. function pushComment(options, array) {
  18911. return function(block, text, start, end, startLoc, endLoc) {
  18912. var comment = {
  18913. type: block ? "Block" : "Line",
  18914. value: text,
  18915. start: start,
  18916. end: end
  18917. };
  18918. if (options.locations)
  18919. { comment.loc = new SourceLocation(this, startLoc, endLoc); }
  18920. if (options.ranges)
  18921. { comment.range = [start, end]; }
  18922. array.push(comment);
  18923. }
  18924. }
  18925. // Each scope gets a bitset that may contain these flags
  18926. var
  18927. SCOPE_TOP = 1,
  18928. SCOPE_FUNCTION = 2,
  18929. SCOPE_ASYNC = 4,
  18930. SCOPE_GENERATOR = 8,
  18931. SCOPE_ARROW = 16,
  18932. SCOPE_SIMPLE_CATCH = 32,
  18933. SCOPE_SUPER = 64,
  18934. SCOPE_DIRECT_SUPER = 128,
  18935. SCOPE_CLASS_STATIC_BLOCK = 256,
  18936. SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK;
  18937. function functionFlags(async, generator) {
  18938. return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0)
  18939. }
  18940. // Used in checkLVal* and declareName to determine the type of a binding
  18941. var
  18942. BIND_NONE = 0, // Not a binding
  18943. BIND_VAR = 1, // Var-style binding
  18944. BIND_LEXICAL = 2, // Let- or const-style binding
  18945. BIND_FUNCTION = 3, // Function declaration
  18946. BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding
  18947. BIND_OUTSIDE = 5; // Special case for function names as bound inside the function
  18948. var Parser = function Parser(options, input, startPos) {
  18949. this.options = options = getOptions(options);
  18950. this.sourceFile = options.sourceFile;
  18951. this.keywords = wordsRegexp(keywords$1[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);
  18952. var reserved = "";
  18953. if (options.allowReserved !== true) {
  18954. reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3];
  18955. if (options.sourceType === "module") { reserved += " await"; }
  18956. }
  18957. this.reservedWords = wordsRegexp(reserved);
  18958. var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict;
  18959. this.reservedWordsStrict = wordsRegexp(reservedStrict);
  18960. this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind);
  18961. this.input = String(input);
  18962. // Used to signal to callers of `readWord1` whether the word
  18963. // contained any escape sequences. This is needed because words with
  18964. // escape sequences must not be interpreted as keywords.
  18965. this.containsEsc = false;
  18966. // Set up token state
  18967. // The current position of the tokenizer in the input.
  18968. if (startPos) {
  18969. this.pos = startPos;
  18970. this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;
  18971. this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;
  18972. } else {
  18973. this.pos = this.lineStart = 0;
  18974. this.curLine = 1;
  18975. }
  18976. // Properties of the current token:
  18977. // Its type
  18978. this.type = types$1.eof;
  18979. // For tokens that include more information than their type, the value
  18980. this.value = null;
  18981. // Its start and end offset
  18982. this.start = this.end = this.pos;
  18983. // And, if locations are used, the {line, column} object
  18984. // corresponding to those offsets
  18985. this.startLoc = this.endLoc = this.curPosition();
  18986. // Position information for the previous token
  18987. this.lastTokEndLoc = this.lastTokStartLoc = null;
  18988. this.lastTokStart = this.lastTokEnd = this.pos;
  18989. // The context stack is used to superficially track syntactic
  18990. // context to predict whether a regular expression is allowed in a
  18991. // given position.
  18992. this.context = this.initialContext();
  18993. this.exprAllowed = true;
  18994. // Figure out if it's a module code.
  18995. this.inModule = options.sourceType === "module";
  18996. this.strict = this.inModule || this.strictDirective(this.pos);
  18997. // Used to signify the start of a potential arrow function
  18998. this.potentialArrowAt = -1;
  18999. this.potentialArrowInForAwait = false;
  19000. // Positions to delayed-check that yield/await does not exist in default parameters.
  19001. this.yieldPos = this.awaitPos = this.awaitIdentPos = 0;
  19002. // Labels in scope.
  19003. this.labels = [];
  19004. // Thus-far undefined exports.
  19005. this.undefinedExports = Object.create(null);
  19006. // If enabled, skip leading hashbang line.
  19007. if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!")
  19008. { this.skipLineComment(2); }
  19009. // Scope tracking for duplicate variable names (see scope.js)
  19010. this.scopeStack = [];
  19011. this.enterScope(SCOPE_TOP);
  19012. // For RegExp validation
  19013. this.regexpState = null;
  19014. // The stack of private names.
  19015. // Each element has two properties: 'declared' and 'used'.
  19016. // When it exited from the outermost class definition, all used private names must be declared.
  19017. this.privateNameStack = [];
  19018. };
  19019. var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },canAwait: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true },allowNewDotTarget: { configurable: true },inClassStaticBlock: { configurable: true } };
  19020. Parser.prototype.parse = function parse () {
  19021. var node = this.options.program || this.startNode();
  19022. this.nextToken();
  19023. return this.parseTopLevel(node)
  19024. };
  19025. prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 };
  19026. prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 && !this.currentVarScope().inClassFieldInit };
  19027. prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 && !this.currentVarScope().inClassFieldInit };
  19028. prototypeAccessors.canAwait.get = function () {
  19029. for (var i = this.scopeStack.length - 1; i >= 0; i--) {
  19030. var scope = this.scopeStack[i];
  19031. if (scope.inClassFieldInit || scope.flags & SCOPE_CLASS_STATIC_BLOCK) { return false }
  19032. if (scope.flags & SCOPE_FUNCTION) { return (scope.flags & SCOPE_ASYNC) > 0 }
  19033. }
  19034. return (this.inModule && this.options.ecmaVersion >= 13) || this.options.allowAwaitOutsideFunction
  19035. };
  19036. prototypeAccessors.allowSuper.get = function () {
  19037. var ref = this.currentThisScope();
  19038. var flags = ref.flags;
  19039. var inClassFieldInit = ref.inClassFieldInit;
  19040. return (flags & SCOPE_SUPER) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod
  19041. };
  19042. prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 };
  19043. prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) };
  19044. prototypeAccessors.allowNewDotTarget.get = function () {
  19045. var ref = this.currentThisScope();
  19046. var flags = ref.flags;
  19047. var inClassFieldInit = ref.inClassFieldInit;
  19048. return (flags & (SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK)) > 0 || inClassFieldInit
  19049. };
  19050. prototypeAccessors.inClassStaticBlock.get = function () {
  19051. return (this.currentVarScope().flags & SCOPE_CLASS_STATIC_BLOCK) > 0
  19052. };
  19053. Parser.extend = function extend () {
  19054. var plugins = [], len = arguments.length;
  19055. while ( len-- ) plugins[ len ] = arguments[ len ];
  19056. var cls = this;
  19057. for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); }
  19058. return cls
  19059. };
  19060. Parser.parse = function parse (input, options) {
  19061. return new this(options, input).parse()
  19062. };
  19063. Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) {
  19064. var parser = new this(options, input, pos);
  19065. parser.nextToken();
  19066. return parser.parseExpression()
  19067. };
  19068. Parser.tokenizer = function tokenizer (input, options) {
  19069. return new this(options, input)
  19070. };
  19071. Object.defineProperties( Parser.prototype, prototypeAccessors );
  19072. var pp$9 = Parser.prototype;
  19073. // ## Parser utilities
  19074. var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/;
  19075. pp$9.strictDirective = function(start) {
  19076. if (this.options.ecmaVersion < 5) { return false }
  19077. for (;;) {
  19078. // Try to find string literal.
  19079. skipWhiteSpace.lastIndex = start;
  19080. start += skipWhiteSpace.exec(this.input)[0].length;
  19081. var match = literal.exec(this.input.slice(start));
  19082. if (!match) { return false }
  19083. if ((match[1] || match[2]) === "use strict") {
  19084. skipWhiteSpace.lastIndex = start + match[0].length;
  19085. var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length;
  19086. var next = this.input.charAt(end);
  19087. return next === ";" || next === "}" ||
  19088. (lineBreak.test(spaceAfter[0]) &&
  19089. !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "="))
  19090. }
  19091. start += match[0].length;
  19092. // Skip semicolon, if any.
  19093. skipWhiteSpace.lastIndex = start;
  19094. start += skipWhiteSpace.exec(this.input)[0].length;
  19095. if (this.input[start] === ";")
  19096. { start++; }
  19097. }
  19098. };
  19099. // Predicate that tests whether the next token is of the given
  19100. // type, and if yes, consumes it as a side effect.
  19101. pp$9.eat = function(type) {
  19102. if (this.type === type) {
  19103. this.next();
  19104. return true
  19105. } else {
  19106. return false
  19107. }
  19108. };
  19109. // Tests whether parsed token is a contextual keyword.
  19110. pp$9.isContextual = function(name) {
  19111. return this.type === types$1.name && this.value === name && !this.containsEsc
  19112. };
  19113. // Consumes contextual keyword if possible.
  19114. pp$9.eatContextual = function(name) {
  19115. if (!this.isContextual(name)) { return false }
  19116. this.next();
  19117. return true
  19118. };
  19119. // Asserts that following token is given contextual keyword.
  19120. pp$9.expectContextual = function(name) {
  19121. if (!this.eatContextual(name)) { this.unexpected(); }
  19122. };
  19123. // Test whether a semicolon can be inserted at the current position.
  19124. pp$9.canInsertSemicolon = function() {
  19125. return this.type === types$1.eof ||
  19126. this.type === types$1.braceR ||
  19127. lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
  19128. };
  19129. pp$9.insertSemicolon = function() {
  19130. if (this.canInsertSemicolon()) {
  19131. if (this.options.onInsertedSemicolon)
  19132. { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); }
  19133. return true
  19134. }
  19135. };
  19136. // Consume a semicolon, or, failing that, see if we are allowed to
  19137. // pretend that there is a semicolon at this position.
  19138. pp$9.semicolon = function() {
  19139. if (!this.eat(types$1.semi) && !this.insertSemicolon()) { this.unexpected(); }
  19140. };
  19141. pp$9.afterTrailingComma = function(tokType, notNext) {
  19142. if (this.type === tokType) {
  19143. if (this.options.onTrailingComma)
  19144. { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); }
  19145. if (!notNext)
  19146. { this.next(); }
  19147. return true
  19148. }
  19149. };
  19150. // Expect a token of a given type. If found, consume it, otherwise,
  19151. // raise an unexpected token error.
  19152. pp$9.expect = function(type) {
  19153. this.eat(type) || this.unexpected();
  19154. };
  19155. // Raise an unexpected token error.
  19156. pp$9.unexpected = function(pos) {
  19157. this.raise(pos != null ? pos : this.start, "Unexpected token");
  19158. };
  19159. var DestructuringErrors = function DestructuringErrors() {
  19160. this.shorthandAssign =
  19161. this.trailingComma =
  19162. this.parenthesizedAssign =
  19163. this.parenthesizedBind =
  19164. this.doubleProto =
  19165. -1;
  19166. };
  19167. pp$9.checkPatternErrors = function(refDestructuringErrors, isAssign) {
  19168. if (!refDestructuringErrors) { return }
  19169. if (refDestructuringErrors.trailingComma > -1)
  19170. { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); }
  19171. var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;
  19172. if (parens > -1) { this.raiseRecoverable(parens, isAssign ? "Assigning to rvalue" : "Parenthesized pattern"); }
  19173. };
  19174. pp$9.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
  19175. if (!refDestructuringErrors) { return false }
  19176. var shorthandAssign = refDestructuringErrors.shorthandAssign;
  19177. var doubleProto = refDestructuringErrors.doubleProto;
  19178. if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 }
  19179. if (shorthandAssign >= 0)
  19180. { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); }
  19181. if (doubleProto >= 0)
  19182. { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); }
  19183. };
  19184. pp$9.checkYieldAwaitInDefaultParams = function() {
  19185. if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos))
  19186. { this.raise(this.yieldPos, "Yield expression cannot be a default value"); }
  19187. if (this.awaitPos)
  19188. { this.raise(this.awaitPos, "Await expression cannot be a default value"); }
  19189. };
  19190. pp$9.isSimpleAssignTarget = function(expr) {
  19191. if (expr.type === "ParenthesizedExpression")
  19192. { return this.isSimpleAssignTarget(expr.expression) }
  19193. return expr.type === "Identifier" || expr.type === "MemberExpression"
  19194. };
  19195. var pp$8 = Parser.prototype;
  19196. // ### Statement parsing
  19197. // Parse a program. Initializes the parser, reads any number of
  19198. // statements, and wraps them in a Program node. Optionally takes a
  19199. // `program` argument. If present, the statements will be appended
  19200. // to its body instead of creating a new node.
  19201. pp$8.parseTopLevel = function(node) {
  19202. var exports = Object.create(null);
  19203. if (!node.body) { node.body = []; }
  19204. while (this.type !== types$1.eof) {
  19205. var stmt = this.parseStatement(null, true, exports);
  19206. node.body.push(stmt);
  19207. }
  19208. if (this.inModule)
  19209. { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1)
  19210. {
  19211. var name = list[i];
  19212. this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined"));
  19213. } }
  19214. this.adaptDirectivePrologue(node.body);
  19215. this.next();
  19216. node.sourceType = this.options.sourceType;
  19217. return this.finishNode(node, "Program")
  19218. };
  19219. var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"};
  19220. pp$8.isLet = function(context) {
  19221. if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false }
  19222. skipWhiteSpace.lastIndex = this.pos;
  19223. var skip = skipWhiteSpace.exec(this.input);
  19224. var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
  19225. // For ambiguous cases, determine if a LexicalDeclaration (or only a
  19226. // Statement) is allowed here. If context is not empty then only a Statement
  19227. // is allowed. However, `let [` is an explicit negative lookahead for
  19228. // ExpressionStatement, so special-case it first.
  19229. if (nextCh === 91 || nextCh === 92) { return true } // '[', '/'
  19230. if (context) { return false }
  19231. if (nextCh === 123 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } // '{', astral
  19232. if (isIdentifierStart(nextCh, true)) {
  19233. var pos = next + 1;
  19234. while (isIdentifierChar(nextCh = this.input.charCodeAt(pos), true)) { ++pos; }
  19235. if (nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true }
  19236. var ident = this.input.slice(next, pos);
  19237. if (!keywordRelationalOperator.test(ident)) { return true }
  19238. }
  19239. return false
  19240. };
  19241. // check 'async [no LineTerminator here] function'
  19242. // - 'async /*foo*/ function' is OK.
  19243. // - 'async /*\n*/ function' is invalid.
  19244. pp$8.isAsyncFunction = function() {
  19245. if (this.options.ecmaVersion < 8 || !this.isContextual("async"))
  19246. { return false }
  19247. skipWhiteSpace.lastIndex = this.pos;
  19248. var skip = skipWhiteSpace.exec(this.input);
  19249. var next = this.pos + skip[0].length, after;
  19250. return !lineBreak.test(this.input.slice(this.pos, next)) &&
  19251. this.input.slice(next, next + 8) === "function" &&
  19252. (next + 8 === this.input.length ||
  19253. !(isIdentifierChar(after = this.input.charCodeAt(next + 8)) || after > 0xd7ff && after < 0xdc00))
  19254. };
  19255. // Parse a single statement.
  19256. //
  19257. // If expecting a statement and finding a slash operator, parse a
  19258. // regular expression literal. This is to handle cases like
  19259. // `if (foo) /blah/.exec(foo)`, where looking at the previous token
  19260. // does not help.
  19261. pp$8.parseStatement = function(context, topLevel, exports) {
  19262. var starttype = this.type, node = this.startNode(), kind;
  19263. if (this.isLet(context)) {
  19264. starttype = types$1._var;
  19265. kind = "let";
  19266. }
  19267. // Most types of statements are recognized by the keyword they
  19268. // start with. Many are trivial to parse, some require a bit of
  19269. // complexity.
  19270. switch (starttype) {
  19271. case types$1._break: case types$1._continue: return this.parseBreakContinueStatement(node, starttype.keyword)
  19272. case types$1._debugger: return this.parseDebuggerStatement(node)
  19273. case types$1._do: return this.parseDoStatement(node)
  19274. case types$1._for: return this.parseForStatement(node)
  19275. case types$1._function:
  19276. // Function as sole body of either an if statement or a labeled statement
  19277. // works, but not when it is part of a labeled statement that is the sole
  19278. // body of an if statement.
  19279. if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); }
  19280. return this.parseFunctionStatement(node, false, !context)
  19281. case types$1._class:
  19282. if (context) { this.unexpected(); }
  19283. return this.parseClass(node, true)
  19284. case types$1._if: return this.parseIfStatement(node)
  19285. case types$1._return: return this.parseReturnStatement(node)
  19286. case types$1._switch: return this.parseSwitchStatement(node)
  19287. case types$1._throw: return this.parseThrowStatement(node)
  19288. case types$1._try: return this.parseTryStatement(node)
  19289. case types$1._const: case types$1._var:
  19290. kind = kind || this.value;
  19291. if (context && kind !== "var") { this.unexpected(); }
  19292. return this.parseVarStatement(node, kind)
  19293. case types$1._while: return this.parseWhileStatement(node)
  19294. case types$1._with: return this.parseWithStatement(node)
  19295. case types$1.braceL: return this.parseBlock(true, node)
  19296. case types$1.semi: return this.parseEmptyStatement(node)
  19297. case types$1._export:
  19298. case types$1._import:
  19299. if (this.options.ecmaVersion > 10 && starttype === types$1._import) {
  19300. skipWhiteSpace.lastIndex = this.pos;
  19301. var skip = skipWhiteSpace.exec(this.input);
  19302. var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
  19303. if (nextCh === 40 || nextCh === 46) // '(' or '.'
  19304. { return this.parseExpressionStatement(node, this.parseExpression()) }
  19305. }
  19306. if (!this.options.allowImportExportEverywhere) {
  19307. if (!topLevel)
  19308. { this.raise(this.start, "'import' and 'export' may only appear at the top level"); }
  19309. if (!this.inModule)
  19310. { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); }
  19311. }
  19312. return starttype === types$1._import ? this.parseImport(node) : this.parseExport(node, exports)
  19313. // If the statement does not start with a statement keyword or a
  19314. // brace, it's an ExpressionStatement or LabeledStatement. We
  19315. // simply start parsing an expression, and afterwards, if the
  19316. // next token is a colon and the expression was a simple
  19317. // Identifier node, we switch to interpreting it as a label.
  19318. default:
  19319. if (this.isAsyncFunction()) {
  19320. if (context) { this.unexpected(); }
  19321. this.next();
  19322. return this.parseFunctionStatement(node, true, !context)
  19323. }
  19324. var maybeName = this.value, expr = this.parseExpression();
  19325. if (starttype === types$1.name && expr.type === "Identifier" && this.eat(types$1.colon))
  19326. { return this.parseLabeledStatement(node, maybeName, expr, context) }
  19327. else { return this.parseExpressionStatement(node, expr) }
  19328. }
  19329. };
  19330. pp$8.parseBreakContinueStatement = function(node, keyword) {
  19331. var isBreak = keyword === "break";
  19332. this.next();
  19333. if (this.eat(types$1.semi) || this.insertSemicolon()) { node.label = null; }
  19334. else if (this.type !== types$1.name) { this.unexpected(); }
  19335. else {
  19336. node.label = this.parseIdent();
  19337. this.semicolon();
  19338. }
  19339. // Verify that there is an actual destination to break or
  19340. // continue to.
  19341. var i = 0;
  19342. for (; i < this.labels.length; ++i) {
  19343. var lab = this.labels[i];
  19344. if (node.label == null || lab.name === node.label.name) {
  19345. if (lab.kind != null && (isBreak || lab.kind === "loop")) { break }
  19346. if (node.label && isBreak) { break }
  19347. }
  19348. }
  19349. if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); }
  19350. return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement")
  19351. };
  19352. pp$8.parseDebuggerStatement = function(node) {
  19353. this.next();
  19354. this.semicolon();
  19355. return this.finishNode(node, "DebuggerStatement")
  19356. };
  19357. pp$8.parseDoStatement = function(node) {
  19358. this.next();
  19359. this.labels.push(loopLabel);
  19360. node.body = this.parseStatement("do");
  19361. this.labels.pop();
  19362. this.expect(types$1._while);
  19363. node.test = this.parseParenExpression();
  19364. if (this.options.ecmaVersion >= 6)
  19365. { this.eat(types$1.semi); }
  19366. else
  19367. { this.semicolon(); }
  19368. return this.finishNode(node, "DoWhileStatement")
  19369. };
  19370. // Disambiguating between a `for` and a `for`/`in` or `for`/`of`
  19371. // loop is non-trivial. Basically, we have to parse the init `var`
  19372. // statement or expression, disallowing the `in` operator (see
  19373. // the second parameter to `parseExpression`), and then check
  19374. // whether the next token is `in` or `of`. When there is no init
  19375. // part (semicolon immediately after the opening parenthesis), it
  19376. // is a regular `for` loop.
  19377. pp$8.parseForStatement = function(node) {
  19378. this.next();
  19379. var awaitAt = (this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await")) ? this.lastTokStart : -1;
  19380. this.labels.push(loopLabel);
  19381. this.enterScope(0);
  19382. this.expect(types$1.parenL);
  19383. if (this.type === types$1.semi) {
  19384. if (awaitAt > -1) { this.unexpected(awaitAt); }
  19385. return this.parseFor(node, null)
  19386. }
  19387. var isLet = this.isLet();
  19388. if (this.type === types$1._var || this.type === types$1._const || isLet) {
  19389. var init$1 = this.startNode(), kind = isLet ? "let" : this.value;
  19390. this.next();
  19391. this.parseVar(init$1, true, kind);
  19392. this.finishNode(init$1, "VariableDeclaration");
  19393. if ((this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) {
  19394. if (this.options.ecmaVersion >= 9) {
  19395. if (this.type === types$1._in) {
  19396. if (awaitAt > -1) { this.unexpected(awaitAt); }
  19397. } else { node.await = awaitAt > -1; }
  19398. }
  19399. return this.parseForIn(node, init$1)
  19400. }
  19401. if (awaitAt > -1) { this.unexpected(awaitAt); }
  19402. return this.parseFor(node, init$1)
  19403. }
  19404. var startsWithLet = this.isContextual("let"), isForOf = false;
  19405. var refDestructuringErrors = new DestructuringErrors;
  19406. var init = this.parseExpression(awaitAt > -1 ? "await" : true, refDestructuringErrors);
  19407. if (this.type === types$1._in || (isForOf = this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
  19408. if (this.options.ecmaVersion >= 9) {
  19409. if (this.type === types$1._in) {
  19410. if (awaitAt > -1) { this.unexpected(awaitAt); }
  19411. } else { node.await = awaitAt > -1; }
  19412. }
  19413. if (startsWithLet && isForOf) { this.raise(init.start, "The left-hand side of a for-of loop may not start with 'let'."); }
  19414. this.toAssignable(init, false, refDestructuringErrors);
  19415. this.checkLValPattern(init);
  19416. return this.parseForIn(node, init)
  19417. } else {
  19418. this.checkExpressionErrors(refDestructuringErrors, true);
  19419. }
  19420. if (awaitAt > -1) { this.unexpected(awaitAt); }
  19421. return this.parseFor(node, init)
  19422. };
  19423. pp$8.parseFunctionStatement = function(node, isAsync, declarationPosition) {
  19424. this.next();
  19425. return this.parseFunction(node, FUNC_STATEMENT$1 | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync)
  19426. };
  19427. pp$8.parseIfStatement = function(node) {
  19428. this.next();
  19429. node.test = this.parseParenExpression();
  19430. // allow function declarations in branches, but only in non-strict mode
  19431. node.consequent = this.parseStatement("if");
  19432. node.alternate = this.eat(types$1._else) ? this.parseStatement("if") : null;
  19433. return this.finishNode(node, "IfStatement")
  19434. };
  19435. pp$8.parseReturnStatement = function(node) {
  19436. if (!this.inFunction && !this.options.allowReturnOutsideFunction)
  19437. { this.raise(this.start, "'return' outside of function"); }
  19438. this.next();
  19439. // In `return` (and `break`/`continue`), the keywords with
  19440. // optional arguments, we eagerly look for a semicolon or the
  19441. // possibility to insert one.
  19442. if (this.eat(types$1.semi) || this.insertSemicolon()) { node.argument = null; }
  19443. else { node.argument = this.parseExpression(); this.semicolon(); }
  19444. return this.finishNode(node, "ReturnStatement")
  19445. };
  19446. pp$8.parseSwitchStatement = function(node) {
  19447. this.next();
  19448. node.discriminant = this.parseParenExpression();
  19449. node.cases = [];
  19450. this.expect(types$1.braceL);
  19451. this.labels.push(switchLabel);
  19452. this.enterScope(0);
  19453. // Statements under must be grouped (by label) in SwitchCase
  19454. // nodes. `cur` is used to keep the node that we are currently
  19455. // adding statements to.
  19456. var cur;
  19457. for (var sawDefault = false; this.type !== types$1.braceR;) {
  19458. if (this.type === types$1._case || this.type === types$1._default) {
  19459. var isCase = this.type === types$1._case;
  19460. if (cur) { this.finishNode(cur, "SwitchCase"); }
  19461. node.cases.push(cur = this.startNode());
  19462. cur.consequent = [];
  19463. this.next();
  19464. if (isCase) {
  19465. cur.test = this.parseExpression();
  19466. } else {
  19467. if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); }
  19468. sawDefault = true;
  19469. cur.test = null;
  19470. }
  19471. this.expect(types$1.colon);
  19472. } else {
  19473. if (!cur) { this.unexpected(); }
  19474. cur.consequent.push(this.parseStatement(null));
  19475. }
  19476. }
  19477. this.exitScope();
  19478. if (cur) { this.finishNode(cur, "SwitchCase"); }
  19479. this.next(); // Closing brace
  19480. this.labels.pop();
  19481. return this.finishNode(node, "SwitchStatement")
  19482. };
  19483. pp$8.parseThrowStatement = function(node) {
  19484. this.next();
  19485. if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start)))
  19486. { this.raise(this.lastTokEnd, "Illegal newline after throw"); }
  19487. node.argument = this.parseExpression();
  19488. this.semicolon();
  19489. return this.finishNode(node, "ThrowStatement")
  19490. };
  19491. // Reused empty array added for node fields that are always empty.
  19492. var empty$1 = [];
  19493. pp$8.parseCatchClauseParam = function() {
  19494. var param = this.parseBindingAtom();
  19495. var simple = param.type === "Identifier";
  19496. this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0);
  19497. this.checkLValPattern(param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL);
  19498. this.expect(types$1.parenR);
  19499. return param
  19500. };
  19501. pp$8.parseTryStatement = function(node) {
  19502. this.next();
  19503. node.block = this.parseBlock();
  19504. node.handler = null;
  19505. if (this.type === types$1._catch) {
  19506. var clause = this.startNode();
  19507. this.next();
  19508. if (this.eat(types$1.parenL)) {
  19509. clause.param = this.parseCatchClauseParam();
  19510. } else {
  19511. if (this.options.ecmaVersion < 10) { this.unexpected(); }
  19512. clause.param = null;
  19513. this.enterScope(0);
  19514. }
  19515. clause.body = this.parseBlock(false);
  19516. this.exitScope();
  19517. node.handler = this.finishNode(clause, "CatchClause");
  19518. }
  19519. node.finalizer = this.eat(types$1._finally) ? this.parseBlock() : null;
  19520. if (!node.handler && !node.finalizer)
  19521. { this.raise(node.start, "Missing catch or finally clause"); }
  19522. return this.finishNode(node, "TryStatement")
  19523. };
  19524. pp$8.parseVarStatement = function(node, kind, allowMissingInitializer) {
  19525. this.next();
  19526. this.parseVar(node, false, kind, allowMissingInitializer);
  19527. this.semicolon();
  19528. return this.finishNode(node, "VariableDeclaration")
  19529. };
  19530. pp$8.parseWhileStatement = function(node) {
  19531. this.next();
  19532. node.test = this.parseParenExpression();
  19533. this.labels.push(loopLabel);
  19534. node.body = this.parseStatement("while");
  19535. this.labels.pop();
  19536. return this.finishNode(node, "WhileStatement")
  19537. };
  19538. pp$8.parseWithStatement = function(node) {
  19539. if (this.strict) { this.raise(this.start, "'with' in strict mode"); }
  19540. this.next();
  19541. node.object = this.parseParenExpression();
  19542. node.body = this.parseStatement("with");
  19543. return this.finishNode(node, "WithStatement")
  19544. };
  19545. pp$8.parseEmptyStatement = function(node) {
  19546. this.next();
  19547. return this.finishNode(node, "EmptyStatement")
  19548. };
  19549. pp$8.parseLabeledStatement = function(node, maybeName, expr, context) {
  19550. for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1)
  19551. {
  19552. var label = list[i$1];
  19553. if (label.name === maybeName)
  19554. { this.raise(expr.start, "Label '" + maybeName + "' is already declared");
  19555. } }
  19556. var kind = this.type.isLoop ? "loop" : this.type === types$1._switch ? "switch" : null;
  19557. for (var i = this.labels.length - 1; i >= 0; i--) {
  19558. var label$1 = this.labels[i];
  19559. if (label$1.statementStart === node.start) {
  19560. // Update information about previous labels on this node
  19561. label$1.statementStart = this.start;
  19562. label$1.kind = kind;
  19563. } else { break }
  19564. }
  19565. this.labels.push({name: maybeName, kind: kind, statementStart: this.start});
  19566. node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
  19567. this.labels.pop();
  19568. node.label = expr;
  19569. return this.finishNode(node, "LabeledStatement")
  19570. };
  19571. pp$8.parseExpressionStatement = function(node, expr) {
  19572. node.expression = expr;
  19573. this.semicolon();
  19574. return this.finishNode(node, "ExpressionStatement")
  19575. };
  19576. // Parse a semicolon-enclosed block of statements, handling `"use
  19577. // strict"` declarations when `allowStrict` is true (used for
  19578. // function bodies).
  19579. pp$8.parseBlock = function(createNewLexicalScope, node, exitStrict) {
  19580. if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true;
  19581. if ( node === void 0 ) node = this.startNode();
  19582. node.body = [];
  19583. this.expect(types$1.braceL);
  19584. if (createNewLexicalScope) { this.enterScope(0); }
  19585. while (this.type !== types$1.braceR) {
  19586. var stmt = this.parseStatement(null);
  19587. node.body.push(stmt);
  19588. }
  19589. if (exitStrict) { this.strict = false; }
  19590. this.next();
  19591. if (createNewLexicalScope) { this.exitScope(); }
  19592. return this.finishNode(node, "BlockStatement")
  19593. };
  19594. // Parse a regular `for` loop. The disambiguation code in
  19595. // `parseStatement` will already have parsed the init statement or
  19596. // expression.
  19597. pp$8.parseFor = function(node, init) {
  19598. node.init = init;
  19599. this.expect(types$1.semi);
  19600. node.test = this.type === types$1.semi ? null : this.parseExpression();
  19601. this.expect(types$1.semi);
  19602. node.update = this.type === types$1.parenR ? null : this.parseExpression();
  19603. this.expect(types$1.parenR);
  19604. node.body = this.parseStatement("for");
  19605. this.exitScope();
  19606. this.labels.pop();
  19607. return this.finishNode(node, "ForStatement")
  19608. };
  19609. // Parse a `for`/`in` and `for`/`of` loop, which are almost
  19610. // same from parser's perspective.
  19611. pp$8.parseForIn = function(node, init) {
  19612. var isForIn = this.type === types$1._in;
  19613. this.next();
  19614. if (
  19615. init.type === "VariableDeclaration" &&
  19616. init.declarations[0].init != null &&
  19617. (
  19618. !isForIn ||
  19619. this.options.ecmaVersion < 8 ||
  19620. this.strict ||
  19621. init.kind !== "var" ||
  19622. init.declarations[0].id.type !== "Identifier"
  19623. )
  19624. ) {
  19625. this.raise(
  19626. init.start,
  19627. ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer")
  19628. );
  19629. }
  19630. node.left = init;
  19631. node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
  19632. this.expect(types$1.parenR);
  19633. node.body = this.parseStatement("for");
  19634. this.exitScope();
  19635. this.labels.pop();
  19636. return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement")
  19637. };
  19638. // Parse a list of variable declarations.
  19639. pp$8.parseVar = function(node, isFor, kind, allowMissingInitializer) {
  19640. node.declarations = [];
  19641. node.kind = kind;
  19642. for (;;) {
  19643. var decl = this.startNode();
  19644. this.parseVarId(decl, kind);
  19645. if (this.eat(types$1.eq)) {
  19646. decl.init = this.parseMaybeAssign(isFor);
  19647. } else if (!allowMissingInitializer && kind === "const" && !(this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) {
  19648. this.unexpected();
  19649. } else if (!allowMissingInitializer && decl.id.type !== "Identifier" && !(isFor && (this.type === types$1._in || this.isContextual("of")))) {
  19650. this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
  19651. } else {
  19652. decl.init = null;
  19653. }
  19654. node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
  19655. if (!this.eat(types$1.comma)) { break }
  19656. }
  19657. return node
  19658. };
  19659. pp$8.parseVarId = function(decl, kind) {
  19660. decl.id = this.parseBindingAtom();
  19661. this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false);
  19662. };
  19663. var FUNC_STATEMENT$1 = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID$1 = 4;
  19664. // Parse a function declaration or literal (depending on the
  19665. // `statement & FUNC_STATEMENT`).
  19666. // Remove `allowExpressionBody` for 7.0.0, as it is only called with false
  19667. pp$8.parseFunction = function(node, statement, allowExpressionBody, isAsync, forInit) {
  19668. this.initFunction(node);
  19669. if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) {
  19670. if (this.type === types$1.star && (statement & FUNC_HANGING_STATEMENT))
  19671. { this.unexpected(); }
  19672. node.generator = this.eat(types$1.star);
  19673. }
  19674. if (this.options.ecmaVersion >= 8)
  19675. { node.async = !!isAsync; }
  19676. if (statement & FUNC_STATEMENT$1) {
  19677. node.id = (statement & FUNC_NULLABLE_ID$1) && this.type !== types$1.name ? null : this.parseIdent();
  19678. if (node.id && !(statement & FUNC_HANGING_STATEMENT))
  19679. // If it is a regular function declaration in sloppy mode, then it is
  19680. // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding
  19681. // mode depends on properties of the current scope (see
  19682. // treatFunctionsAsVar).
  19683. { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); }
  19684. }
  19685. var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  19686. this.yieldPos = 0;
  19687. this.awaitPos = 0;
  19688. this.awaitIdentPos = 0;
  19689. this.enterScope(functionFlags(node.async, node.generator));
  19690. if (!(statement & FUNC_STATEMENT$1))
  19691. { node.id = this.type === types$1.name ? this.parseIdent() : null; }
  19692. this.parseFunctionParams(node);
  19693. this.parseFunctionBody(node, allowExpressionBody, false, forInit);
  19694. this.yieldPos = oldYieldPos;
  19695. this.awaitPos = oldAwaitPos;
  19696. this.awaitIdentPos = oldAwaitIdentPos;
  19697. return this.finishNode(node, (statement & FUNC_STATEMENT$1) ? "FunctionDeclaration" : "FunctionExpression")
  19698. };
  19699. pp$8.parseFunctionParams = function(node) {
  19700. this.expect(types$1.parenL);
  19701. node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8);
  19702. this.checkYieldAwaitInDefaultParams();
  19703. };
  19704. // Parse a class declaration or literal (depending on the
  19705. // `isStatement` parameter).
  19706. pp$8.parseClass = function(node, isStatement) {
  19707. this.next();
  19708. // ecma-262 14.6 Class Definitions
  19709. // A class definition is always strict mode code.
  19710. var oldStrict = this.strict;
  19711. this.strict = true;
  19712. this.parseClassId(node, isStatement);
  19713. this.parseClassSuper(node);
  19714. var privateNameMap = this.enterClassBody();
  19715. var classBody = this.startNode();
  19716. var hadConstructor = false;
  19717. classBody.body = [];
  19718. this.expect(types$1.braceL);
  19719. while (this.type !== types$1.braceR) {
  19720. var element = this.parseClassElement(node.superClass !== null);
  19721. if (element) {
  19722. classBody.body.push(element);
  19723. if (element.type === "MethodDefinition" && element.kind === "constructor") {
  19724. if (hadConstructor) { this.raiseRecoverable(element.start, "Duplicate constructor in the same class"); }
  19725. hadConstructor = true;
  19726. } else if (element.key && element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) {
  19727. this.raiseRecoverable(element.key.start, ("Identifier '#" + (element.key.name) + "' has already been declared"));
  19728. }
  19729. }
  19730. }
  19731. this.strict = oldStrict;
  19732. this.next();
  19733. node.body = this.finishNode(classBody, "ClassBody");
  19734. this.exitClassBody();
  19735. return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression")
  19736. };
  19737. pp$8.parseClassElement = function(constructorAllowsSuper) {
  19738. if (this.eat(types$1.semi)) { return null }
  19739. var ecmaVersion = this.options.ecmaVersion;
  19740. var node = this.startNode();
  19741. var keyName = "";
  19742. var isGenerator = false;
  19743. var isAsync = false;
  19744. var kind = "method";
  19745. var isStatic = false;
  19746. if (this.eatContextual("static")) {
  19747. // Parse static init block
  19748. if (ecmaVersion >= 13 && this.eat(types$1.braceL)) {
  19749. this.parseClassStaticBlock(node);
  19750. return node
  19751. }
  19752. if (this.isClassElementNameStart() || this.type === types$1.star) {
  19753. isStatic = true;
  19754. } else {
  19755. keyName = "static";
  19756. }
  19757. }
  19758. node.static = isStatic;
  19759. if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) {
  19760. if ((this.isClassElementNameStart() || this.type === types$1.star) && !this.canInsertSemicolon()) {
  19761. isAsync = true;
  19762. } else {
  19763. keyName = "async";
  19764. }
  19765. }
  19766. if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(types$1.star)) {
  19767. isGenerator = true;
  19768. }
  19769. if (!keyName && !isAsync && !isGenerator) {
  19770. var lastValue = this.value;
  19771. if (this.eatContextual("get") || this.eatContextual("set")) {
  19772. if (this.isClassElementNameStart()) {
  19773. kind = lastValue;
  19774. } else {
  19775. keyName = lastValue;
  19776. }
  19777. }
  19778. }
  19779. // Parse element name
  19780. if (keyName) {
  19781. // 'async', 'get', 'set', or 'static' were not a keyword contextually.
  19782. // The last token is any of those. Make it the element name.
  19783. node.computed = false;
  19784. node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc);
  19785. node.key.name = keyName;
  19786. this.finishNode(node.key, "Identifier");
  19787. } else {
  19788. this.parseClassElementName(node);
  19789. }
  19790. // Parse element value
  19791. if (ecmaVersion < 13 || this.type === types$1.parenL || kind !== "method" || isGenerator || isAsync) {
  19792. var isConstructor = !node.static && checkKeyName(node, "constructor");
  19793. var allowsDirectSuper = isConstructor && constructorAllowsSuper;
  19794. // Couldn't move this check into the 'parseClassMethod' method for backward compatibility.
  19795. if (isConstructor && kind !== "method") { this.raise(node.key.start, "Constructor can't have get/set modifier"); }
  19796. node.kind = isConstructor ? "constructor" : kind;
  19797. this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper);
  19798. } else {
  19799. this.parseClassField(node);
  19800. }
  19801. return node
  19802. };
  19803. pp$8.isClassElementNameStart = function() {
  19804. return (
  19805. this.type === types$1.name ||
  19806. this.type === types$1.privateId ||
  19807. this.type === types$1.num ||
  19808. this.type === types$1.string ||
  19809. this.type === types$1.bracketL ||
  19810. this.type.keyword
  19811. )
  19812. };
  19813. pp$8.parseClassElementName = function(element) {
  19814. if (this.type === types$1.privateId) {
  19815. if (this.value === "constructor") {
  19816. this.raise(this.start, "Classes can't have an element named '#constructor'");
  19817. }
  19818. element.computed = false;
  19819. element.key = this.parsePrivateIdent();
  19820. } else {
  19821. this.parsePropertyName(element);
  19822. }
  19823. };
  19824. pp$8.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) {
  19825. // Check key and flags
  19826. var key = method.key;
  19827. if (method.kind === "constructor") {
  19828. if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); }
  19829. if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); }
  19830. } else if (method.static && checkKeyName(method, "prototype")) {
  19831. this.raise(key.start, "Classes may not have a static property named prototype");
  19832. }
  19833. // Parse value
  19834. var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper);
  19835. // Check value
  19836. if (method.kind === "get" && value.params.length !== 0)
  19837. { this.raiseRecoverable(value.start, "getter should have no params"); }
  19838. if (method.kind === "set" && value.params.length !== 1)
  19839. { this.raiseRecoverable(value.start, "setter should have exactly one param"); }
  19840. if (method.kind === "set" && value.params[0].type === "RestElement")
  19841. { this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params"); }
  19842. return this.finishNode(method, "MethodDefinition")
  19843. };
  19844. pp$8.parseClassField = function(field) {
  19845. if (checkKeyName(field, "constructor")) {
  19846. this.raise(field.key.start, "Classes can't have a field named 'constructor'");
  19847. } else if (field.static && checkKeyName(field, "prototype")) {
  19848. this.raise(field.key.start, "Classes can't have a static field named 'prototype'");
  19849. }
  19850. if (this.eat(types$1.eq)) {
  19851. // To raise SyntaxError if 'arguments' exists in the initializer.
  19852. var scope = this.currentThisScope();
  19853. var inClassFieldInit = scope.inClassFieldInit;
  19854. scope.inClassFieldInit = true;
  19855. field.value = this.parseMaybeAssign();
  19856. scope.inClassFieldInit = inClassFieldInit;
  19857. } else {
  19858. field.value = null;
  19859. }
  19860. this.semicolon();
  19861. return this.finishNode(field, "PropertyDefinition")
  19862. };
  19863. pp$8.parseClassStaticBlock = function(node) {
  19864. node.body = [];
  19865. var oldLabels = this.labels;
  19866. this.labels = [];
  19867. this.enterScope(SCOPE_CLASS_STATIC_BLOCK | SCOPE_SUPER);
  19868. while (this.type !== types$1.braceR) {
  19869. var stmt = this.parseStatement(null);
  19870. node.body.push(stmt);
  19871. }
  19872. this.next();
  19873. this.exitScope();
  19874. this.labels = oldLabels;
  19875. return this.finishNode(node, "StaticBlock")
  19876. };
  19877. pp$8.parseClassId = function(node, isStatement) {
  19878. if (this.type === types$1.name) {
  19879. node.id = this.parseIdent();
  19880. if (isStatement)
  19881. { this.checkLValSimple(node.id, BIND_LEXICAL, false); }
  19882. } else {
  19883. if (isStatement === true)
  19884. { this.unexpected(); }
  19885. node.id = null;
  19886. }
  19887. };
  19888. pp$8.parseClassSuper = function(node) {
  19889. node.superClass = this.eat(types$1._extends) ? this.parseExprSubscripts(null, false) : null;
  19890. };
  19891. pp$8.enterClassBody = function() {
  19892. var element = {declared: Object.create(null), used: []};
  19893. this.privateNameStack.push(element);
  19894. return element.declared
  19895. };
  19896. pp$8.exitClassBody = function() {
  19897. var ref = this.privateNameStack.pop();
  19898. var declared = ref.declared;
  19899. var used = ref.used;
  19900. if (!this.options.checkPrivateFields) { return }
  19901. var len = this.privateNameStack.length;
  19902. var parent = len === 0 ? null : this.privateNameStack[len - 1];
  19903. for (var i = 0; i < used.length; ++i) {
  19904. var id = used[i];
  19905. if (!hasOwn(declared, id.name)) {
  19906. if (parent) {
  19907. parent.used.push(id);
  19908. } else {
  19909. this.raiseRecoverable(id.start, ("Private field '#" + (id.name) + "' must be declared in an enclosing class"));
  19910. }
  19911. }
  19912. }
  19913. };
  19914. function isPrivateNameConflicted(privateNameMap, element) {
  19915. var name = element.key.name;
  19916. var curr = privateNameMap[name];
  19917. var next = "true";
  19918. if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) {
  19919. next = (element.static ? "s" : "i") + element.kind;
  19920. }
  19921. // `class { get #a(){}; static set #a(_){} }` is also conflict.
  19922. if (
  19923. curr === "iget" && next === "iset" ||
  19924. curr === "iset" && next === "iget" ||
  19925. curr === "sget" && next === "sset" ||
  19926. curr === "sset" && next === "sget"
  19927. ) {
  19928. privateNameMap[name] = "true";
  19929. return false
  19930. } else if (!curr) {
  19931. privateNameMap[name] = next;
  19932. return false
  19933. } else {
  19934. return true
  19935. }
  19936. }
  19937. function checkKeyName(node, name) {
  19938. var computed = node.computed;
  19939. var key = node.key;
  19940. return !computed && (
  19941. key.type === "Identifier" && key.name === name ||
  19942. key.type === "Literal" && key.value === name
  19943. )
  19944. }
  19945. // Parses module export declaration.
  19946. pp$8.parseExportAllDeclaration = function(node, exports) {
  19947. if (this.options.ecmaVersion >= 11) {
  19948. if (this.eatContextual("as")) {
  19949. node.exported = this.parseModuleExportName();
  19950. this.checkExport(exports, node.exported, this.lastTokStart);
  19951. } else {
  19952. node.exported = null;
  19953. }
  19954. }
  19955. this.expectContextual("from");
  19956. if (this.type !== types$1.string) { this.unexpected(); }
  19957. node.source = this.parseExprAtom();
  19958. this.semicolon();
  19959. return this.finishNode(node, "ExportAllDeclaration")
  19960. };
  19961. pp$8.parseExport = function(node, exports) {
  19962. this.next();
  19963. // export * from '...'
  19964. if (this.eat(types$1.star)) {
  19965. return this.parseExportAllDeclaration(node, exports)
  19966. }
  19967. if (this.eat(types$1._default)) { // export default ...
  19968. this.checkExport(exports, "default", this.lastTokStart);
  19969. node.declaration = this.parseExportDefaultDeclaration();
  19970. return this.finishNode(node, "ExportDefaultDeclaration")
  19971. }
  19972. // export var|const|let|function|class ...
  19973. if (this.shouldParseExportStatement()) {
  19974. node.declaration = this.parseExportDeclaration(node);
  19975. if (node.declaration.type === "VariableDeclaration")
  19976. { this.checkVariableExport(exports, node.declaration.declarations); }
  19977. else
  19978. { this.checkExport(exports, node.declaration.id, node.declaration.id.start); }
  19979. node.specifiers = [];
  19980. node.source = null;
  19981. } else { // export { x, y as z } [from '...']
  19982. node.declaration = null;
  19983. node.specifiers = this.parseExportSpecifiers(exports);
  19984. if (this.eatContextual("from")) {
  19985. if (this.type !== types$1.string) { this.unexpected(); }
  19986. node.source = this.parseExprAtom();
  19987. } else {
  19988. for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
  19989. // check for keywords used as local names
  19990. var spec = list[i];
  19991. this.checkUnreserved(spec.local);
  19992. // check if export is defined
  19993. this.checkLocalExport(spec.local);
  19994. if (spec.local.type === "Literal") {
  19995. this.raise(spec.local.start, "A string literal cannot be used as an exported binding without `from`.");
  19996. }
  19997. }
  19998. node.source = null;
  19999. }
  20000. this.semicolon();
  20001. }
  20002. return this.finishNode(node, "ExportNamedDeclaration")
  20003. };
  20004. pp$8.parseExportDeclaration = function(node) {
  20005. return this.parseStatement(null)
  20006. };
  20007. pp$8.parseExportDefaultDeclaration = function() {
  20008. var isAsync;
  20009. if (this.type === types$1._function || (isAsync = this.isAsyncFunction())) {
  20010. var fNode = this.startNode();
  20011. this.next();
  20012. if (isAsync) { this.next(); }
  20013. return this.parseFunction(fNode, FUNC_STATEMENT$1 | FUNC_NULLABLE_ID$1, false, isAsync)
  20014. } else if (this.type === types$1._class) {
  20015. var cNode = this.startNode();
  20016. return this.parseClass(cNode, "nullableID")
  20017. } else {
  20018. var declaration = this.parseMaybeAssign();
  20019. this.semicolon();
  20020. return declaration
  20021. }
  20022. };
  20023. pp$8.checkExport = function(exports, name, pos) {
  20024. if (!exports) { return }
  20025. if (typeof name !== "string")
  20026. { name = name.type === "Identifier" ? name.name : name.value; }
  20027. if (hasOwn(exports, name))
  20028. { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); }
  20029. exports[name] = true;
  20030. };
  20031. pp$8.checkPatternExport = function(exports, pat) {
  20032. var type = pat.type;
  20033. if (type === "Identifier")
  20034. { this.checkExport(exports, pat, pat.start); }
  20035. else if (type === "ObjectPattern")
  20036. { for (var i = 0, list = pat.properties; i < list.length; i += 1)
  20037. {
  20038. var prop = list[i];
  20039. this.checkPatternExport(exports, prop);
  20040. } }
  20041. else if (type === "ArrayPattern")
  20042. { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) {
  20043. var elt = list$1[i$1];
  20044. if (elt) { this.checkPatternExport(exports, elt); }
  20045. } }
  20046. else if (type === "Property")
  20047. { this.checkPatternExport(exports, pat.value); }
  20048. else if (type === "AssignmentPattern")
  20049. { this.checkPatternExport(exports, pat.left); }
  20050. else if (type === "RestElement")
  20051. { this.checkPatternExport(exports, pat.argument); }
  20052. else if (type === "ParenthesizedExpression")
  20053. { this.checkPatternExport(exports, pat.expression); }
  20054. };
  20055. pp$8.checkVariableExport = function(exports, decls) {
  20056. if (!exports) { return }
  20057. for (var i = 0, list = decls; i < list.length; i += 1)
  20058. {
  20059. var decl = list[i];
  20060. this.checkPatternExport(exports, decl.id);
  20061. }
  20062. };
  20063. pp$8.shouldParseExportStatement = function() {
  20064. return this.type.keyword === "var" ||
  20065. this.type.keyword === "const" ||
  20066. this.type.keyword === "class" ||
  20067. this.type.keyword === "function" ||
  20068. this.isLet() ||
  20069. this.isAsyncFunction()
  20070. };
  20071. // Parses a comma-separated list of module exports.
  20072. pp$8.parseExportSpecifier = function(exports) {
  20073. var node = this.startNode();
  20074. node.local = this.parseModuleExportName();
  20075. node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local;
  20076. this.checkExport(
  20077. exports,
  20078. node.exported,
  20079. node.exported.start
  20080. );
  20081. return this.finishNode(node, "ExportSpecifier")
  20082. };
  20083. pp$8.parseExportSpecifiers = function(exports) {
  20084. var nodes = [], first = true;
  20085. // export { x, y as z } [from '...']
  20086. this.expect(types$1.braceL);
  20087. while (!this.eat(types$1.braceR)) {
  20088. if (!first) {
  20089. this.expect(types$1.comma);
  20090. if (this.afterTrailingComma(types$1.braceR)) { break }
  20091. } else { first = false; }
  20092. nodes.push(this.parseExportSpecifier(exports));
  20093. }
  20094. return nodes
  20095. };
  20096. // Parses import declaration.
  20097. pp$8.parseImport = function(node) {
  20098. this.next();
  20099. // import '...'
  20100. if (this.type === types$1.string) {
  20101. node.specifiers = empty$1;
  20102. node.source = this.parseExprAtom();
  20103. } else {
  20104. node.specifiers = this.parseImportSpecifiers();
  20105. this.expectContextual("from");
  20106. node.source = this.type === types$1.string ? this.parseExprAtom() : this.unexpected();
  20107. }
  20108. this.semicolon();
  20109. return this.finishNode(node, "ImportDeclaration")
  20110. };
  20111. // Parses a comma-separated list of module imports.
  20112. pp$8.parseImportSpecifier = function() {
  20113. var node = this.startNode();
  20114. node.imported = this.parseModuleExportName();
  20115. if (this.eatContextual("as")) {
  20116. node.local = this.parseIdent();
  20117. } else {
  20118. this.checkUnreserved(node.imported);
  20119. node.local = node.imported;
  20120. }
  20121. this.checkLValSimple(node.local, BIND_LEXICAL);
  20122. return this.finishNode(node, "ImportSpecifier")
  20123. };
  20124. pp$8.parseImportDefaultSpecifier = function() {
  20125. // import defaultObj, { x, y as z } from '...'
  20126. var node = this.startNode();
  20127. node.local = this.parseIdent();
  20128. this.checkLValSimple(node.local, BIND_LEXICAL);
  20129. return this.finishNode(node, "ImportDefaultSpecifier")
  20130. };
  20131. pp$8.parseImportNamespaceSpecifier = function() {
  20132. var node = this.startNode();
  20133. this.next();
  20134. this.expectContextual("as");
  20135. node.local = this.parseIdent();
  20136. this.checkLValSimple(node.local, BIND_LEXICAL);
  20137. return this.finishNode(node, "ImportNamespaceSpecifier")
  20138. };
  20139. pp$8.parseImportSpecifiers = function() {
  20140. var nodes = [], first = true;
  20141. if (this.type === types$1.name) {
  20142. nodes.push(this.parseImportDefaultSpecifier());
  20143. if (!this.eat(types$1.comma)) { return nodes }
  20144. }
  20145. if (this.type === types$1.star) {
  20146. nodes.push(this.parseImportNamespaceSpecifier());
  20147. return nodes
  20148. }
  20149. this.expect(types$1.braceL);
  20150. while (!this.eat(types$1.braceR)) {
  20151. if (!first) {
  20152. this.expect(types$1.comma);
  20153. if (this.afterTrailingComma(types$1.braceR)) { break }
  20154. } else { first = false; }
  20155. nodes.push(this.parseImportSpecifier());
  20156. }
  20157. return nodes
  20158. };
  20159. pp$8.parseModuleExportName = function() {
  20160. if (this.options.ecmaVersion >= 13 && this.type === types$1.string) {
  20161. var stringLiteral = this.parseLiteral(this.value);
  20162. if (loneSurrogate.test(stringLiteral.value)) {
  20163. this.raise(stringLiteral.start, "An export name cannot include a lone surrogate.");
  20164. }
  20165. return stringLiteral
  20166. }
  20167. return this.parseIdent(true)
  20168. };
  20169. // Set `ExpressionStatement#directive` property for directive prologues.
  20170. pp$8.adaptDirectivePrologue = function(statements) {
  20171. for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) {
  20172. statements[i].directive = statements[i].expression.raw.slice(1, -1);
  20173. }
  20174. };
  20175. pp$8.isDirectiveCandidate = function(statement) {
  20176. return (
  20177. this.options.ecmaVersion >= 5 &&
  20178. statement.type === "ExpressionStatement" &&
  20179. statement.expression.type === "Literal" &&
  20180. typeof statement.expression.value === "string" &&
  20181. // Reject parenthesized strings.
  20182. (this.input[statement.start] === "\"" || this.input[statement.start] === "'")
  20183. )
  20184. };
  20185. var pp$7 = Parser.prototype;
  20186. // Convert existing expression atom to assignable pattern
  20187. // if possible.
  20188. pp$7.toAssignable = function(node, isBinding, refDestructuringErrors) {
  20189. if (this.options.ecmaVersion >= 6 && node) {
  20190. switch (node.type) {
  20191. case "Identifier":
  20192. if (this.inAsync && node.name === "await")
  20193. { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); }
  20194. break
  20195. case "ObjectPattern":
  20196. case "ArrayPattern":
  20197. case "AssignmentPattern":
  20198. case "RestElement":
  20199. break
  20200. case "ObjectExpression":
  20201. node.type = "ObjectPattern";
  20202. if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  20203. for (var i = 0, list = node.properties; i < list.length; i += 1) {
  20204. var prop = list[i];
  20205. this.toAssignable(prop, isBinding);
  20206. // Early error:
  20207. // AssignmentRestProperty[Yield, Await] :
  20208. // `...` DestructuringAssignmentTarget[Yield, Await]
  20209. //
  20210. // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|.
  20211. if (
  20212. prop.type === "RestElement" &&
  20213. (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")
  20214. ) {
  20215. this.raise(prop.argument.start, "Unexpected token");
  20216. }
  20217. }
  20218. break
  20219. case "Property":
  20220. // AssignmentProperty has type === "Property"
  20221. if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); }
  20222. this.toAssignable(node.value, isBinding);
  20223. break
  20224. case "ArrayExpression":
  20225. node.type = "ArrayPattern";
  20226. if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  20227. this.toAssignableList(node.elements, isBinding);
  20228. break
  20229. case "SpreadElement":
  20230. node.type = "RestElement";
  20231. this.toAssignable(node.argument, isBinding);
  20232. if (node.argument.type === "AssignmentPattern")
  20233. { this.raise(node.argument.start, "Rest elements cannot have a default value"); }
  20234. break
  20235. case "AssignmentExpression":
  20236. if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); }
  20237. node.type = "AssignmentPattern";
  20238. delete node.operator;
  20239. this.toAssignable(node.left, isBinding);
  20240. break
  20241. case "ParenthesizedExpression":
  20242. this.toAssignable(node.expression, isBinding, refDestructuringErrors);
  20243. break
  20244. case "ChainExpression":
  20245. this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side");
  20246. break
  20247. case "MemberExpression":
  20248. if (!isBinding) { break }
  20249. default:
  20250. this.raise(node.start, "Assigning to rvalue");
  20251. }
  20252. } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  20253. return node
  20254. };
  20255. // Convert list of expression atoms to binding list.
  20256. pp$7.toAssignableList = function(exprList, isBinding) {
  20257. var end = exprList.length;
  20258. for (var i = 0; i < end; i++) {
  20259. var elt = exprList[i];
  20260. if (elt) { this.toAssignable(elt, isBinding); }
  20261. }
  20262. if (end) {
  20263. var last = exprList[end - 1];
  20264. if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier")
  20265. { this.unexpected(last.argument.start); }
  20266. }
  20267. return exprList
  20268. };
  20269. // Parses spread element.
  20270. pp$7.parseSpread = function(refDestructuringErrors) {
  20271. var node = this.startNode();
  20272. this.next();
  20273. node.argument = this.parseMaybeAssign(false, refDestructuringErrors);
  20274. return this.finishNode(node, "SpreadElement")
  20275. };
  20276. pp$7.parseRestBinding = function() {
  20277. var node = this.startNode();
  20278. this.next();
  20279. // RestElement inside of a function parameter must be an identifier
  20280. if (this.options.ecmaVersion === 6 && this.type !== types$1.name)
  20281. { this.unexpected(); }
  20282. node.argument = this.parseBindingAtom();
  20283. return this.finishNode(node, "RestElement")
  20284. };
  20285. // Parses lvalue (assignable) atom.
  20286. pp$7.parseBindingAtom = function() {
  20287. if (this.options.ecmaVersion >= 6) {
  20288. switch (this.type) {
  20289. case types$1.bracketL:
  20290. var node = this.startNode();
  20291. this.next();
  20292. node.elements = this.parseBindingList(types$1.bracketR, true, true);
  20293. return this.finishNode(node, "ArrayPattern")
  20294. case types$1.braceL:
  20295. return this.parseObj(true)
  20296. }
  20297. }
  20298. return this.parseIdent()
  20299. };
  20300. pp$7.parseBindingList = function(close, allowEmpty, allowTrailingComma, allowModifiers) {
  20301. var elts = [], first = true;
  20302. while (!this.eat(close)) {
  20303. if (first) { first = false; }
  20304. else { this.expect(types$1.comma); }
  20305. if (allowEmpty && this.type === types$1.comma) {
  20306. elts.push(null);
  20307. } else if (allowTrailingComma && this.afterTrailingComma(close)) {
  20308. break
  20309. } else if (this.type === types$1.ellipsis) {
  20310. var rest = this.parseRestBinding();
  20311. this.parseBindingListItem(rest);
  20312. elts.push(rest);
  20313. if (this.type === types$1.comma) { this.raiseRecoverable(this.start, "Comma is not permitted after the rest element"); }
  20314. this.expect(close);
  20315. break
  20316. } else {
  20317. elts.push(this.parseAssignableListItem(allowModifiers));
  20318. }
  20319. }
  20320. return elts
  20321. };
  20322. pp$7.parseAssignableListItem = function(allowModifiers) {
  20323. var elem = this.parseMaybeDefault(this.start, this.startLoc);
  20324. this.parseBindingListItem(elem);
  20325. return elem
  20326. };
  20327. pp$7.parseBindingListItem = function(param) {
  20328. return param
  20329. };
  20330. // Parses assignment pattern around given atom if possible.
  20331. pp$7.parseMaybeDefault = function(startPos, startLoc, left) {
  20332. left = left || this.parseBindingAtom();
  20333. if (this.options.ecmaVersion < 6 || !this.eat(types$1.eq)) { return left }
  20334. var node = this.startNodeAt(startPos, startLoc);
  20335. node.left = left;
  20336. node.right = this.parseMaybeAssign();
  20337. return this.finishNode(node, "AssignmentPattern")
  20338. };
  20339. // The following three functions all verify that a node is an lvalue —
  20340. // something that can be bound, or assigned to. In order to do so, they perform
  20341. // a variety of checks:
  20342. //
  20343. // - Check that none of the bound/assigned-to identifiers are reserved words.
  20344. // - Record name declarations for bindings in the appropriate scope.
  20345. // - Check duplicate argument names, if checkClashes is set.
  20346. //
  20347. // If a complex binding pattern is encountered (e.g., object and array
  20348. // destructuring), the entire pattern is recursively checked.
  20349. //
  20350. // There are three versions of checkLVal*() appropriate for different
  20351. // circumstances:
  20352. //
  20353. // - checkLValSimple() shall be used if the syntactic construct supports
  20354. // nothing other than identifiers and member expressions. Parenthesized
  20355. // expressions are also correctly handled. This is generally appropriate for
  20356. // constructs for which the spec says
  20357. //
  20358. // > It is a Syntax Error if AssignmentTargetType of [the production] is not
  20359. // > simple.
  20360. //
  20361. // It is also appropriate for checking if an identifier is valid and not
  20362. // defined elsewhere, like import declarations or function/class identifiers.
  20363. //
  20364. // Examples where this is used include:
  20365. // a += …;
  20366. // import a from '…';
  20367. // where a is the node to be checked.
  20368. //
  20369. // - checkLValPattern() shall be used if the syntactic construct supports
  20370. // anything checkLValSimple() supports, as well as object and array
  20371. // destructuring patterns. This is generally appropriate for constructs for
  20372. // which the spec says
  20373. //
  20374. // > It is a Syntax Error if [the production] is neither an ObjectLiteral nor
  20375. // > an ArrayLiteral and AssignmentTargetType of [the production] is not
  20376. // > simple.
  20377. //
  20378. // Examples where this is used include:
  20379. // (a = …);
  20380. // const a = …;
  20381. // try { … } catch (a) { … }
  20382. // where a is the node to be checked.
  20383. //
  20384. // - checkLValInnerPattern() shall be used if the syntactic construct supports
  20385. // anything checkLValPattern() supports, as well as default assignment
  20386. // patterns, rest elements, and other constructs that may appear within an
  20387. // object or array destructuring pattern.
  20388. //
  20389. // As a special case, function parameters also use checkLValInnerPattern(),
  20390. // as they also support defaults and rest constructs.
  20391. //
  20392. // These functions deliberately support both assignment and binding constructs,
  20393. // as the logic for both is exceedingly similar. If the node is the target of
  20394. // an assignment, then bindingType should be set to BIND_NONE. Otherwise, it
  20395. // should be set to the appropriate BIND_* constant, like BIND_VAR or
  20396. // BIND_LEXICAL.
  20397. //
  20398. // If the function is called with a non-BIND_NONE bindingType, then
  20399. // additionally a checkClashes object may be specified to allow checking for
  20400. // duplicate argument names. checkClashes is ignored if the provided construct
  20401. // is an assignment (i.e., bindingType is BIND_NONE).
  20402. pp$7.checkLValSimple = function(expr, bindingType, checkClashes) {
  20403. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  20404. var isBind = bindingType !== BIND_NONE;
  20405. switch (expr.type) {
  20406. case "Identifier":
  20407. if (this.strict && this.reservedWordsStrictBind.test(expr.name))
  20408. { this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); }
  20409. if (isBind) {
  20410. if (bindingType === BIND_LEXICAL && expr.name === "let")
  20411. { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); }
  20412. if (checkClashes) {
  20413. if (hasOwn(checkClashes, expr.name))
  20414. { this.raiseRecoverable(expr.start, "Argument name clash"); }
  20415. checkClashes[expr.name] = true;
  20416. }
  20417. if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); }
  20418. }
  20419. break
  20420. case "ChainExpression":
  20421. this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side");
  20422. break
  20423. case "MemberExpression":
  20424. if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); }
  20425. break
  20426. case "ParenthesizedExpression":
  20427. if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); }
  20428. return this.checkLValSimple(expr.expression, bindingType, checkClashes)
  20429. default:
  20430. this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue");
  20431. }
  20432. };
  20433. pp$7.checkLValPattern = function(expr, bindingType, checkClashes) {
  20434. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  20435. switch (expr.type) {
  20436. case "ObjectPattern":
  20437. for (var i = 0, list = expr.properties; i < list.length; i += 1) {
  20438. var prop = list[i];
  20439. this.checkLValInnerPattern(prop, bindingType, checkClashes);
  20440. }
  20441. break
  20442. case "ArrayPattern":
  20443. for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) {
  20444. var elem = list$1[i$1];
  20445. if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); }
  20446. }
  20447. break
  20448. default:
  20449. this.checkLValSimple(expr, bindingType, checkClashes);
  20450. }
  20451. };
  20452. pp$7.checkLValInnerPattern = function(expr, bindingType, checkClashes) {
  20453. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  20454. switch (expr.type) {
  20455. case "Property":
  20456. // AssignmentProperty has type === "Property"
  20457. this.checkLValInnerPattern(expr.value, bindingType, checkClashes);
  20458. break
  20459. case "AssignmentPattern":
  20460. this.checkLValPattern(expr.left, bindingType, checkClashes);
  20461. break
  20462. case "RestElement":
  20463. this.checkLValPattern(expr.argument, bindingType, checkClashes);
  20464. break
  20465. default:
  20466. this.checkLValPattern(expr, bindingType, checkClashes);
  20467. }
  20468. };
  20469. // The algorithm used to determine whether a regexp can appear at a
  20470. // given point in the program is loosely based on sweet.js' approach.
  20471. // See https://github.com/mozilla/sweet.js/wiki/design
  20472. var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) {
  20473. this.token = token;
  20474. this.isExpr = !!isExpr;
  20475. this.preserveSpace = !!preserveSpace;
  20476. this.override = override;
  20477. this.generator = !!generator;
  20478. };
  20479. var types = {
  20480. b_stat: new TokContext("{", false),
  20481. b_expr: new TokContext("{", true),
  20482. b_tmpl: new TokContext("${", false),
  20483. p_stat: new TokContext("(", false),
  20484. p_expr: new TokContext("(", true),
  20485. q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }),
  20486. f_stat: new TokContext("function", false),
  20487. f_expr: new TokContext("function", true),
  20488. f_expr_gen: new TokContext("function", true, false, null, true),
  20489. f_gen: new TokContext("function", false, false, null, true)
  20490. };
  20491. var pp$6 = Parser.prototype;
  20492. pp$6.initialContext = function() {
  20493. return [types.b_stat]
  20494. };
  20495. pp$6.curContext = function() {
  20496. return this.context[this.context.length - 1]
  20497. };
  20498. pp$6.braceIsBlock = function(prevType) {
  20499. var parent = this.curContext();
  20500. if (parent === types.f_expr || parent === types.f_stat)
  20501. { return true }
  20502. if (prevType === types$1.colon && (parent === types.b_stat || parent === types.b_expr))
  20503. { return !parent.isExpr }
  20504. // The check for `tt.name && exprAllowed` detects whether we are
  20505. // after a `yield` or `of` construct. See the `updateContext` for
  20506. // `tt.name`.
  20507. if (prevType === types$1._return || prevType === types$1.name && this.exprAllowed)
  20508. { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }
  20509. if (prevType === types$1._else || prevType === types$1.semi || prevType === types$1.eof || prevType === types$1.parenR || prevType === types$1.arrow)
  20510. { return true }
  20511. if (prevType === types$1.braceL)
  20512. { return parent === types.b_stat }
  20513. if (prevType === types$1._var || prevType === types$1._const || prevType === types$1.name)
  20514. { return false }
  20515. return !this.exprAllowed
  20516. };
  20517. pp$6.inGeneratorContext = function() {
  20518. for (var i = this.context.length - 1; i >= 1; i--) {
  20519. var context = this.context[i];
  20520. if (context.token === "function")
  20521. { return context.generator }
  20522. }
  20523. return false
  20524. };
  20525. pp$6.updateContext = function(prevType) {
  20526. var update, type = this.type;
  20527. if (type.keyword && prevType === types$1.dot)
  20528. { this.exprAllowed = false; }
  20529. else if (update = type.updateContext)
  20530. { update.call(this, prevType); }
  20531. else
  20532. { this.exprAllowed = type.beforeExpr; }
  20533. };
  20534. // Used to handle egde cases when token context could not be inferred correctly during tokenization phase
  20535. pp$6.overrideContext = function(tokenCtx) {
  20536. if (this.curContext() !== tokenCtx) {
  20537. this.context[this.context.length - 1] = tokenCtx;
  20538. }
  20539. };
  20540. // Token-specific context update code
  20541. types$1.parenR.updateContext = types$1.braceR.updateContext = function() {
  20542. if (this.context.length === 1) {
  20543. this.exprAllowed = true;
  20544. return
  20545. }
  20546. var out = this.context.pop();
  20547. if (out === types.b_stat && this.curContext().token === "function") {
  20548. out = this.context.pop();
  20549. }
  20550. this.exprAllowed = !out.isExpr;
  20551. };
  20552. types$1.braceL.updateContext = function(prevType) {
  20553. this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr);
  20554. this.exprAllowed = true;
  20555. };
  20556. types$1.dollarBraceL.updateContext = function() {
  20557. this.context.push(types.b_tmpl);
  20558. this.exprAllowed = true;
  20559. };
  20560. types$1.parenL.updateContext = function(prevType) {
  20561. var statementParens = prevType === types$1._if || prevType === types$1._for || prevType === types$1._with || prevType === types$1._while;
  20562. this.context.push(statementParens ? types.p_stat : types.p_expr);
  20563. this.exprAllowed = true;
  20564. };
  20565. types$1.incDec.updateContext = function() {
  20566. // tokExprAllowed stays unchanged
  20567. };
  20568. types$1._function.updateContext = types$1._class.updateContext = function(prevType) {
  20569. if (prevType.beforeExpr && prevType !== types$1._else &&
  20570. !(prevType === types$1.semi && this.curContext() !== types.p_stat) &&
  20571. !(prevType === types$1._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) &&
  20572. !((prevType === types$1.colon || prevType === types$1.braceL) && this.curContext() === types.b_stat))
  20573. { this.context.push(types.f_expr); }
  20574. else
  20575. { this.context.push(types.f_stat); }
  20576. this.exprAllowed = false;
  20577. };
  20578. types$1.backQuote.updateContext = function() {
  20579. if (this.curContext() === types.q_tmpl)
  20580. { this.context.pop(); }
  20581. else
  20582. { this.context.push(types.q_tmpl); }
  20583. this.exprAllowed = false;
  20584. };
  20585. types$1.star.updateContext = function(prevType) {
  20586. if (prevType === types$1._function) {
  20587. var index = this.context.length - 1;
  20588. if (this.context[index] === types.f_expr)
  20589. { this.context[index] = types.f_expr_gen; }
  20590. else
  20591. { this.context[index] = types.f_gen; }
  20592. }
  20593. this.exprAllowed = true;
  20594. };
  20595. types$1.name.updateContext = function(prevType) {
  20596. var allowed = false;
  20597. if (this.options.ecmaVersion >= 6 && prevType !== types$1.dot) {
  20598. if (this.value === "of" && !this.exprAllowed ||
  20599. this.value === "yield" && this.inGeneratorContext())
  20600. { allowed = true; }
  20601. }
  20602. this.exprAllowed = allowed;
  20603. };
  20604. // A recursive descent parser operates by defining functions for all
  20605. // syntactic elements, and recursively calling those, each function
  20606. // advancing the input stream and returning an AST node. Precedence
  20607. // of constructs (for example, the fact that `!x[1]` means `!(x[1])`
  20608. // instead of `(!x)[1]` is handled by the fact that the parser
  20609. // function that parses unary prefix operators is called first, and
  20610. // in turn calls the function that parses `[]` subscripts — that
  20611. // way, it'll receive the node for `x[1]` already parsed, and wraps
  20612. // *that* in the unary operator node.
  20613. //
  20614. // Acorn uses an [operator precedence parser][opp] to handle binary
  20615. // operator precedence, because it is much more compact than using
  20616. // the technique outlined above, which uses different, nesting
  20617. // functions to specify precedence, for all of the ten binary
  20618. // precedence levels that JavaScript defines.
  20619. //
  20620. // [opp]: http://en.wikipedia.org/wiki/Operator-precedence_parser
  20621. var pp$5 = Parser.prototype;
  20622. // Check if property name clashes with already added.
  20623. // Object/class getters and setters are not allowed to clash —
  20624. // either with each other or with an init property — and in
  20625. // strict mode, init properties are also not allowed to be repeated.
  20626. pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) {
  20627. if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement")
  20628. { return }
  20629. if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand))
  20630. { return }
  20631. var key = prop.key;
  20632. var name;
  20633. switch (key.type) {
  20634. case "Identifier": name = key.name; break
  20635. case "Literal": name = String(key.value); break
  20636. default: return
  20637. }
  20638. var kind = prop.kind;
  20639. if (this.options.ecmaVersion >= 6) {
  20640. if (name === "__proto__" && kind === "init") {
  20641. if (propHash.proto) {
  20642. if (refDestructuringErrors) {
  20643. if (refDestructuringErrors.doubleProto < 0) {
  20644. refDestructuringErrors.doubleProto = key.start;
  20645. }
  20646. } else {
  20647. this.raiseRecoverable(key.start, "Redefinition of __proto__ property");
  20648. }
  20649. }
  20650. propHash.proto = true;
  20651. }
  20652. return
  20653. }
  20654. name = "$" + name;
  20655. var other = propHash[name];
  20656. if (other) {
  20657. var redefinition;
  20658. if (kind === "init") {
  20659. redefinition = this.strict && other.init || other.get || other.set;
  20660. } else {
  20661. redefinition = other.init || other[kind];
  20662. }
  20663. if (redefinition)
  20664. { this.raiseRecoverable(key.start, "Redefinition of property"); }
  20665. } else {
  20666. other = propHash[name] = {
  20667. init: false,
  20668. get: false,
  20669. set: false
  20670. };
  20671. }
  20672. other[kind] = true;
  20673. };
  20674. // ### Expression parsing
  20675. // These nest, from the most general expression type at the top to
  20676. // 'atomic', nondivisible expression types at the bottom. Most of
  20677. // the functions will simply let the function(s) below them parse,
  20678. // and, *if* the syntactic construct they handle is present, wrap
  20679. // the AST node that the inner parser gave them in another node.
  20680. // Parse a full expression. The optional arguments are used to
  20681. // forbid the `in` operator (in for loops initalization expressions)
  20682. // and provide reference for storing '=' operator inside shorthand
  20683. // property assignment in contexts where both object expression
  20684. // and object pattern might appear (so it's possible to raise
  20685. // delayed syntax error at correct position).
  20686. pp$5.parseExpression = function(forInit, refDestructuringErrors) {
  20687. var startPos = this.start, startLoc = this.startLoc;
  20688. var expr = this.parseMaybeAssign(forInit, refDestructuringErrors);
  20689. if (this.type === types$1.comma) {
  20690. var node = this.startNodeAt(startPos, startLoc);
  20691. node.expressions = [expr];
  20692. while (this.eat(types$1.comma)) { node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors)); }
  20693. return this.finishNode(node, "SequenceExpression")
  20694. }
  20695. return expr
  20696. };
  20697. // Parse an assignment expression. This includes applications of
  20698. // operators like `+=`.
  20699. pp$5.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) {
  20700. if (this.isContextual("yield")) {
  20701. if (this.inGenerator) { return this.parseYield(forInit) }
  20702. // The tokenizer will assume an expression is allowed after
  20703. // `yield`, but this isn't that kind of yield
  20704. else { this.exprAllowed = false; }
  20705. }
  20706. var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldDoubleProto = -1;
  20707. if (refDestructuringErrors) {
  20708. oldParenAssign = refDestructuringErrors.parenthesizedAssign;
  20709. oldTrailingComma = refDestructuringErrors.trailingComma;
  20710. oldDoubleProto = refDestructuringErrors.doubleProto;
  20711. refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;
  20712. } else {
  20713. refDestructuringErrors = new DestructuringErrors;
  20714. ownDestructuringErrors = true;
  20715. }
  20716. var startPos = this.start, startLoc = this.startLoc;
  20717. if (this.type === types$1.parenL || this.type === types$1.name) {
  20718. this.potentialArrowAt = this.start;
  20719. this.potentialArrowInForAwait = forInit === "await";
  20720. }
  20721. var left = this.parseMaybeConditional(forInit, refDestructuringErrors);
  20722. if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); }
  20723. if (this.type.isAssign) {
  20724. var node = this.startNodeAt(startPos, startLoc);
  20725. node.operator = this.value;
  20726. if (this.type === types$1.eq)
  20727. { left = this.toAssignable(left, false, refDestructuringErrors); }
  20728. if (!ownDestructuringErrors) {
  20729. refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1;
  20730. }
  20731. if (refDestructuringErrors.shorthandAssign >= left.start)
  20732. { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly
  20733. if (this.type === types$1.eq)
  20734. { this.checkLValPattern(left); }
  20735. else
  20736. { this.checkLValSimple(left); }
  20737. node.left = left;
  20738. this.next();
  20739. node.right = this.parseMaybeAssign(forInit);
  20740. if (oldDoubleProto > -1) { refDestructuringErrors.doubleProto = oldDoubleProto; }
  20741. return this.finishNode(node, "AssignmentExpression")
  20742. } else {
  20743. if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); }
  20744. }
  20745. if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; }
  20746. if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; }
  20747. return left
  20748. };
  20749. // Parse a ternary conditional (`?:`) operator.
  20750. pp$5.parseMaybeConditional = function(forInit, refDestructuringErrors) {
  20751. var startPos = this.start, startLoc = this.startLoc;
  20752. var expr = this.parseExprOps(forInit, refDestructuringErrors);
  20753. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  20754. if (this.eat(types$1.question)) {
  20755. var node = this.startNodeAt(startPos, startLoc);
  20756. node.test = expr;
  20757. node.consequent = this.parseMaybeAssign();
  20758. this.expect(types$1.colon);
  20759. node.alternate = this.parseMaybeAssign(forInit);
  20760. return this.finishNode(node, "ConditionalExpression")
  20761. }
  20762. return expr
  20763. };
  20764. // Start the precedence parser.
  20765. pp$5.parseExprOps = function(forInit, refDestructuringErrors) {
  20766. var startPos = this.start, startLoc = this.startLoc;
  20767. var expr = this.parseMaybeUnary(refDestructuringErrors, false, false, forInit);
  20768. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  20769. return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit)
  20770. };
  20771. // Parse binary operators with the operator precedence parsing
  20772. // algorithm. `left` is the left-hand side of the operator.
  20773. // `minPrec` provides context that allows the function to stop and
  20774. // defer further parser to one of its callers when it encounters an
  20775. // operator that has a lower precedence than the set it is parsing.
  20776. pp$5.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) {
  20777. var prec = this.type.binop;
  20778. if (prec != null && (!forInit || this.type !== types$1._in)) {
  20779. if (prec > minPrec) {
  20780. var logical = this.type === types$1.logicalOR || this.type === types$1.logicalAND;
  20781. var coalesce = this.type === types$1.coalesce;
  20782. if (coalesce) {
  20783. // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions.
  20784. // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error.
  20785. prec = types$1.logicalAND.binop;
  20786. }
  20787. var op = this.value;
  20788. this.next();
  20789. var startPos = this.start, startLoc = this.startLoc;
  20790. var right = this.parseExprOp(this.parseMaybeUnary(null, false, false, forInit), startPos, startLoc, prec, forInit);
  20791. var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce);
  20792. if ((logical && this.type === types$1.coalesce) || (coalesce && (this.type === types$1.logicalOR || this.type === types$1.logicalAND))) {
  20793. this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses");
  20794. }
  20795. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit)
  20796. }
  20797. }
  20798. return left
  20799. };
  20800. pp$5.buildBinary = function(startPos, startLoc, left, right, op, logical) {
  20801. if (right.type === "PrivateIdentifier") { this.raise(right.start, "Private identifier can only be left side of binary expression"); }
  20802. var node = this.startNodeAt(startPos, startLoc);
  20803. node.left = left;
  20804. node.operator = op;
  20805. node.right = right;
  20806. return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression")
  20807. };
  20808. // Parse unary operators, both prefix and postfix.
  20809. pp$5.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec, forInit) {
  20810. var startPos = this.start, startLoc = this.startLoc, expr;
  20811. if (this.isContextual("await") && this.canAwait) {
  20812. expr = this.parseAwait(forInit);
  20813. sawUnary = true;
  20814. } else if (this.type.prefix) {
  20815. var node = this.startNode(), update = this.type === types$1.incDec;
  20816. node.operator = this.value;
  20817. node.prefix = true;
  20818. this.next();
  20819. node.argument = this.parseMaybeUnary(null, true, update, forInit);
  20820. this.checkExpressionErrors(refDestructuringErrors, true);
  20821. if (update) { this.checkLValSimple(node.argument); }
  20822. else if (this.strict && node.operator === "delete" &&
  20823. node.argument.type === "Identifier")
  20824. { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); }
  20825. else if (node.operator === "delete" && isPrivateFieldAccess(node.argument))
  20826. { this.raiseRecoverable(node.start, "Private fields can not be deleted"); }
  20827. else { sawUnary = true; }
  20828. expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
  20829. } else if (!sawUnary && this.type === types$1.privateId) {
  20830. if ((forInit || this.privateNameStack.length === 0) && this.options.checkPrivateFields) { this.unexpected(); }
  20831. expr = this.parsePrivateIdent();
  20832. // only could be private fields in 'in', such as #x in obj
  20833. if (this.type !== types$1._in) { this.unexpected(); }
  20834. } else {
  20835. expr = this.parseExprSubscripts(refDestructuringErrors, forInit);
  20836. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  20837. while (this.type.postfix && !this.canInsertSemicolon()) {
  20838. var node$1 = this.startNodeAt(startPos, startLoc);
  20839. node$1.operator = this.value;
  20840. node$1.prefix = false;
  20841. node$1.argument = expr;
  20842. this.checkLValSimple(expr);
  20843. this.next();
  20844. expr = this.finishNode(node$1, "UpdateExpression");
  20845. }
  20846. }
  20847. if (!incDec && this.eat(types$1.starstar)) {
  20848. if (sawUnary)
  20849. { this.unexpected(this.lastTokStart); }
  20850. else
  20851. { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false, false, forInit), "**", false) }
  20852. } else {
  20853. return expr
  20854. }
  20855. };
  20856. function isPrivateFieldAccess(node) {
  20857. return (
  20858. node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" ||
  20859. node.type === "ChainExpression" && isPrivateFieldAccess(node.expression)
  20860. )
  20861. }
  20862. // Parse call, dot, and `[]`-subscript expressions.
  20863. pp$5.parseExprSubscripts = function(refDestructuringErrors, forInit) {
  20864. var startPos = this.start, startLoc = this.startLoc;
  20865. var expr = this.parseExprAtom(refDestructuringErrors, forInit);
  20866. if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")")
  20867. { return expr }
  20868. var result = this.parseSubscripts(expr, startPos, startLoc, false, forInit);
  20869. if (refDestructuringErrors && result.type === "MemberExpression") {
  20870. if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; }
  20871. if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; }
  20872. if (refDestructuringErrors.trailingComma >= result.start) { refDestructuringErrors.trailingComma = -1; }
  20873. }
  20874. return result
  20875. };
  20876. pp$5.parseSubscripts = function(base, startPos, startLoc, noCalls, forInit) {
  20877. var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" &&
  20878. this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 &&
  20879. this.potentialArrowAt === base.start;
  20880. var optionalChained = false;
  20881. while (true) {
  20882. var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit);
  20883. if (element.optional) { optionalChained = true; }
  20884. if (element === base || element.type === "ArrowFunctionExpression") {
  20885. if (optionalChained) {
  20886. var chainNode = this.startNodeAt(startPos, startLoc);
  20887. chainNode.expression = element;
  20888. element = this.finishNode(chainNode, "ChainExpression");
  20889. }
  20890. return element
  20891. }
  20892. base = element;
  20893. }
  20894. };
  20895. pp$5.shouldParseAsyncArrow = function() {
  20896. return !this.canInsertSemicolon() && this.eat(types$1.arrow)
  20897. };
  20898. pp$5.parseSubscriptAsyncArrow = function(startPos, startLoc, exprList, forInit) {
  20899. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true, forInit)
  20900. };
  20901. pp$5.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) {
  20902. var optionalSupported = this.options.ecmaVersion >= 11;
  20903. var optional = optionalSupported && this.eat(types$1.questionDot);
  20904. if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); }
  20905. var computed = this.eat(types$1.bracketL);
  20906. if (computed || (optional && this.type !== types$1.parenL && this.type !== types$1.backQuote) || this.eat(types$1.dot)) {
  20907. var node = this.startNodeAt(startPos, startLoc);
  20908. node.object = base;
  20909. if (computed) {
  20910. node.property = this.parseExpression();
  20911. this.expect(types$1.bracketR);
  20912. } else if (this.type === types$1.privateId && base.type !== "Super") {
  20913. node.property = this.parsePrivateIdent();
  20914. } else {
  20915. node.property = this.parseIdent(this.options.allowReserved !== "never");
  20916. }
  20917. node.computed = !!computed;
  20918. if (optionalSupported) {
  20919. node.optional = optional;
  20920. }
  20921. base = this.finishNode(node, "MemberExpression");
  20922. } else if (!noCalls && this.eat(types$1.parenL)) {
  20923. var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  20924. this.yieldPos = 0;
  20925. this.awaitPos = 0;
  20926. this.awaitIdentPos = 0;
  20927. var exprList = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);
  20928. if (maybeAsyncArrow && !optional && this.shouldParseAsyncArrow()) {
  20929. this.checkPatternErrors(refDestructuringErrors, false);
  20930. this.checkYieldAwaitInDefaultParams();
  20931. if (this.awaitIdentPos > 0)
  20932. { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); }
  20933. this.yieldPos = oldYieldPos;
  20934. this.awaitPos = oldAwaitPos;
  20935. this.awaitIdentPos = oldAwaitIdentPos;
  20936. return this.parseSubscriptAsyncArrow(startPos, startLoc, exprList, forInit)
  20937. }
  20938. this.checkExpressionErrors(refDestructuringErrors, true);
  20939. this.yieldPos = oldYieldPos || this.yieldPos;
  20940. this.awaitPos = oldAwaitPos || this.awaitPos;
  20941. this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;
  20942. var node$1 = this.startNodeAt(startPos, startLoc);
  20943. node$1.callee = base;
  20944. node$1.arguments = exprList;
  20945. if (optionalSupported) {
  20946. node$1.optional = optional;
  20947. }
  20948. base = this.finishNode(node$1, "CallExpression");
  20949. } else if (this.type === types$1.backQuote) {
  20950. if (optional || optionalChained) {
  20951. this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions");
  20952. }
  20953. var node$2 = this.startNodeAt(startPos, startLoc);
  20954. node$2.tag = base;
  20955. node$2.quasi = this.parseTemplate({isTagged: true});
  20956. base = this.finishNode(node$2, "TaggedTemplateExpression");
  20957. }
  20958. return base
  20959. };
  20960. // Parse an atomic expression — either a single token that is an
  20961. // expression, an expression started by a keyword like `function` or
  20962. // `new`, or an expression wrapped in punctuation like `()`, `[]`,
  20963. // or `{}`.
  20964. pp$5.parseExprAtom = function(refDestructuringErrors, forInit, forNew) {
  20965. // If a division operator appears in an expression position, the
  20966. // tokenizer got confused, and we force it to read a regexp instead.
  20967. if (this.type === types$1.slash) { this.readRegexp(); }
  20968. var node, canBeArrow = this.potentialArrowAt === this.start;
  20969. switch (this.type) {
  20970. case types$1._super:
  20971. if (!this.allowSuper)
  20972. { this.raise(this.start, "'super' keyword outside a method"); }
  20973. node = this.startNode();
  20974. this.next();
  20975. if (this.type === types$1.parenL && !this.allowDirectSuper)
  20976. { this.raise(node.start, "super() call outside constructor of a subclass"); }
  20977. // The `super` keyword can appear at below:
  20978. // SuperProperty:
  20979. // super [ Expression ]
  20980. // super . IdentifierName
  20981. // SuperCall:
  20982. // super ( Arguments )
  20983. if (this.type !== types$1.dot && this.type !== types$1.bracketL && this.type !== types$1.parenL)
  20984. { this.unexpected(); }
  20985. return this.finishNode(node, "Super")
  20986. case types$1._this:
  20987. node = this.startNode();
  20988. this.next();
  20989. return this.finishNode(node, "ThisExpression")
  20990. case types$1.name:
  20991. var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc;
  20992. var id = this.parseIdent(false);
  20993. if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types$1._function)) {
  20994. this.overrideContext(types.f_expr);
  20995. return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true, forInit)
  20996. }
  20997. if (canBeArrow && !this.canInsertSemicolon()) {
  20998. if (this.eat(types$1.arrow))
  20999. { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false, forInit) }
  21000. if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types$1.name && !containsEsc &&
  21001. (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) {
  21002. id = this.parseIdent(false);
  21003. if (this.canInsertSemicolon() || !this.eat(types$1.arrow))
  21004. { this.unexpected(); }
  21005. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true, forInit)
  21006. }
  21007. }
  21008. return id
  21009. case types$1.regexp:
  21010. var value = this.value;
  21011. node = this.parseLiteral(value.value);
  21012. node.regex = {pattern: value.pattern, flags: value.flags};
  21013. return node
  21014. case types$1.num: case types$1.string:
  21015. return this.parseLiteral(this.value)
  21016. case types$1._null: case types$1._true: case types$1._false:
  21017. node = this.startNode();
  21018. node.value = this.type === types$1._null ? null : this.type === types$1._true;
  21019. node.raw = this.type.keyword;
  21020. this.next();
  21021. return this.finishNode(node, "Literal")
  21022. case types$1.parenL:
  21023. var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow, forInit);
  21024. if (refDestructuringErrors) {
  21025. if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))
  21026. { refDestructuringErrors.parenthesizedAssign = start; }
  21027. if (refDestructuringErrors.parenthesizedBind < 0)
  21028. { refDestructuringErrors.parenthesizedBind = start; }
  21029. }
  21030. return expr
  21031. case types$1.bracketL:
  21032. node = this.startNode();
  21033. this.next();
  21034. node.elements = this.parseExprList(types$1.bracketR, true, true, refDestructuringErrors);
  21035. return this.finishNode(node, "ArrayExpression")
  21036. case types$1.braceL:
  21037. this.overrideContext(types.b_expr);
  21038. return this.parseObj(false, refDestructuringErrors)
  21039. case types$1._function:
  21040. node = this.startNode();
  21041. this.next();
  21042. return this.parseFunction(node, 0)
  21043. case types$1._class:
  21044. return this.parseClass(this.startNode(), false)
  21045. case types$1._new:
  21046. return this.parseNew()
  21047. case types$1.backQuote:
  21048. return this.parseTemplate()
  21049. case types$1._import:
  21050. if (this.options.ecmaVersion >= 11) {
  21051. return this.parseExprImport(forNew)
  21052. } else {
  21053. return this.unexpected()
  21054. }
  21055. default:
  21056. return this.parseExprAtomDefault()
  21057. }
  21058. };
  21059. pp$5.parseExprAtomDefault = function() {
  21060. this.unexpected();
  21061. };
  21062. pp$5.parseExprImport = function(forNew) {
  21063. var node = this.startNode();
  21064. // Consume `import` as an identifier for `import.meta`.
  21065. // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`.
  21066. if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); }
  21067. var meta = this.parseIdent(true);
  21068. if (this.type === types$1.parenL && !forNew) {
  21069. return this.parseDynamicImport(node)
  21070. } else if (this.type === types$1.dot) {
  21071. node.meta = meta;
  21072. return this.parseImportMeta(node)
  21073. } else {
  21074. this.unexpected();
  21075. }
  21076. };
  21077. pp$5.parseDynamicImport = function(node) {
  21078. this.next(); // skip `(`
  21079. // Parse node.source.
  21080. node.source = this.parseMaybeAssign();
  21081. // Verify ending.
  21082. if (!this.eat(types$1.parenR)) {
  21083. var errorPos = this.start;
  21084. if (this.eat(types$1.comma) && this.eat(types$1.parenR)) {
  21085. this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()");
  21086. } else {
  21087. this.unexpected(errorPos);
  21088. }
  21089. }
  21090. return this.finishNode(node, "ImportExpression")
  21091. };
  21092. pp$5.parseImportMeta = function(node) {
  21093. this.next(); // skip `.`
  21094. var containsEsc = this.containsEsc;
  21095. node.property = this.parseIdent(true);
  21096. if (node.property.name !== "meta")
  21097. { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); }
  21098. if (containsEsc)
  21099. { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); }
  21100. if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere)
  21101. { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); }
  21102. return this.finishNode(node, "MetaProperty")
  21103. };
  21104. pp$5.parseLiteral = function(value) {
  21105. var node = this.startNode();
  21106. node.value = value;
  21107. node.raw = this.input.slice(this.start, this.end);
  21108. if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); }
  21109. this.next();
  21110. return this.finishNode(node, "Literal")
  21111. };
  21112. pp$5.parseParenExpression = function() {
  21113. this.expect(types$1.parenL);
  21114. var val = this.parseExpression();
  21115. this.expect(types$1.parenR);
  21116. return val
  21117. };
  21118. pp$5.shouldParseArrow = function(exprList) {
  21119. return !this.canInsertSemicolon()
  21120. };
  21121. pp$5.parseParenAndDistinguishExpression = function(canBeArrow, forInit) {
  21122. var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;
  21123. if (this.options.ecmaVersion >= 6) {
  21124. this.next();
  21125. var innerStartPos = this.start, innerStartLoc = this.startLoc;
  21126. var exprList = [], first = true, lastIsComma = false;
  21127. var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart;
  21128. this.yieldPos = 0;
  21129. this.awaitPos = 0;
  21130. // Do not save awaitIdentPos to allow checking awaits nested in parameters
  21131. while (this.type !== types$1.parenR) {
  21132. first ? first = false : this.expect(types$1.comma);
  21133. if (allowTrailingComma && this.afterTrailingComma(types$1.parenR, true)) {
  21134. lastIsComma = true;
  21135. break
  21136. } else if (this.type === types$1.ellipsis) {
  21137. spreadStart = this.start;
  21138. exprList.push(this.parseParenItem(this.parseRestBinding()));
  21139. if (this.type === types$1.comma) {
  21140. this.raiseRecoverable(
  21141. this.start,
  21142. "Comma is not permitted after the rest element"
  21143. );
  21144. }
  21145. break
  21146. } else {
  21147. exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));
  21148. }
  21149. }
  21150. var innerEndPos = this.lastTokEnd, innerEndLoc = this.lastTokEndLoc;
  21151. this.expect(types$1.parenR);
  21152. if (canBeArrow && this.shouldParseArrow(exprList) && this.eat(types$1.arrow)) {
  21153. this.checkPatternErrors(refDestructuringErrors, false);
  21154. this.checkYieldAwaitInDefaultParams();
  21155. this.yieldPos = oldYieldPos;
  21156. this.awaitPos = oldAwaitPos;
  21157. return this.parseParenArrowList(startPos, startLoc, exprList, forInit)
  21158. }
  21159. if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); }
  21160. if (spreadStart) { this.unexpected(spreadStart); }
  21161. this.checkExpressionErrors(refDestructuringErrors, true);
  21162. this.yieldPos = oldYieldPos || this.yieldPos;
  21163. this.awaitPos = oldAwaitPos || this.awaitPos;
  21164. if (exprList.length > 1) {
  21165. val = this.startNodeAt(innerStartPos, innerStartLoc);
  21166. val.expressions = exprList;
  21167. this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
  21168. } else {
  21169. val = exprList[0];
  21170. }
  21171. } else {
  21172. val = this.parseParenExpression();
  21173. }
  21174. if (this.options.preserveParens) {
  21175. var par = this.startNodeAt(startPos, startLoc);
  21176. par.expression = val;
  21177. return this.finishNode(par, "ParenthesizedExpression")
  21178. } else {
  21179. return val
  21180. }
  21181. };
  21182. pp$5.parseParenItem = function(item) {
  21183. return item
  21184. };
  21185. pp$5.parseParenArrowList = function(startPos, startLoc, exprList, forInit) {
  21186. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, false, forInit)
  21187. };
  21188. // New's precedence is slightly tricky. It must allow its argument to
  21189. // be a `[]` or dot subscript expression, but not a call — at least,
  21190. // not without wrapping it in parentheses. Thus, it uses the noCalls
  21191. // argument to parseSubscripts to prevent it from consuming the
  21192. // argument list.
  21193. var empty = [];
  21194. pp$5.parseNew = function() {
  21195. if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); }
  21196. var node = this.startNode();
  21197. var meta = this.parseIdent(true);
  21198. if (this.options.ecmaVersion >= 6 && this.eat(types$1.dot)) {
  21199. node.meta = meta;
  21200. var containsEsc = this.containsEsc;
  21201. node.property = this.parseIdent(true);
  21202. if (node.property.name !== "target")
  21203. { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); }
  21204. if (containsEsc)
  21205. { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); }
  21206. if (!this.allowNewDotTarget)
  21207. { this.raiseRecoverable(node.start, "'new.target' can only be used in functions and class static block"); }
  21208. return this.finishNode(node, "MetaProperty")
  21209. }
  21210. var startPos = this.start, startLoc = this.startLoc;
  21211. node.callee = this.parseSubscripts(this.parseExprAtom(null, false, true), startPos, startLoc, true, false);
  21212. if (this.eat(types$1.parenL)) { node.arguments = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false); }
  21213. else { node.arguments = empty; }
  21214. return this.finishNode(node, "NewExpression")
  21215. };
  21216. // Parse template expression.
  21217. pp$5.parseTemplateElement = function(ref) {
  21218. var isTagged = ref.isTagged;
  21219. var elem = this.startNode();
  21220. if (this.type === types$1.invalidTemplate) {
  21221. if (!isTagged) {
  21222. this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");
  21223. }
  21224. elem.value = {
  21225. raw: this.value,
  21226. cooked: null
  21227. };
  21228. } else {
  21229. elem.value = {
  21230. raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
  21231. cooked: this.value
  21232. };
  21233. }
  21234. this.next();
  21235. elem.tail = this.type === types$1.backQuote;
  21236. return this.finishNode(elem, "TemplateElement")
  21237. };
  21238. pp$5.parseTemplate = function(ref) {
  21239. if ( ref === void 0 ) ref = {};
  21240. var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false;
  21241. var node = this.startNode();
  21242. this.next();
  21243. node.expressions = [];
  21244. var curElt = this.parseTemplateElement({isTagged: isTagged});
  21245. node.quasis = [curElt];
  21246. while (!curElt.tail) {
  21247. if (this.type === types$1.eof) { this.raise(this.pos, "Unterminated template literal"); }
  21248. this.expect(types$1.dollarBraceL);
  21249. node.expressions.push(this.parseExpression());
  21250. this.expect(types$1.braceR);
  21251. node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged}));
  21252. }
  21253. this.next();
  21254. return this.finishNode(node, "TemplateLiteral")
  21255. };
  21256. pp$5.isAsyncProp = function(prop) {
  21257. return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" &&
  21258. (this.type === types$1.name || this.type === types$1.num || this.type === types$1.string || this.type === types$1.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === types$1.star)) &&
  21259. !lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
  21260. };
  21261. // Parse an object literal or binding pattern.
  21262. pp$5.parseObj = function(isPattern, refDestructuringErrors) {
  21263. var node = this.startNode(), first = true, propHash = {};
  21264. node.properties = [];
  21265. this.next();
  21266. while (!this.eat(types$1.braceR)) {
  21267. if (!first) {
  21268. this.expect(types$1.comma);
  21269. if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types$1.braceR)) { break }
  21270. } else { first = false; }
  21271. var prop = this.parseProperty(isPattern, refDestructuringErrors);
  21272. if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); }
  21273. node.properties.push(prop);
  21274. }
  21275. return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")
  21276. };
  21277. pp$5.parseProperty = function(isPattern, refDestructuringErrors) {
  21278. var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc;
  21279. if (this.options.ecmaVersion >= 9 && this.eat(types$1.ellipsis)) {
  21280. if (isPattern) {
  21281. prop.argument = this.parseIdent(false);
  21282. if (this.type === types$1.comma) {
  21283. this.raiseRecoverable(this.start, "Comma is not permitted after the rest element");
  21284. }
  21285. return this.finishNode(prop, "RestElement")
  21286. }
  21287. // Parse argument.
  21288. prop.argument = this.parseMaybeAssign(false, refDestructuringErrors);
  21289. // To disallow trailing comma via `this.toAssignable()`.
  21290. if (this.type === types$1.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {
  21291. refDestructuringErrors.trailingComma = this.start;
  21292. }
  21293. // Finish
  21294. return this.finishNode(prop, "SpreadElement")
  21295. }
  21296. if (this.options.ecmaVersion >= 6) {
  21297. prop.method = false;
  21298. prop.shorthand = false;
  21299. if (isPattern || refDestructuringErrors) {
  21300. startPos = this.start;
  21301. startLoc = this.startLoc;
  21302. }
  21303. if (!isPattern)
  21304. { isGenerator = this.eat(types$1.star); }
  21305. }
  21306. var containsEsc = this.containsEsc;
  21307. this.parsePropertyName(prop);
  21308. if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {
  21309. isAsync = true;
  21310. isGenerator = this.options.ecmaVersion >= 9 && this.eat(types$1.star);
  21311. this.parsePropertyName(prop);
  21312. } else {
  21313. isAsync = false;
  21314. }
  21315. this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc);
  21316. return this.finishNode(prop, "Property")
  21317. };
  21318. pp$5.parseGetterSetter = function(prop) {
  21319. prop.kind = prop.key.name;
  21320. this.parsePropertyName(prop);
  21321. prop.value = this.parseMethod(false);
  21322. var paramCount = prop.kind === "get" ? 0 : 1;
  21323. if (prop.value.params.length !== paramCount) {
  21324. var start = prop.value.start;
  21325. if (prop.kind === "get")
  21326. { this.raiseRecoverable(start, "getter should have no params"); }
  21327. else
  21328. { this.raiseRecoverable(start, "setter should have exactly one param"); }
  21329. } else {
  21330. if (prop.kind === "set" && prop.value.params[0].type === "RestElement")
  21331. { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); }
  21332. }
  21333. };
  21334. pp$5.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) {
  21335. if ((isGenerator || isAsync) && this.type === types$1.colon)
  21336. { this.unexpected(); }
  21337. if (this.eat(types$1.colon)) {
  21338. prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);
  21339. prop.kind = "init";
  21340. } else if (this.options.ecmaVersion >= 6 && this.type === types$1.parenL) {
  21341. if (isPattern) { this.unexpected(); }
  21342. prop.kind = "init";
  21343. prop.method = true;
  21344. prop.value = this.parseMethod(isGenerator, isAsync);
  21345. } else if (!isPattern && !containsEsc &&
  21346. this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" &&
  21347. (prop.key.name === "get" || prop.key.name === "set") &&
  21348. (this.type !== types$1.comma && this.type !== types$1.braceR && this.type !== types$1.eq)) {
  21349. if (isGenerator || isAsync) { this.unexpected(); }
  21350. this.parseGetterSetter(prop);
  21351. } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
  21352. if (isGenerator || isAsync) { this.unexpected(); }
  21353. this.checkUnreserved(prop.key);
  21354. if (prop.key.name === "await" && !this.awaitIdentPos)
  21355. { this.awaitIdentPos = startPos; }
  21356. prop.kind = "init";
  21357. if (isPattern) {
  21358. prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
  21359. } else if (this.type === types$1.eq && refDestructuringErrors) {
  21360. if (refDestructuringErrors.shorthandAssign < 0)
  21361. { refDestructuringErrors.shorthandAssign = this.start; }
  21362. prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
  21363. } else {
  21364. prop.value = this.copyNode(prop.key);
  21365. }
  21366. prop.shorthand = true;
  21367. } else { this.unexpected(); }
  21368. };
  21369. pp$5.parsePropertyName = function(prop) {
  21370. if (this.options.ecmaVersion >= 6) {
  21371. if (this.eat(types$1.bracketL)) {
  21372. prop.computed = true;
  21373. prop.key = this.parseMaybeAssign();
  21374. this.expect(types$1.bracketR);
  21375. return prop.key
  21376. } else {
  21377. prop.computed = false;
  21378. }
  21379. }
  21380. return prop.key = this.type === types$1.num || this.type === types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never")
  21381. };
  21382. // Initialize empty function node.
  21383. pp$5.initFunction = function(node) {
  21384. node.id = null;
  21385. if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; }
  21386. if (this.options.ecmaVersion >= 8) { node.async = false; }
  21387. };
  21388. // Parse object or class method.
  21389. pp$5.parseMethod = function(isGenerator, isAsync, allowDirectSuper) {
  21390. var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  21391. this.initFunction(node);
  21392. if (this.options.ecmaVersion >= 6)
  21393. { node.generator = isGenerator; }
  21394. if (this.options.ecmaVersion >= 8)
  21395. { node.async = !!isAsync; }
  21396. this.yieldPos = 0;
  21397. this.awaitPos = 0;
  21398. this.awaitIdentPos = 0;
  21399. this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
  21400. this.expect(types$1.parenL);
  21401. node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8);
  21402. this.checkYieldAwaitInDefaultParams();
  21403. this.parseFunctionBody(node, false, true, false);
  21404. this.yieldPos = oldYieldPos;
  21405. this.awaitPos = oldAwaitPos;
  21406. this.awaitIdentPos = oldAwaitIdentPos;
  21407. return this.finishNode(node, "FunctionExpression")
  21408. };
  21409. // Parse arrow function expression with given parameters.
  21410. pp$5.parseArrowExpression = function(node, params, isAsync, forInit) {
  21411. var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  21412. this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW);
  21413. this.initFunction(node);
  21414. if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; }
  21415. this.yieldPos = 0;
  21416. this.awaitPos = 0;
  21417. this.awaitIdentPos = 0;
  21418. node.params = this.toAssignableList(params, true);
  21419. this.parseFunctionBody(node, true, false, forInit);
  21420. this.yieldPos = oldYieldPos;
  21421. this.awaitPos = oldAwaitPos;
  21422. this.awaitIdentPos = oldAwaitIdentPos;
  21423. return this.finishNode(node, "ArrowFunctionExpression")
  21424. };
  21425. // Parse function body and check parameters.
  21426. pp$5.parseFunctionBody = function(node, isArrowFunction, isMethod, forInit) {
  21427. var isExpression = isArrowFunction && this.type !== types$1.braceL;
  21428. var oldStrict = this.strict, useStrict = false;
  21429. if (isExpression) {
  21430. node.body = this.parseMaybeAssign(forInit);
  21431. node.expression = true;
  21432. this.checkParams(node, false);
  21433. } else {
  21434. var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);
  21435. if (!oldStrict || nonSimple) {
  21436. useStrict = this.strictDirective(this.end);
  21437. // If this is a strict mode function, verify that argument names
  21438. // are not repeated, and it does not try to bind the words `eval`
  21439. // or `arguments`.
  21440. if (useStrict && nonSimple)
  21441. { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); }
  21442. }
  21443. // Start a new scope with regard to labels and the `inFunction`
  21444. // flag (restore them to their old value afterwards).
  21445. var oldLabels = this.labels;
  21446. this.labels = [];
  21447. if (useStrict) { this.strict = true; }
  21448. // Add the params to varDeclaredNames to ensure that an error is thrown
  21449. // if a let/const declaration in the function clashes with one of the params.
  21450. this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params));
  21451. // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'
  21452. if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); }
  21453. node.body = this.parseBlock(false, undefined, useStrict && !oldStrict);
  21454. node.expression = false;
  21455. this.adaptDirectivePrologue(node.body.body);
  21456. this.labels = oldLabels;
  21457. }
  21458. this.exitScope();
  21459. };
  21460. pp$5.isSimpleParamList = function(params) {
  21461. for (var i = 0, list = params; i < list.length; i += 1)
  21462. {
  21463. var param = list[i];
  21464. if (param.type !== "Identifier") { return false
  21465. } }
  21466. return true
  21467. };
  21468. // Checks function params for various disallowed patterns such as using "eval"
  21469. // or "arguments" and duplicate parameters.
  21470. pp$5.checkParams = function(node, allowDuplicates) {
  21471. var nameHash = Object.create(null);
  21472. for (var i = 0, list = node.params; i < list.length; i += 1)
  21473. {
  21474. var param = list[i];
  21475. this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash);
  21476. }
  21477. };
  21478. // Parses a comma-separated list of expressions, and returns them as
  21479. // an array. `close` is the token type that ends the list, and
  21480. // `allowEmpty` can be turned on to allow subsequent commas with
  21481. // nothing in between them to be parsed as `null` (which is needed
  21482. // for array literals).
  21483. pp$5.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
  21484. var elts = [], first = true;
  21485. while (!this.eat(close)) {
  21486. if (!first) {
  21487. this.expect(types$1.comma);
  21488. if (allowTrailingComma && this.afterTrailingComma(close)) { break }
  21489. } else { first = false; }
  21490. var elt = (void 0);
  21491. if (allowEmpty && this.type === types$1.comma)
  21492. { elt = null; }
  21493. else if (this.type === types$1.ellipsis) {
  21494. elt = this.parseSpread(refDestructuringErrors);
  21495. if (refDestructuringErrors && this.type === types$1.comma && refDestructuringErrors.trailingComma < 0)
  21496. { refDestructuringErrors.trailingComma = this.start; }
  21497. } else {
  21498. elt = this.parseMaybeAssign(false, refDestructuringErrors);
  21499. }
  21500. elts.push(elt);
  21501. }
  21502. return elts
  21503. };
  21504. pp$5.checkUnreserved = function(ref) {
  21505. var start = ref.start;
  21506. var end = ref.end;
  21507. var name = ref.name;
  21508. if (this.inGenerator && name === "yield")
  21509. { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); }
  21510. if (this.inAsync && name === "await")
  21511. { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); }
  21512. if (this.currentThisScope().inClassFieldInit && name === "arguments")
  21513. { this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer"); }
  21514. if (this.inClassStaticBlock && (name === "arguments" || name === "await"))
  21515. { this.raise(start, ("Cannot use " + name + " in class static initialization block")); }
  21516. if (this.keywords.test(name))
  21517. { this.raise(start, ("Unexpected keyword '" + name + "'")); }
  21518. if (this.options.ecmaVersion < 6 &&
  21519. this.input.slice(start, end).indexOf("\\") !== -1) { return }
  21520. var re = this.strict ? this.reservedWordsStrict : this.reservedWords;
  21521. if (re.test(name)) {
  21522. if (!this.inAsync && name === "await")
  21523. { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); }
  21524. this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved"));
  21525. }
  21526. };
  21527. // Parse the next token as an identifier. If `liberal` is true (used
  21528. // when parsing properties), it will also convert keywords into
  21529. // identifiers.
  21530. pp$5.parseIdent = function(liberal) {
  21531. var node = this.parseIdentNode();
  21532. this.next(!!liberal);
  21533. this.finishNode(node, "Identifier");
  21534. if (!liberal) {
  21535. this.checkUnreserved(node);
  21536. if (node.name === "await" && !this.awaitIdentPos)
  21537. { this.awaitIdentPos = node.start; }
  21538. }
  21539. return node
  21540. };
  21541. pp$5.parseIdentNode = function() {
  21542. var node = this.startNode();
  21543. if (this.type === types$1.name) {
  21544. node.name = this.value;
  21545. } else if (this.type.keyword) {
  21546. node.name = this.type.keyword;
  21547. // To fix https://github.com/acornjs/acorn/issues/575
  21548. // `class` and `function` keywords push new context into this.context.
  21549. // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name.
  21550. // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword
  21551. if ((node.name === "class" || node.name === "function") &&
  21552. (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {
  21553. this.context.pop();
  21554. }
  21555. } else {
  21556. this.unexpected();
  21557. }
  21558. return node
  21559. };
  21560. pp$5.parsePrivateIdent = function() {
  21561. var node = this.startNode();
  21562. if (this.type === types$1.privateId) {
  21563. node.name = this.value;
  21564. } else {
  21565. this.unexpected();
  21566. }
  21567. this.next();
  21568. this.finishNode(node, "PrivateIdentifier");
  21569. // For validating existence
  21570. if (this.options.checkPrivateFields) {
  21571. if (this.privateNameStack.length === 0) {
  21572. this.raise(node.start, ("Private field '#" + (node.name) + "' must be declared in an enclosing class"));
  21573. } else {
  21574. this.privateNameStack[this.privateNameStack.length - 1].used.push(node);
  21575. }
  21576. }
  21577. return node
  21578. };
  21579. // Parses yield expression inside generator.
  21580. pp$5.parseYield = function(forInit) {
  21581. if (!this.yieldPos) { this.yieldPos = this.start; }
  21582. var node = this.startNode();
  21583. this.next();
  21584. if (this.type === types$1.semi || this.canInsertSemicolon() || (this.type !== types$1.star && !this.type.startsExpr)) {
  21585. node.delegate = false;
  21586. node.argument = null;
  21587. } else {
  21588. node.delegate = this.eat(types$1.star);
  21589. node.argument = this.parseMaybeAssign(forInit);
  21590. }
  21591. return this.finishNode(node, "YieldExpression")
  21592. };
  21593. pp$5.parseAwait = function(forInit) {
  21594. if (!this.awaitPos) { this.awaitPos = this.start; }
  21595. var node = this.startNode();
  21596. this.next();
  21597. node.argument = this.parseMaybeUnary(null, true, false, forInit);
  21598. return this.finishNode(node, "AwaitExpression")
  21599. };
  21600. var pp$4 = Parser.prototype;
  21601. // This function is used to raise exceptions on parse errors. It
  21602. // takes an offset integer (into the current `input`) to indicate
  21603. // the location of the error, attaches the position to the end
  21604. // of the error message, and then raises a `SyntaxError` with that
  21605. // message.
  21606. pp$4.raise = function(pos, message) {
  21607. var loc = getLineInfo(this.input, pos);
  21608. message += " (" + loc.line + ":" + loc.column + ")";
  21609. var err = new SyntaxError(message);
  21610. err.pos = pos; err.loc = loc; err.raisedAt = this.pos;
  21611. throw err
  21612. };
  21613. pp$4.raiseRecoverable = pp$4.raise;
  21614. pp$4.curPosition = function() {
  21615. if (this.options.locations) {
  21616. return new Position(this.curLine, this.pos - this.lineStart)
  21617. }
  21618. };
  21619. var pp$3 = Parser.prototype;
  21620. var Scope = function Scope(flags) {
  21621. this.flags = flags;
  21622. // A list of var-declared names in the current lexical scope
  21623. this.var = [];
  21624. // A list of lexically-declared names in the current lexical scope
  21625. this.lexical = [];
  21626. // A list of lexically-declared FunctionDeclaration names in the current lexical scope
  21627. this.functions = [];
  21628. // A switch to disallow the identifier reference 'arguments'
  21629. this.inClassFieldInit = false;
  21630. };
  21631. // The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names.
  21632. pp$3.enterScope = function(flags) {
  21633. this.scopeStack.push(new Scope(flags));
  21634. };
  21635. pp$3.exitScope = function() {
  21636. this.scopeStack.pop();
  21637. };
  21638. // The spec says:
  21639. // > At the top level of a function, or script, function declarations are
  21640. // > treated like var declarations rather than like lexical declarations.
  21641. pp$3.treatFunctionsAsVarInScope = function(scope) {
  21642. return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP)
  21643. };
  21644. pp$3.declareName = function(name, bindingType, pos) {
  21645. var redeclared = false;
  21646. if (bindingType === BIND_LEXICAL) {
  21647. var scope = this.currentScope();
  21648. redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
  21649. scope.lexical.push(name);
  21650. if (this.inModule && (scope.flags & SCOPE_TOP))
  21651. { delete this.undefinedExports[name]; }
  21652. } else if (bindingType === BIND_SIMPLE_CATCH) {
  21653. var scope$1 = this.currentScope();
  21654. scope$1.lexical.push(name);
  21655. } else if (bindingType === BIND_FUNCTION) {
  21656. var scope$2 = this.currentScope();
  21657. if (this.treatFunctionsAsVar)
  21658. { redeclared = scope$2.lexical.indexOf(name) > -1; }
  21659. else
  21660. { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; }
  21661. scope$2.functions.push(name);
  21662. } else {
  21663. for (var i = this.scopeStack.length - 1; i >= 0; --i) {
  21664. var scope$3 = this.scopeStack[i];
  21665. if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) ||
  21666. !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) {
  21667. redeclared = true;
  21668. break
  21669. }
  21670. scope$3.var.push(name);
  21671. if (this.inModule && (scope$3.flags & SCOPE_TOP))
  21672. { delete this.undefinedExports[name]; }
  21673. if (scope$3.flags & SCOPE_VAR) { break }
  21674. }
  21675. }
  21676. if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); }
  21677. };
  21678. pp$3.checkLocalExport = function(id) {
  21679. // scope.functions must be empty as Module code is always strict.
  21680. if (this.scopeStack[0].lexical.indexOf(id.name) === -1 &&
  21681. this.scopeStack[0].var.indexOf(id.name) === -1) {
  21682. this.undefinedExports[id.name] = id;
  21683. }
  21684. };
  21685. pp$3.currentScope = function() {
  21686. return this.scopeStack[this.scopeStack.length - 1]
  21687. };
  21688. pp$3.currentVarScope = function() {
  21689. for (var i = this.scopeStack.length - 1;; i--) {
  21690. var scope = this.scopeStack[i];
  21691. if (scope.flags & SCOPE_VAR) { return scope }
  21692. }
  21693. };
  21694. // Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`.
  21695. pp$3.currentThisScope = function() {
  21696. for (var i = this.scopeStack.length - 1;; i--) {
  21697. var scope = this.scopeStack[i];
  21698. if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope }
  21699. }
  21700. };
  21701. var Node = function Node(parser, pos, loc) {
  21702. this.type = "";
  21703. this.start = pos;
  21704. this.end = 0;
  21705. if (parser.options.locations)
  21706. { this.loc = new SourceLocation(parser, loc); }
  21707. if (parser.options.directSourceFile)
  21708. { this.sourceFile = parser.options.directSourceFile; }
  21709. if (parser.options.ranges)
  21710. { this.range = [pos, 0]; }
  21711. };
  21712. // Start an AST node, attaching a start offset.
  21713. var pp$2 = Parser.prototype;
  21714. pp$2.startNode = function() {
  21715. return new Node(this, this.start, this.startLoc)
  21716. };
  21717. pp$2.startNodeAt = function(pos, loc) {
  21718. return new Node(this, pos, loc)
  21719. };
  21720. // Finish an AST node, adding `type` and `end` properties.
  21721. function finishNodeAt(node, type, pos, loc) {
  21722. node.type = type;
  21723. node.end = pos;
  21724. if (this.options.locations)
  21725. { node.loc.end = loc; }
  21726. if (this.options.ranges)
  21727. { node.range[1] = pos; }
  21728. return node
  21729. }
  21730. pp$2.finishNode = function(node, type) {
  21731. return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)
  21732. };
  21733. // Finish node at given position
  21734. pp$2.finishNodeAt = function(node, type, pos, loc) {
  21735. return finishNodeAt.call(this, node, type, pos, loc)
  21736. };
  21737. pp$2.copyNode = function(node) {
  21738. var newNode = new Node(this, node.start, this.startLoc);
  21739. for (var prop in node) { newNode[prop] = node[prop]; }
  21740. return newNode
  21741. };
  21742. // This file contains Unicode properties extracted from the ECMAScript specification.
  21743. // The lists are extracted like so:
  21744. // $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText)
  21745. // #table-binary-unicode-properties
  21746. var ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS";
  21747. var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic";
  21748. var ecma11BinaryProperties = ecma10BinaryProperties;
  21749. var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict";
  21750. var ecma13BinaryProperties = ecma12BinaryProperties;
  21751. var ecma14BinaryProperties = ecma13BinaryProperties;
  21752. var unicodeBinaryProperties = {
  21753. 9: ecma9BinaryProperties,
  21754. 10: ecma10BinaryProperties,
  21755. 11: ecma11BinaryProperties,
  21756. 12: ecma12BinaryProperties,
  21757. 13: ecma13BinaryProperties,
  21758. 14: ecma14BinaryProperties
  21759. };
  21760. // #table-binary-unicode-properties-of-strings
  21761. var ecma14BinaryPropertiesOfStrings = "Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji";
  21762. var unicodeBinaryPropertiesOfStrings = {
  21763. 9: "",
  21764. 10: "",
  21765. 11: "",
  21766. 12: "",
  21767. 13: "",
  21768. 14: ecma14BinaryPropertiesOfStrings
  21769. };
  21770. // #table-unicode-general-category-values
  21771. var unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu";
  21772. // #table-unicode-script-values
  21773. var ecma9ScriptValues = "Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb";
  21774. var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";
  21775. var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";
  21776. var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";
  21777. var ecma13ScriptValues = ecma12ScriptValues + " Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith";
  21778. var ecma14ScriptValues = ecma13ScriptValues + " Hrkt Katakana_Or_Hiragana Kawi Nag_Mundari Nagm Unknown Zzzz";
  21779. var unicodeScriptValues = {
  21780. 9: ecma9ScriptValues,
  21781. 10: ecma10ScriptValues,
  21782. 11: ecma11ScriptValues,
  21783. 12: ecma12ScriptValues,
  21784. 13: ecma13ScriptValues,
  21785. 14: ecma14ScriptValues
  21786. };
  21787. var data = {};
  21788. function buildUnicodeData(ecmaVersion) {
  21789. var d = data[ecmaVersion] = {
  21790. binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues),
  21791. binaryOfStrings: wordsRegexp(unicodeBinaryPropertiesOfStrings[ecmaVersion]),
  21792. nonBinary: {
  21793. General_Category: wordsRegexp(unicodeGeneralCategoryValues),
  21794. Script: wordsRegexp(unicodeScriptValues[ecmaVersion])
  21795. }
  21796. };
  21797. d.nonBinary.Script_Extensions = d.nonBinary.Script;
  21798. d.nonBinary.gc = d.nonBinary.General_Category;
  21799. d.nonBinary.sc = d.nonBinary.Script;
  21800. d.nonBinary.scx = d.nonBinary.Script_Extensions;
  21801. }
  21802. for (var i = 0, list = [9, 10, 11, 12, 13, 14]; i < list.length; i += 1) {
  21803. var ecmaVersion = list[i];
  21804. buildUnicodeData(ecmaVersion);
  21805. }
  21806. var pp$1 = Parser.prototype;
  21807. var RegExpValidationState = function RegExpValidationState(parser) {
  21808. this.parser = parser;
  21809. this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : "") + (parser.options.ecmaVersion >= 15 ? "v" : "");
  21810. this.unicodeProperties = data[parser.options.ecmaVersion >= 14 ? 14 : parser.options.ecmaVersion];
  21811. this.source = "";
  21812. this.flags = "";
  21813. this.start = 0;
  21814. this.switchU = false;
  21815. this.switchV = false;
  21816. this.switchN = false;
  21817. this.pos = 0;
  21818. this.lastIntValue = 0;
  21819. this.lastStringValue = "";
  21820. this.lastAssertionIsQuantifiable = false;
  21821. this.numCapturingParens = 0;
  21822. this.maxBackReference = 0;
  21823. this.groupNames = [];
  21824. this.backReferenceNames = [];
  21825. };
  21826. RegExpValidationState.prototype.reset = function reset (start, pattern, flags) {
  21827. var unicodeSets = flags.indexOf("v") !== -1;
  21828. var unicode = flags.indexOf("u") !== -1;
  21829. this.start = start | 0;
  21830. this.source = pattern + "";
  21831. this.flags = flags;
  21832. if (unicodeSets && this.parser.options.ecmaVersion >= 15) {
  21833. this.switchU = true;
  21834. this.switchV = true;
  21835. this.switchN = true;
  21836. } else {
  21837. this.switchU = unicode && this.parser.options.ecmaVersion >= 6;
  21838. this.switchV = false;
  21839. this.switchN = unicode && this.parser.options.ecmaVersion >= 9;
  21840. }
  21841. };
  21842. RegExpValidationState.prototype.raise = function raise (message) {
  21843. this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message));
  21844. };
  21845. // If u flag is given, this returns the code point at the index (it combines a surrogate pair).
  21846. // Otherwise, this returns the code unit of the index (can be a part of a surrogate pair).
  21847. RegExpValidationState.prototype.at = function at (i, forceU) {
  21848. if ( forceU === void 0 ) forceU = false;
  21849. var s = this.source;
  21850. var l = s.length;
  21851. if (i >= l) {
  21852. return -1
  21853. }
  21854. var c = s.charCodeAt(i);
  21855. if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) {
  21856. return c
  21857. }
  21858. var next = s.charCodeAt(i + 1);
  21859. return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c
  21860. };
  21861. RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) {
  21862. if ( forceU === void 0 ) forceU = false;
  21863. var s = this.source;
  21864. var l = s.length;
  21865. if (i >= l) {
  21866. return l
  21867. }
  21868. var c = s.charCodeAt(i), next;
  21869. if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l ||
  21870. (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) {
  21871. return i + 1
  21872. }
  21873. return i + 2
  21874. };
  21875. RegExpValidationState.prototype.current = function current (forceU) {
  21876. if ( forceU === void 0 ) forceU = false;
  21877. return this.at(this.pos, forceU)
  21878. };
  21879. RegExpValidationState.prototype.lookahead = function lookahead (forceU) {
  21880. if ( forceU === void 0 ) forceU = false;
  21881. return this.at(this.nextIndex(this.pos, forceU), forceU)
  21882. };
  21883. RegExpValidationState.prototype.advance = function advance (forceU) {
  21884. if ( forceU === void 0 ) forceU = false;
  21885. this.pos = this.nextIndex(this.pos, forceU);
  21886. };
  21887. RegExpValidationState.prototype.eat = function eat (ch, forceU) {
  21888. if ( forceU === void 0 ) forceU = false;
  21889. if (this.current(forceU) === ch) {
  21890. this.advance(forceU);
  21891. return true
  21892. }
  21893. return false
  21894. };
  21895. RegExpValidationState.prototype.eatChars = function eatChars (chs, forceU) {
  21896. if ( forceU === void 0 ) forceU = false;
  21897. var pos = this.pos;
  21898. for (var i = 0, list = chs; i < list.length; i += 1) {
  21899. var ch = list[i];
  21900. var current = this.at(pos, forceU);
  21901. if (current === -1 || current !== ch) {
  21902. return false
  21903. }
  21904. pos = this.nextIndex(pos, forceU);
  21905. }
  21906. this.pos = pos;
  21907. return true
  21908. };
  21909. /**
  21910. * Validate the flags part of a given RegExpLiteral.
  21911. *
  21912. * @param {RegExpValidationState} state The state to validate RegExp.
  21913. * @returns {void}
  21914. */
  21915. pp$1.validateRegExpFlags = function(state) {
  21916. var validFlags = state.validFlags;
  21917. var flags = state.flags;
  21918. var u = false;
  21919. var v = false;
  21920. for (var i = 0; i < flags.length; i++) {
  21921. var flag = flags.charAt(i);
  21922. if (validFlags.indexOf(flag) === -1) {
  21923. this.raise(state.start, "Invalid regular expression flag");
  21924. }
  21925. if (flags.indexOf(flag, i + 1) > -1) {
  21926. this.raise(state.start, "Duplicate regular expression flag");
  21927. }
  21928. if (flag === "u") { u = true; }
  21929. if (flag === "v") { v = true; }
  21930. }
  21931. if (this.options.ecmaVersion >= 15 && u && v) {
  21932. this.raise(state.start, "Invalid regular expression flag");
  21933. }
  21934. };
  21935. /**
  21936. * Validate the pattern part of a given RegExpLiteral.
  21937. *
  21938. * @param {RegExpValidationState} state The state to validate RegExp.
  21939. * @returns {void}
  21940. */
  21941. pp$1.validateRegExpPattern = function(state) {
  21942. this.regexp_pattern(state);
  21943. // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of
  21944. // parsing contains a |GroupName|, reparse with the goal symbol
  21945. // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError*
  21946. // exception if _P_ did not conform to the grammar, if any elements of _P_
  21947. // were not matched by the parse, or if any Early Error conditions exist.
  21948. if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) {
  21949. state.switchN = true;
  21950. this.regexp_pattern(state);
  21951. }
  21952. };
  21953. // https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern
  21954. pp$1.regexp_pattern = function(state) {
  21955. state.pos = 0;
  21956. state.lastIntValue = 0;
  21957. state.lastStringValue = "";
  21958. state.lastAssertionIsQuantifiable = false;
  21959. state.numCapturingParens = 0;
  21960. state.maxBackReference = 0;
  21961. state.groupNames.length = 0;
  21962. state.backReferenceNames.length = 0;
  21963. this.regexp_disjunction(state);
  21964. if (state.pos !== state.source.length) {
  21965. // Make the same messages as V8.
  21966. if (state.eat(0x29 /* ) */)) {
  21967. state.raise("Unmatched ')'");
  21968. }
  21969. if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) {
  21970. state.raise("Lone quantifier brackets");
  21971. }
  21972. }
  21973. if (state.maxBackReference > state.numCapturingParens) {
  21974. state.raise("Invalid escape");
  21975. }
  21976. for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) {
  21977. var name = list[i];
  21978. if (state.groupNames.indexOf(name) === -1) {
  21979. state.raise("Invalid named capture referenced");
  21980. }
  21981. }
  21982. };
  21983. // https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction
  21984. pp$1.regexp_disjunction = function(state) {
  21985. this.regexp_alternative(state);
  21986. while (state.eat(0x7C /* | */)) {
  21987. this.regexp_alternative(state);
  21988. }
  21989. // Make the same message as V8.
  21990. if (this.regexp_eatQuantifier(state, true)) {
  21991. state.raise("Nothing to repeat");
  21992. }
  21993. if (state.eat(0x7B /* { */)) {
  21994. state.raise("Lone quantifier brackets");
  21995. }
  21996. };
  21997. // https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative
  21998. pp$1.regexp_alternative = function(state) {
  21999. while (state.pos < state.source.length && this.regexp_eatTerm(state))
  22000. { }
  22001. };
  22002. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term
  22003. pp$1.regexp_eatTerm = function(state) {
  22004. if (this.regexp_eatAssertion(state)) {
  22005. // Handle `QuantifiableAssertion Quantifier` alternative.
  22006. // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion
  22007. // is a QuantifiableAssertion.
  22008. if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) {
  22009. // Make the same message as V8.
  22010. if (state.switchU) {
  22011. state.raise("Invalid quantifier");
  22012. }
  22013. }
  22014. return true
  22015. }
  22016. if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) {
  22017. this.regexp_eatQuantifier(state);
  22018. return true
  22019. }
  22020. return false
  22021. };
  22022. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion
  22023. pp$1.regexp_eatAssertion = function(state) {
  22024. var start = state.pos;
  22025. state.lastAssertionIsQuantifiable = false;
  22026. // ^, $
  22027. if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) {
  22028. return true
  22029. }
  22030. // \b \B
  22031. if (state.eat(0x5C /* \ */)) {
  22032. if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) {
  22033. return true
  22034. }
  22035. state.pos = start;
  22036. }
  22037. // Lookahead / Lookbehind
  22038. if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) {
  22039. var lookbehind = false;
  22040. if (this.options.ecmaVersion >= 9) {
  22041. lookbehind = state.eat(0x3C /* < */);
  22042. }
  22043. if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) {
  22044. this.regexp_disjunction(state);
  22045. if (!state.eat(0x29 /* ) */)) {
  22046. state.raise("Unterminated group");
  22047. }
  22048. state.lastAssertionIsQuantifiable = !lookbehind;
  22049. return true
  22050. }
  22051. }
  22052. state.pos = start;
  22053. return false
  22054. };
  22055. // https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier
  22056. pp$1.regexp_eatQuantifier = function(state, noError) {
  22057. if ( noError === void 0 ) noError = false;
  22058. if (this.regexp_eatQuantifierPrefix(state, noError)) {
  22059. state.eat(0x3F /* ? */);
  22060. return true
  22061. }
  22062. return false
  22063. };
  22064. // https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix
  22065. pp$1.regexp_eatQuantifierPrefix = function(state, noError) {
  22066. return (
  22067. state.eat(0x2A /* * */) ||
  22068. state.eat(0x2B /* + */) ||
  22069. state.eat(0x3F /* ? */) ||
  22070. this.regexp_eatBracedQuantifier(state, noError)
  22071. )
  22072. };
  22073. pp$1.regexp_eatBracedQuantifier = function(state, noError) {
  22074. var start = state.pos;
  22075. if (state.eat(0x7B /* { */)) {
  22076. var min = 0, max = -1;
  22077. if (this.regexp_eatDecimalDigits(state)) {
  22078. min = state.lastIntValue;
  22079. if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) {
  22080. max = state.lastIntValue;
  22081. }
  22082. if (state.eat(0x7D /* } */)) {
  22083. // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term
  22084. if (max !== -1 && max < min && !noError) {
  22085. state.raise("numbers out of order in {} quantifier");
  22086. }
  22087. return true
  22088. }
  22089. }
  22090. if (state.switchU && !noError) {
  22091. state.raise("Incomplete quantifier");
  22092. }
  22093. state.pos = start;
  22094. }
  22095. return false
  22096. };
  22097. // https://www.ecma-international.org/ecma-262/8.0/#prod-Atom
  22098. pp$1.regexp_eatAtom = function(state) {
  22099. return (
  22100. this.regexp_eatPatternCharacters(state) ||
  22101. state.eat(0x2E /* . */) ||
  22102. this.regexp_eatReverseSolidusAtomEscape(state) ||
  22103. this.regexp_eatCharacterClass(state) ||
  22104. this.regexp_eatUncapturingGroup(state) ||
  22105. this.regexp_eatCapturingGroup(state)
  22106. )
  22107. };
  22108. pp$1.regexp_eatReverseSolidusAtomEscape = function(state) {
  22109. var start = state.pos;
  22110. if (state.eat(0x5C /* \ */)) {
  22111. if (this.regexp_eatAtomEscape(state)) {
  22112. return true
  22113. }
  22114. state.pos = start;
  22115. }
  22116. return false
  22117. };
  22118. pp$1.regexp_eatUncapturingGroup = function(state) {
  22119. var start = state.pos;
  22120. if (state.eat(0x28 /* ( */)) {
  22121. if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) {
  22122. this.regexp_disjunction(state);
  22123. if (state.eat(0x29 /* ) */)) {
  22124. return true
  22125. }
  22126. state.raise("Unterminated group");
  22127. }
  22128. state.pos = start;
  22129. }
  22130. return false
  22131. };
  22132. pp$1.regexp_eatCapturingGroup = function(state) {
  22133. if (state.eat(0x28 /* ( */)) {
  22134. if (this.options.ecmaVersion >= 9) {
  22135. this.regexp_groupSpecifier(state);
  22136. } else if (state.current() === 0x3F /* ? */) {
  22137. state.raise("Invalid group");
  22138. }
  22139. this.regexp_disjunction(state);
  22140. if (state.eat(0x29 /* ) */)) {
  22141. state.numCapturingParens += 1;
  22142. return true
  22143. }
  22144. state.raise("Unterminated group");
  22145. }
  22146. return false
  22147. };
  22148. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom
  22149. pp$1.regexp_eatExtendedAtom = function(state) {
  22150. return (
  22151. state.eat(0x2E /* . */) ||
  22152. this.regexp_eatReverseSolidusAtomEscape(state) ||
  22153. this.regexp_eatCharacterClass(state) ||
  22154. this.regexp_eatUncapturingGroup(state) ||
  22155. this.regexp_eatCapturingGroup(state) ||
  22156. this.regexp_eatInvalidBracedQuantifier(state) ||
  22157. this.regexp_eatExtendedPatternCharacter(state)
  22158. )
  22159. };
  22160. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier
  22161. pp$1.regexp_eatInvalidBracedQuantifier = function(state) {
  22162. if (this.regexp_eatBracedQuantifier(state, true)) {
  22163. state.raise("Nothing to repeat");
  22164. }
  22165. return false
  22166. };
  22167. // https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter
  22168. pp$1.regexp_eatSyntaxCharacter = function(state) {
  22169. var ch = state.current();
  22170. if (isSyntaxCharacter(ch)) {
  22171. state.lastIntValue = ch;
  22172. state.advance();
  22173. return true
  22174. }
  22175. return false
  22176. };
  22177. function isSyntaxCharacter(ch) {
  22178. return (
  22179. ch === 0x24 /* $ */ ||
  22180. ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ ||
  22181. ch === 0x2E /* . */ ||
  22182. ch === 0x3F /* ? */ ||
  22183. ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ ||
  22184. ch >= 0x7B /* { */ && ch <= 0x7D /* } */
  22185. )
  22186. }
  22187. // https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter
  22188. // But eat eager.
  22189. pp$1.regexp_eatPatternCharacters = function(state) {
  22190. var start = state.pos;
  22191. var ch = 0;
  22192. while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) {
  22193. state.advance();
  22194. }
  22195. return state.pos !== start
  22196. };
  22197. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter
  22198. pp$1.regexp_eatExtendedPatternCharacter = function(state) {
  22199. var ch = state.current();
  22200. if (
  22201. ch !== -1 &&
  22202. ch !== 0x24 /* $ */ &&
  22203. !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) &&
  22204. ch !== 0x2E /* . */ &&
  22205. ch !== 0x3F /* ? */ &&
  22206. ch !== 0x5B /* [ */ &&
  22207. ch !== 0x5E /* ^ */ &&
  22208. ch !== 0x7C /* | */
  22209. ) {
  22210. state.advance();
  22211. return true
  22212. }
  22213. return false
  22214. };
  22215. // GroupSpecifier ::
  22216. // [empty]
  22217. // `?` GroupName
  22218. pp$1.regexp_groupSpecifier = function(state) {
  22219. if (state.eat(0x3F /* ? */)) {
  22220. if (this.regexp_eatGroupName(state)) {
  22221. if (state.groupNames.indexOf(state.lastStringValue) !== -1) {
  22222. state.raise("Duplicate capture group name");
  22223. }
  22224. state.groupNames.push(state.lastStringValue);
  22225. return
  22226. }
  22227. state.raise("Invalid group");
  22228. }
  22229. };
  22230. // GroupName ::
  22231. // `<` RegExpIdentifierName `>`
  22232. // Note: this updates `state.lastStringValue` property with the eaten name.
  22233. pp$1.regexp_eatGroupName = function(state) {
  22234. state.lastStringValue = "";
  22235. if (state.eat(0x3C /* < */)) {
  22236. if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) {
  22237. return true
  22238. }
  22239. state.raise("Invalid capture group name");
  22240. }
  22241. return false
  22242. };
  22243. // RegExpIdentifierName ::
  22244. // RegExpIdentifierStart
  22245. // RegExpIdentifierName RegExpIdentifierPart
  22246. // Note: this updates `state.lastStringValue` property with the eaten name.
  22247. pp$1.regexp_eatRegExpIdentifierName = function(state) {
  22248. state.lastStringValue = "";
  22249. if (this.regexp_eatRegExpIdentifierStart(state)) {
  22250. state.lastStringValue += codePointToString(state.lastIntValue);
  22251. while (this.regexp_eatRegExpIdentifierPart(state)) {
  22252. state.lastStringValue += codePointToString(state.lastIntValue);
  22253. }
  22254. return true
  22255. }
  22256. return false
  22257. };
  22258. // RegExpIdentifierStart ::
  22259. // UnicodeIDStart
  22260. // `$`
  22261. // `_`
  22262. // `\` RegExpUnicodeEscapeSequence[+U]
  22263. pp$1.regexp_eatRegExpIdentifierStart = function(state) {
  22264. var start = state.pos;
  22265. var forceU = this.options.ecmaVersion >= 11;
  22266. var ch = state.current(forceU);
  22267. state.advance(forceU);
  22268. if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
  22269. ch = state.lastIntValue;
  22270. }
  22271. if (isRegExpIdentifierStart(ch)) {
  22272. state.lastIntValue = ch;
  22273. return true
  22274. }
  22275. state.pos = start;
  22276. return false
  22277. };
  22278. function isRegExpIdentifierStart(ch) {
  22279. return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */
  22280. }
  22281. // RegExpIdentifierPart ::
  22282. // UnicodeIDContinue
  22283. // `$`
  22284. // `_`
  22285. // `\` RegExpUnicodeEscapeSequence[+U]
  22286. // <ZWNJ>
  22287. // <ZWJ>
  22288. pp$1.regexp_eatRegExpIdentifierPart = function(state) {
  22289. var start = state.pos;
  22290. var forceU = this.options.ecmaVersion >= 11;
  22291. var ch = state.current(forceU);
  22292. state.advance(forceU);
  22293. if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
  22294. ch = state.lastIntValue;
  22295. }
  22296. if (isRegExpIdentifierPart(ch)) {
  22297. state.lastIntValue = ch;
  22298. return true
  22299. }
  22300. state.pos = start;
  22301. return false
  22302. };
  22303. function isRegExpIdentifierPart(ch) {
  22304. return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* <ZWNJ> */ || ch === 0x200D /* <ZWJ> */
  22305. }
  22306. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape
  22307. pp$1.regexp_eatAtomEscape = function(state) {
  22308. if (
  22309. this.regexp_eatBackReference(state) ||
  22310. this.regexp_eatCharacterClassEscape(state) ||
  22311. this.regexp_eatCharacterEscape(state) ||
  22312. (state.switchN && this.regexp_eatKGroupName(state))
  22313. ) {
  22314. return true
  22315. }
  22316. if (state.switchU) {
  22317. // Make the same message as V8.
  22318. if (state.current() === 0x63 /* c */) {
  22319. state.raise("Invalid unicode escape");
  22320. }
  22321. state.raise("Invalid escape");
  22322. }
  22323. return false
  22324. };
  22325. pp$1.regexp_eatBackReference = function(state) {
  22326. var start = state.pos;
  22327. if (this.regexp_eatDecimalEscape(state)) {
  22328. var n = state.lastIntValue;
  22329. if (state.switchU) {
  22330. // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape
  22331. if (n > state.maxBackReference) {
  22332. state.maxBackReference = n;
  22333. }
  22334. return true
  22335. }
  22336. if (n <= state.numCapturingParens) {
  22337. return true
  22338. }
  22339. state.pos = start;
  22340. }
  22341. return false
  22342. };
  22343. pp$1.regexp_eatKGroupName = function(state) {
  22344. if (state.eat(0x6B /* k */)) {
  22345. if (this.regexp_eatGroupName(state)) {
  22346. state.backReferenceNames.push(state.lastStringValue);
  22347. return true
  22348. }
  22349. state.raise("Invalid named reference");
  22350. }
  22351. return false
  22352. };
  22353. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape
  22354. pp$1.regexp_eatCharacterEscape = function(state) {
  22355. return (
  22356. this.regexp_eatControlEscape(state) ||
  22357. this.regexp_eatCControlLetter(state) ||
  22358. this.regexp_eatZero(state) ||
  22359. this.regexp_eatHexEscapeSequence(state) ||
  22360. this.regexp_eatRegExpUnicodeEscapeSequence(state, false) ||
  22361. (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) ||
  22362. this.regexp_eatIdentityEscape(state)
  22363. )
  22364. };
  22365. pp$1.regexp_eatCControlLetter = function(state) {
  22366. var start = state.pos;
  22367. if (state.eat(0x63 /* c */)) {
  22368. if (this.regexp_eatControlLetter(state)) {
  22369. return true
  22370. }
  22371. state.pos = start;
  22372. }
  22373. return false
  22374. };
  22375. pp$1.regexp_eatZero = function(state) {
  22376. if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) {
  22377. state.lastIntValue = 0;
  22378. state.advance();
  22379. return true
  22380. }
  22381. return false
  22382. };
  22383. // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape
  22384. pp$1.regexp_eatControlEscape = function(state) {
  22385. var ch = state.current();
  22386. if (ch === 0x74 /* t */) {
  22387. state.lastIntValue = 0x09; /* \t */
  22388. state.advance();
  22389. return true
  22390. }
  22391. if (ch === 0x6E /* n */) {
  22392. state.lastIntValue = 0x0A; /* \n */
  22393. state.advance();
  22394. return true
  22395. }
  22396. if (ch === 0x76 /* v */) {
  22397. state.lastIntValue = 0x0B; /* \v */
  22398. state.advance();
  22399. return true
  22400. }
  22401. if (ch === 0x66 /* f */) {
  22402. state.lastIntValue = 0x0C; /* \f */
  22403. state.advance();
  22404. return true
  22405. }
  22406. if (ch === 0x72 /* r */) {
  22407. state.lastIntValue = 0x0D; /* \r */
  22408. state.advance();
  22409. return true
  22410. }
  22411. return false
  22412. };
  22413. // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter
  22414. pp$1.regexp_eatControlLetter = function(state) {
  22415. var ch = state.current();
  22416. if (isControlLetter(ch)) {
  22417. state.lastIntValue = ch % 0x20;
  22418. state.advance();
  22419. return true
  22420. }
  22421. return false
  22422. };
  22423. function isControlLetter(ch) {
  22424. return (
  22425. (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) ||
  22426. (ch >= 0x61 /* a */ && ch <= 0x7A /* z */)
  22427. )
  22428. }
  22429. // https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence
  22430. pp$1.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) {
  22431. if ( forceU === void 0 ) forceU = false;
  22432. var start = state.pos;
  22433. var switchU = forceU || state.switchU;
  22434. if (state.eat(0x75 /* u */)) {
  22435. if (this.regexp_eatFixedHexDigits(state, 4)) {
  22436. var lead = state.lastIntValue;
  22437. if (switchU && lead >= 0xD800 && lead <= 0xDBFF) {
  22438. var leadSurrogateEnd = state.pos;
  22439. if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) {
  22440. var trail = state.lastIntValue;
  22441. if (trail >= 0xDC00 && trail <= 0xDFFF) {
  22442. state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
  22443. return true
  22444. }
  22445. }
  22446. state.pos = leadSurrogateEnd;
  22447. state.lastIntValue = lead;
  22448. }
  22449. return true
  22450. }
  22451. if (
  22452. switchU &&
  22453. state.eat(0x7B /* { */) &&
  22454. this.regexp_eatHexDigits(state) &&
  22455. state.eat(0x7D /* } */) &&
  22456. isValidUnicode(state.lastIntValue)
  22457. ) {
  22458. return true
  22459. }
  22460. if (switchU) {
  22461. state.raise("Invalid unicode escape");
  22462. }
  22463. state.pos = start;
  22464. }
  22465. return false
  22466. };
  22467. function isValidUnicode(ch) {
  22468. return ch >= 0 && ch <= 0x10FFFF
  22469. }
  22470. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape
  22471. pp$1.regexp_eatIdentityEscape = function(state) {
  22472. if (state.switchU) {
  22473. if (this.regexp_eatSyntaxCharacter(state)) {
  22474. return true
  22475. }
  22476. if (state.eat(0x2F /* / */)) {
  22477. state.lastIntValue = 0x2F; /* / */
  22478. return true
  22479. }
  22480. return false
  22481. }
  22482. var ch = state.current();
  22483. if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) {
  22484. state.lastIntValue = ch;
  22485. state.advance();
  22486. return true
  22487. }
  22488. return false
  22489. };
  22490. // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape
  22491. pp$1.regexp_eatDecimalEscape = function(state) {
  22492. state.lastIntValue = 0;
  22493. var ch = state.current();
  22494. if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) {
  22495. do {
  22496. state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
  22497. state.advance();
  22498. } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */)
  22499. return true
  22500. }
  22501. return false
  22502. };
  22503. // Return values used by character set parsing methods, needed to
  22504. // forbid negation of sets that can match strings.
  22505. var CharSetNone = 0; // Nothing parsed
  22506. var CharSetOk = 1; // Construct parsed, cannot contain strings
  22507. var CharSetString = 2; // Construct parsed, can contain strings
  22508. // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape
  22509. pp$1.regexp_eatCharacterClassEscape = function(state) {
  22510. var ch = state.current();
  22511. if (isCharacterClassEscape(ch)) {
  22512. state.lastIntValue = -1;
  22513. state.advance();
  22514. return CharSetOk
  22515. }
  22516. var negate = false;
  22517. if (
  22518. state.switchU &&
  22519. this.options.ecmaVersion >= 9 &&
  22520. ((negate = ch === 0x50 /* P */) || ch === 0x70 /* p */)
  22521. ) {
  22522. state.lastIntValue = -1;
  22523. state.advance();
  22524. var result;
  22525. if (
  22526. state.eat(0x7B /* { */) &&
  22527. (result = this.regexp_eatUnicodePropertyValueExpression(state)) &&
  22528. state.eat(0x7D /* } */)
  22529. ) {
  22530. if (negate && result === CharSetString) { state.raise("Invalid property name"); }
  22531. return result
  22532. }
  22533. state.raise("Invalid property name");
  22534. }
  22535. return CharSetNone
  22536. };
  22537. function isCharacterClassEscape(ch) {
  22538. return (
  22539. ch === 0x64 /* d */ ||
  22540. ch === 0x44 /* D */ ||
  22541. ch === 0x73 /* s */ ||
  22542. ch === 0x53 /* S */ ||
  22543. ch === 0x77 /* w */ ||
  22544. ch === 0x57 /* W */
  22545. )
  22546. }
  22547. // UnicodePropertyValueExpression ::
  22548. // UnicodePropertyName `=` UnicodePropertyValue
  22549. // LoneUnicodePropertyNameOrValue
  22550. pp$1.regexp_eatUnicodePropertyValueExpression = function(state) {
  22551. var start = state.pos;
  22552. // UnicodePropertyName `=` UnicodePropertyValue
  22553. if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) {
  22554. var name = state.lastStringValue;
  22555. if (this.regexp_eatUnicodePropertyValue(state)) {
  22556. var value = state.lastStringValue;
  22557. this.regexp_validateUnicodePropertyNameAndValue(state, name, value);
  22558. return CharSetOk
  22559. }
  22560. }
  22561. state.pos = start;
  22562. // LoneUnicodePropertyNameOrValue
  22563. if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {
  22564. var nameOrValue = state.lastStringValue;
  22565. return this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue)
  22566. }
  22567. return CharSetNone
  22568. };
  22569. pp$1.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {
  22570. if (!hasOwn(state.unicodeProperties.nonBinary, name))
  22571. { state.raise("Invalid property name"); }
  22572. if (!state.unicodeProperties.nonBinary[name].test(value))
  22573. { state.raise("Invalid property value"); }
  22574. };
  22575. pp$1.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) {
  22576. if (state.unicodeProperties.binary.test(nameOrValue)) { return CharSetOk }
  22577. if (state.switchV && state.unicodeProperties.binaryOfStrings.test(nameOrValue)) { return CharSetString }
  22578. state.raise("Invalid property name");
  22579. };
  22580. // UnicodePropertyName ::
  22581. // UnicodePropertyNameCharacters
  22582. pp$1.regexp_eatUnicodePropertyName = function(state) {
  22583. var ch = 0;
  22584. state.lastStringValue = "";
  22585. while (isUnicodePropertyNameCharacter(ch = state.current())) {
  22586. state.lastStringValue += codePointToString(ch);
  22587. state.advance();
  22588. }
  22589. return state.lastStringValue !== ""
  22590. };
  22591. function isUnicodePropertyNameCharacter(ch) {
  22592. return isControlLetter(ch) || ch === 0x5F /* _ */
  22593. }
  22594. // UnicodePropertyValue ::
  22595. // UnicodePropertyValueCharacters
  22596. pp$1.regexp_eatUnicodePropertyValue = function(state) {
  22597. var ch = 0;
  22598. state.lastStringValue = "";
  22599. while (isUnicodePropertyValueCharacter(ch = state.current())) {
  22600. state.lastStringValue += codePointToString(ch);
  22601. state.advance();
  22602. }
  22603. return state.lastStringValue !== ""
  22604. };
  22605. function isUnicodePropertyValueCharacter(ch) {
  22606. return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch)
  22607. }
  22608. // LoneUnicodePropertyNameOrValue ::
  22609. // UnicodePropertyValueCharacters
  22610. pp$1.regexp_eatLoneUnicodePropertyNameOrValue = function(state) {
  22611. return this.regexp_eatUnicodePropertyValue(state)
  22612. };
  22613. // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass
  22614. pp$1.regexp_eatCharacterClass = function(state) {
  22615. if (state.eat(0x5B /* [ */)) {
  22616. var negate = state.eat(0x5E /* ^ */);
  22617. var result = this.regexp_classContents(state);
  22618. if (!state.eat(0x5D /* ] */))
  22619. { state.raise("Unterminated character class"); }
  22620. if (negate && result === CharSetString)
  22621. { state.raise("Negated character class may contain strings"); }
  22622. return true
  22623. }
  22624. return false
  22625. };
  22626. // https://tc39.es/ecma262/#prod-ClassContents
  22627. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges
  22628. pp$1.regexp_classContents = function(state) {
  22629. if (state.current() === 0x5D /* ] */) { return CharSetOk }
  22630. if (state.switchV) { return this.regexp_classSetExpression(state) }
  22631. this.regexp_nonEmptyClassRanges(state);
  22632. return CharSetOk
  22633. };
  22634. // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges
  22635. // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash
  22636. pp$1.regexp_nonEmptyClassRanges = function(state) {
  22637. while (this.regexp_eatClassAtom(state)) {
  22638. var left = state.lastIntValue;
  22639. if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) {
  22640. var right = state.lastIntValue;
  22641. if (state.switchU && (left === -1 || right === -1)) {
  22642. state.raise("Invalid character class");
  22643. }
  22644. if (left !== -1 && right !== -1 && left > right) {
  22645. state.raise("Range out of order in character class");
  22646. }
  22647. }
  22648. }
  22649. };
  22650. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom
  22651. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash
  22652. pp$1.regexp_eatClassAtom = function(state) {
  22653. var start = state.pos;
  22654. if (state.eat(0x5C /* \ */)) {
  22655. if (this.regexp_eatClassEscape(state)) {
  22656. return true
  22657. }
  22658. if (state.switchU) {
  22659. // Make the same message as V8.
  22660. var ch$1 = state.current();
  22661. if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) {
  22662. state.raise("Invalid class escape");
  22663. }
  22664. state.raise("Invalid escape");
  22665. }
  22666. state.pos = start;
  22667. }
  22668. var ch = state.current();
  22669. if (ch !== 0x5D /* ] */) {
  22670. state.lastIntValue = ch;
  22671. state.advance();
  22672. return true
  22673. }
  22674. return false
  22675. };
  22676. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape
  22677. pp$1.regexp_eatClassEscape = function(state) {
  22678. var start = state.pos;
  22679. if (state.eat(0x62 /* b */)) {
  22680. state.lastIntValue = 0x08; /* <BS> */
  22681. return true
  22682. }
  22683. if (state.switchU && state.eat(0x2D /* - */)) {
  22684. state.lastIntValue = 0x2D; /* - */
  22685. return true
  22686. }
  22687. if (!state.switchU && state.eat(0x63 /* c */)) {
  22688. if (this.regexp_eatClassControlLetter(state)) {
  22689. return true
  22690. }
  22691. state.pos = start;
  22692. }
  22693. return (
  22694. this.regexp_eatCharacterClassEscape(state) ||
  22695. this.regexp_eatCharacterEscape(state)
  22696. )
  22697. };
  22698. // https://tc39.es/ecma262/#prod-ClassSetExpression
  22699. // https://tc39.es/ecma262/#prod-ClassUnion
  22700. // https://tc39.es/ecma262/#prod-ClassIntersection
  22701. // https://tc39.es/ecma262/#prod-ClassSubtraction
  22702. pp$1.regexp_classSetExpression = function(state) {
  22703. var result = CharSetOk, subResult;
  22704. if (this.regexp_eatClassSetRange(state)) ; else if (subResult = this.regexp_eatClassSetOperand(state)) {
  22705. if (subResult === CharSetString) { result = CharSetString; }
  22706. // https://tc39.es/ecma262/#prod-ClassIntersection
  22707. var start = state.pos;
  22708. while (state.eatChars([0x26, 0x26] /* && */)) {
  22709. if (
  22710. state.current() !== 0x26 /* & */ &&
  22711. (subResult = this.regexp_eatClassSetOperand(state))
  22712. ) {
  22713. if (subResult !== CharSetString) { result = CharSetOk; }
  22714. continue
  22715. }
  22716. state.raise("Invalid character in character class");
  22717. }
  22718. if (start !== state.pos) { return result }
  22719. // https://tc39.es/ecma262/#prod-ClassSubtraction
  22720. while (state.eatChars([0x2D, 0x2D] /* -- */)) {
  22721. if (this.regexp_eatClassSetOperand(state)) { continue }
  22722. state.raise("Invalid character in character class");
  22723. }
  22724. if (start !== state.pos) { return result }
  22725. } else {
  22726. state.raise("Invalid character in character class");
  22727. }
  22728. // https://tc39.es/ecma262/#prod-ClassUnion
  22729. for (;;) {
  22730. if (this.regexp_eatClassSetRange(state)) { continue }
  22731. subResult = this.regexp_eatClassSetOperand(state);
  22732. if (!subResult) { return result }
  22733. if (subResult === CharSetString) { result = CharSetString; }
  22734. }
  22735. };
  22736. // https://tc39.es/ecma262/#prod-ClassSetRange
  22737. pp$1.regexp_eatClassSetRange = function(state) {
  22738. var start = state.pos;
  22739. if (this.regexp_eatClassSetCharacter(state)) {
  22740. var left = state.lastIntValue;
  22741. if (state.eat(0x2D /* - */) && this.regexp_eatClassSetCharacter(state)) {
  22742. var right = state.lastIntValue;
  22743. if (left !== -1 && right !== -1 && left > right) {
  22744. state.raise("Range out of order in character class");
  22745. }
  22746. return true
  22747. }
  22748. state.pos = start;
  22749. }
  22750. return false
  22751. };
  22752. // https://tc39.es/ecma262/#prod-ClassSetOperand
  22753. pp$1.regexp_eatClassSetOperand = function(state) {
  22754. if (this.regexp_eatClassSetCharacter(state)) { return CharSetOk }
  22755. return this.regexp_eatClassStringDisjunction(state) || this.regexp_eatNestedClass(state)
  22756. };
  22757. // https://tc39.es/ecma262/#prod-NestedClass
  22758. pp$1.regexp_eatNestedClass = function(state) {
  22759. var start = state.pos;
  22760. if (state.eat(0x5B /* [ */)) {
  22761. var negate = state.eat(0x5E /* ^ */);
  22762. var result = this.regexp_classContents(state);
  22763. if (state.eat(0x5D /* ] */)) {
  22764. if (negate && result === CharSetString) {
  22765. state.raise("Negated character class may contain strings");
  22766. }
  22767. return result
  22768. }
  22769. state.pos = start;
  22770. }
  22771. if (state.eat(0x5C /* \ */)) {
  22772. var result$1 = this.regexp_eatCharacterClassEscape(state);
  22773. if (result$1) {
  22774. return result$1
  22775. }
  22776. state.pos = start;
  22777. }
  22778. return null
  22779. };
  22780. // https://tc39.es/ecma262/#prod-ClassStringDisjunction
  22781. pp$1.regexp_eatClassStringDisjunction = function(state) {
  22782. var start = state.pos;
  22783. if (state.eatChars([0x5C, 0x71] /* \q */)) {
  22784. if (state.eat(0x7B /* { */)) {
  22785. var result = this.regexp_classStringDisjunctionContents(state);
  22786. if (state.eat(0x7D /* } */)) {
  22787. return result
  22788. }
  22789. } else {
  22790. // Make the same message as V8.
  22791. state.raise("Invalid escape");
  22792. }
  22793. state.pos = start;
  22794. }
  22795. return null
  22796. };
  22797. // https://tc39.es/ecma262/#prod-ClassStringDisjunctionContents
  22798. pp$1.regexp_classStringDisjunctionContents = function(state) {
  22799. var result = this.regexp_classString(state);
  22800. while (state.eat(0x7C /* | */)) {
  22801. if (this.regexp_classString(state) === CharSetString) { result = CharSetString; }
  22802. }
  22803. return result
  22804. };
  22805. // https://tc39.es/ecma262/#prod-ClassString
  22806. // https://tc39.es/ecma262/#prod-NonEmptyClassString
  22807. pp$1.regexp_classString = function(state) {
  22808. var count = 0;
  22809. while (this.regexp_eatClassSetCharacter(state)) { count++; }
  22810. return count === 1 ? CharSetOk : CharSetString
  22811. };
  22812. // https://tc39.es/ecma262/#prod-ClassSetCharacter
  22813. pp$1.regexp_eatClassSetCharacter = function(state) {
  22814. var start = state.pos;
  22815. if (state.eat(0x5C /* \ */)) {
  22816. if (
  22817. this.regexp_eatCharacterEscape(state) ||
  22818. this.regexp_eatClassSetReservedPunctuator(state)
  22819. ) {
  22820. return true
  22821. }
  22822. if (state.eat(0x62 /* b */)) {
  22823. state.lastIntValue = 0x08; /* <BS> */
  22824. return true
  22825. }
  22826. state.pos = start;
  22827. return false
  22828. }
  22829. var ch = state.current();
  22830. if (ch < 0 || ch === state.lookahead() && isClassSetReservedDoublePunctuatorCharacter(ch)) { return false }
  22831. if (isClassSetSyntaxCharacter(ch)) { return false }
  22832. state.advance();
  22833. state.lastIntValue = ch;
  22834. return true
  22835. };
  22836. // https://tc39.es/ecma262/#prod-ClassSetReservedDoublePunctuator
  22837. function isClassSetReservedDoublePunctuatorCharacter(ch) {
  22838. return (
  22839. ch === 0x21 /* ! */ ||
  22840. ch >= 0x23 /* # */ && ch <= 0x26 /* & */ ||
  22841. ch >= 0x2A /* * */ && ch <= 0x2C /* , */ ||
  22842. ch === 0x2E /* . */ ||
  22843. ch >= 0x3A /* : */ && ch <= 0x40 /* @ */ ||
  22844. ch === 0x5E /* ^ */ ||
  22845. ch === 0x60 /* ` */ ||
  22846. ch === 0x7E /* ~ */
  22847. )
  22848. }
  22849. // https://tc39.es/ecma262/#prod-ClassSetSyntaxCharacter
  22850. function isClassSetSyntaxCharacter(ch) {
  22851. return (
  22852. ch === 0x28 /* ( */ ||
  22853. ch === 0x29 /* ) */ ||
  22854. ch === 0x2D /* - */ ||
  22855. ch === 0x2F /* / */ ||
  22856. ch >= 0x5B /* [ */ && ch <= 0x5D /* ] */ ||
  22857. ch >= 0x7B /* { */ && ch <= 0x7D /* } */
  22858. )
  22859. }
  22860. // https://tc39.es/ecma262/#prod-ClassSetReservedPunctuator
  22861. pp$1.regexp_eatClassSetReservedPunctuator = function(state) {
  22862. var ch = state.current();
  22863. if (isClassSetReservedPunctuator(ch)) {
  22864. state.lastIntValue = ch;
  22865. state.advance();
  22866. return true
  22867. }
  22868. return false
  22869. };
  22870. // https://tc39.es/ecma262/#prod-ClassSetReservedPunctuator
  22871. function isClassSetReservedPunctuator(ch) {
  22872. return (
  22873. ch === 0x21 /* ! */ ||
  22874. ch === 0x23 /* # */ ||
  22875. ch === 0x25 /* % */ ||
  22876. ch === 0x26 /* & */ ||
  22877. ch === 0x2C /* , */ ||
  22878. ch === 0x2D /* - */ ||
  22879. ch >= 0x3A /* : */ && ch <= 0x3E /* > */ ||
  22880. ch === 0x40 /* @ */ ||
  22881. ch === 0x60 /* ` */ ||
  22882. ch === 0x7E /* ~ */
  22883. )
  22884. }
  22885. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter
  22886. pp$1.regexp_eatClassControlLetter = function(state) {
  22887. var ch = state.current();
  22888. if (isDecimalDigit(ch) || ch === 0x5F /* _ */) {
  22889. state.lastIntValue = ch % 0x20;
  22890. state.advance();
  22891. return true
  22892. }
  22893. return false
  22894. };
  22895. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
  22896. pp$1.regexp_eatHexEscapeSequence = function(state) {
  22897. var start = state.pos;
  22898. if (state.eat(0x78 /* x */)) {
  22899. if (this.regexp_eatFixedHexDigits(state, 2)) {
  22900. return true
  22901. }
  22902. if (state.switchU) {
  22903. state.raise("Invalid escape");
  22904. }
  22905. state.pos = start;
  22906. }
  22907. return false
  22908. };
  22909. // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits
  22910. pp$1.regexp_eatDecimalDigits = function(state) {
  22911. var start = state.pos;
  22912. var ch = 0;
  22913. state.lastIntValue = 0;
  22914. while (isDecimalDigit(ch = state.current())) {
  22915. state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
  22916. state.advance();
  22917. }
  22918. return state.pos !== start
  22919. };
  22920. function isDecimalDigit(ch) {
  22921. return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */
  22922. }
  22923. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits
  22924. pp$1.regexp_eatHexDigits = function(state) {
  22925. var start = state.pos;
  22926. var ch = 0;
  22927. state.lastIntValue = 0;
  22928. while (isHexDigit(ch = state.current())) {
  22929. state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
  22930. state.advance();
  22931. }
  22932. return state.pos !== start
  22933. };
  22934. function isHexDigit(ch) {
  22935. return (
  22936. (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) ||
  22937. (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) ||
  22938. (ch >= 0x61 /* a */ && ch <= 0x66 /* f */)
  22939. )
  22940. }
  22941. function hexToInt(ch) {
  22942. if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) {
  22943. return 10 + (ch - 0x41 /* A */)
  22944. }
  22945. if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) {
  22946. return 10 + (ch - 0x61 /* a */)
  22947. }
  22948. return ch - 0x30 /* 0 */
  22949. }
  22950. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence
  22951. // Allows only 0-377(octal) i.e. 0-255(decimal).
  22952. pp$1.regexp_eatLegacyOctalEscapeSequence = function(state) {
  22953. if (this.regexp_eatOctalDigit(state)) {
  22954. var n1 = state.lastIntValue;
  22955. if (this.regexp_eatOctalDigit(state)) {
  22956. var n2 = state.lastIntValue;
  22957. if (n1 <= 3 && this.regexp_eatOctalDigit(state)) {
  22958. state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue;
  22959. } else {
  22960. state.lastIntValue = n1 * 8 + n2;
  22961. }
  22962. } else {
  22963. state.lastIntValue = n1;
  22964. }
  22965. return true
  22966. }
  22967. return false
  22968. };
  22969. // https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit
  22970. pp$1.regexp_eatOctalDigit = function(state) {
  22971. var ch = state.current();
  22972. if (isOctalDigit(ch)) {
  22973. state.lastIntValue = ch - 0x30; /* 0 */
  22974. state.advance();
  22975. return true
  22976. }
  22977. state.lastIntValue = 0;
  22978. return false
  22979. };
  22980. function isOctalDigit(ch) {
  22981. return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */
  22982. }
  22983. // https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits
  22984. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit
  22985. // And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
  22986. pp$1.regexp_eatFixedHexDigits = function(state, length) {
  22987. var start = state.pos;
  22988. state.lastIntValue = 0;
  22989. for (var i = 0; i < length; ++i) {
  22990. var ch = state.current();
  22991. if (!isHexDigit(ch)) {
  22992. state.pos = start;
  22993. return false
  22994. }
  22995. state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
  22996. state.advance();
  22997. }
  22998. return true
  22999. };
  23000. // Object type used to represent tokens. Note that normally, tokens
  23001. // simply exist as properties on the parser object. This is only
  23002. // used for the onToken callback and the external tokenizer.
  23003. var Token = function Token(p) {
  23004. this.type = p.type;
  23005. this.value = p.value;
  23006. this.start = p.start;
  23007. this.end = p.end;
  23008. if (p.options.locations)
  23009. { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); }
  23010. if (p.options.ranges)
  23011. { this.range = [p.start, p.end]; }
  23012. };
  23013. // ## Tokenizer
  23014. var pp = Parser.prototype;
  23015. // Move to the next token
  23016. pp.next = function(ignoreEscapeSequenceInKeyword) {
  23017. if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc)
  23018. { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); }
  23019. if (this.options.onToken)
  23020. { this.options.onToken(new Token(this)); }
  23021. this.lastTokEnd = this.end;
  23022. this.lastTokStart = this.start;
  23023. this.lastTokEndLoc = this.endLoc;
  23024. this.lastTokStartLoc = this.startLoc;
  23025. this.nextToken();
  23026. };
  23027. pp.getToken = function() {
  23028. this.next();
  23029. return new Token(this)
  23030. };
  23031. // If we're in an ES6 environment, make parsers iterable
  23032. if (typeof Symbol !== "undefined")
  23033. { pp[Symbol.iterator] = function() {
  23034. var this$1$1 = this;
  23035. return {
  23036. next: function () {
  23037. var token = this$1$1.getToken();
  23038. return {
  23039. done: token.type === types$1.eof,
  23040. value: token
  23041. }
  23042. }
  23043. }
  23044. }; }
  23045. // Toggle strict mode. Re-reads the next number or string to please
  23046. // pedantic tests (`"use strict"; 010;` should fail).
  23047. // Read a single token, updating the parser object's token-related
  23048. // properties.
  23049. pp.nextToken = function() {
  23050. var curContext = this.curContext();
  23051. if (!curContext || !curContext.preserveSpace) { this.skipSpace(); }
  23052. this.start = this.pos;
  23053. if (this.options.locations) { this.startLoc = this.curPosition(); }
  23054. if (this.pos >= this.input.length) { return this.finishToken(types$1.eof) }
  23055. if (curContext.override) { return curContext.override(this) }
  23056. else { this.readToken(this.fullCharCodeAtPos()); }
  23057. };
  23058. pp.readToken = function(code) {
  23059. // Identifier or keyword. '\uXXXX' sequences are allowed in
  23060. // identifiers, so '\' also dispatches to that.
  23061. if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)
  23062. { return this.readWord() }
  23063. return this.getTokenFromCode(code)
  23064. };
  23065. pp.fullCharCodeAtPos = function() {
  23066. var code = this.input.charCodeAt(this.pos);
  23067. if (code <= 0xd7ff || code >= 0xdc00) { return code }
  23068. var next = this.input.charCodeAt(this.pos + 1);
  23069. return next <= 0xdbff || next >= 0xe000 ? code : (code << 10) + next - 0x35fdc00
  23070. };
  23071. pp.skipBlockComment = function() {
  23072. var startLoc = this.options.onComment && this.curPosition();
  23073. var start = this.pos, end = this.input.indexOf("*/", this.pos += 2);
  23074. if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); }
  23075. this.pos = end + 2;
  23076. if (this.options.locations) {
  23077. for (var nextBreak = (void 0), pos = start; (nextBreak = nextLineBreak(this.input, pos, this.pos)) > -1;) {
  23078. ++this.curLine;
  23079. pos = this.lineStart = nextBreak;
  23080. }
  23081. }
  23082. if (this.options.onComment)
  23083. { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,
  23084. startLoc, this.curPosition()); }
  23085. };
  23086. pp.skipLineComment = function(startSkip) {
  23087. var start = this.pos;
  23088. var startLoc = this.options.onComment && this.curPosition();
  23089. var ch = this.input.charCodeAt(this.pos += startSkip);
  23090. while (this.pos < this.input.length && !isNewLine(ch)) {
  23091. ch = this.input.charCodeAt(++this.pos);
  23092. }
  23093. if (this.options.onComment)
  23094. { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos,
  23095. startLoc, this.curPosition()); }
  23096. };
  23097. // Called at the start of the parse and after every token. Skips
  23098. // whitespace and comments, and.
  23099. pp.skipSpace = function() {
  23100. loop: while (this.pos < this.input.length) {
  23101. var ch = this.input.charCodeAt(this.pos);
  23102. switch (ch) {
  23103. case 32: case 160: // ' '
  23104. ++this.pos;
  23105. break
  23106. case 13:
  23107. if (this.input.charCodeAt(this.pos + 1) === 10) {
  23108. ++this.pos;
  23109. }
  23110. case 10: case 8232: case 8233:
  23111. ++this.pos;
  23112. if (this.options.locations) {
  23113. ++this.curLine;
  23114. this.lineStart = this.pos;
  23115. }
  23116. break
  23117. case 47: // '/'
  23118. switch (this.input.charCodeAt(this.pos + 1)) {
  23119. case 42: // '*'
  23120. this.skipBlockComment();
  23121. break
  23122. case 47:
  23123. this.skipLineComment(2);
  23124. break
  23125. default:
  23126. break loop
  23127. }
  23128. break
  23129. default:
  23130. if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
  23131. ++this.pos;
  23132. } else {
  23133. break loop
  23134. }
  23135. }
  23136. }
  23137. };
  23138. // Called at the end of every token. Sets `end`, `val`, and
  23139. // maintains `context` and `exprAllowed`, and skips the space after
  23140. // the token, so that the next one's `start` will point at the
  23141. // right position.
  23142. pp.finishToken = function(type, val) {
  23143. this.end = this.pos;
  23144. if (this.options.locations) { this.endLoc = this.curPosition(); }
  23145. var prevType = this.type;
  23146. this.type = type;
  23147. this.value = val;
  23148. this.updateContext(prevType);
  23149. };
  23150. // ### Token reading
  23151. // This is the function that is called to fetch the next token. It
  23152. // is somewhat obscure, because it works in character codes rather
  23153. // than characters, and because operator parsing has been inlined
  23154. // into it.
  23155. //
  23156. // All in the name of speed.
  23157. //
  23158. pp.readToken_dot = function() {
  23159. var next = this.input.charCodeAt(this.pos + 1);
  23160. if (next >= 48 && next <= 57) { return this.readNumber(true) }
  23161. var next2 = this.input.charCodeAt(this.pos + 2);
  23162. if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'
  23163. this.pos += 3;
  23164. return this.finishToken(types$1.ellipsis)
  23165. } else {
  23166. ++this.pos;
  23167. return this.finishToken(types$1.dot)
  23168. }
  23169. };
  23170. pp.readToken_slash = function() { // '/'
  23171. var next = this.input.charCodeAt(this.pos + 1);
  23172. if (this.exprAllowed) { ++this.pos; return this.readRegexp() }
  23173. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  23174. return this.finishOp(types$1.slash, 1)
  23175. };
  23176. pp.readToken_mult_modulo_exp = function(code) { // '%*'
  23177. var next = this.input.charCodeAt(this.pos + 1);
  23178. var size = 1;
  23179. var tokentype = code === 42 ? types$1.star : types$1.modulo;
  23180. // exponentiation operator ** and **=
  23181. if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) {
  23182. ++size;
  23183. tokentype = types$1.starstar;
  23184. next = this.input.charCodeAt(this.pos + 2);
  23185. }
  23186. if (next === 61) { return this.finishOp(types$1.assign, size + 1) }
  23187. return this.finishOp(tokentype, size)
  23188. };
  23189. pp.readToken_pipe_amp = function(code) { // '|&'
  23190. var next = this.input.charCodeAt(this.pos + 1);
  23191. if (next === code) {
  23192. if (this.options.ecmaVersion >= 12) {
  23193. var next2 = this.input.charCodeAt(this.pos + 2);
  23194. if (next2 === 61) { return this.finishOp(types$1.assign, 3) }
  23195. }
  23196. return this.finishOp(code === 124 ? types$1.logicalOR : types$1.logicalAND, 2)
  23197. }
  23198. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  23199. return this.finishOp(code === 124 ? types$1.bitwiseOR : types$1.bitwiseAND, 1)
  23200. };
  23201. pp.readToken_caret = function() { // '^'
  23202. var next = this.input.charCodeAt(this.pos + 1);
  23203. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  23204. return this.finishOp(types$1.bitwiseXOR, 1)
  23205. };
  23206. pp.readToken_plus_min = function(code) { // '+-'
  23207. var next = this.input.charCodeAt(this.pos + 1);
  23208. if (next === code) {
  23209. if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 &&
  23210. (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {
  23211. // A `-->` line comment
  23212. this.skipLineComment(3);
  23213. this.skipSpace();
  23214. return this.nextToken()
  23215. }
  23216. return this.finishOp(types$1.incDec, 2)
  23217. }
  23218. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  23219. return this.finishOp(types$1.plusMin, 1)
  23220. };
  23221. pp.readToken_lt_gt = function(code) { // '<>'
  23222. var next = this.input.charCodeAt(this.pos + 1);
  23223. var size = 1;
  23224. if (next === code) {
  23225. size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
  23226. if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types$1.assign, size + 1) }
  23227. return this.finishOp(types$1.bitShift, size)
  23228. }
  23229. if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 &&
  23230. this.input.charCodeAt(this.pos + 3) === 45) {
  23231. // `<!--`, an XML-style comment that should be interpreted as a line comment
  23232. this.skipLineComment(4);
  23233. this.skipSpace();
  23234. return this.nextToken()
  23235. }
  23236. if (next === 61) { size = 2; }
  23237. return this.finishOp(types$1.relational, size)
  23238. };
  23239. pp.readToken_eq_excl = function(code) { // '=!'
  23240. var next = this.input.charCodeAt(this.pos + 1);
  23241. if (next === 61) { return this.finishOp(types$1.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2) }
  23242. if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { // '=>'
  23243. this.pos += 2;
  23244. return this.finishToken(types$1.arrow)
  23245. }
  23246. return this.finishOp(code === 61 ? types$1.eq : types$1.prefix, 1)
  23247. };
  23248. pp.readToken_question = function() { // '?'
  23249. var ecmaVersion = this.options.ecmaVersion;
  23250. if (ecmaVersion >= 11) {
  23251. var next = this.input.charCodeAt(this.pos + 1);
  23252. if (next === 46) {
  23253. var next2 = this.input.charCodeAt(this.pos + 2);
  23254. if (next2 < 48 || next2 > 57) { return this.finishOp(types$1.questionDot, 2) }
  23255. }
  23256. if (next === 63) {
  23257. if (ecmaVersion >= 12) {
  23258. var next2$1 = this.input.charCodeAt(this.pos + 2);
  23259. if (next2$1 === 61) { return this.finishOp(types$1.assign, 3) }
  23260. }
  23261. return this.finishOp(types$1.coalesce, 2)
  23262. }
  23263. }
  23264. return this.finishOp(types$1.question, 1)
  23265. };
  23266. pp.readToken_numberSign = function() { // '#'
  23267. var ecmaVersion = this.options.ecmaVersion;
  23268. var code = 35; // '#'
  23269. if (ecmaVersion >= 13) {
  23270. ++this.pos;
  23271. code = this.fullCharCodeAtPos();
  23272. if (isIdentifierStart(code, true) || code === 92 /* '\' */) {
  23273. return this.finishToken(types$1.privateId, this.readWord1())
  23274. }
  23275. }
  23276. this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
  23277. };
  23278. pp.getTokenFromCode = function(code) {
  23279. switch (code) {
  23280. // The interpretation of a dot depends on whether it is followed
  23281. // by a digit or another two dots.
  23282. case 46: // '.'
  23283. return this.readToken_dot()
  23284. // Punctuation tokens.
  23285. case 40: ++this.pos; return this.finishToken(types$1.parenL)
  23286. case 41: ++this.pos; return this.finishToken(types$1.parenR)
  23287. case 59: ++this.pos; return this.finishToken(types$1.semi)
  23288. case 44: ++this.pos; return this.finishToken(types$1.comma)
  23289. case 91: ++this.pos; return this.finishToken(types$1.bracketL)
  23290. case 93: ++this.pos; return this.finishToken(types$1.bracketR)
  23291. case 123: ++this.pos; return this.finishToken(types$1.braceL)
  23292. case 125: ++this.pos; return this.finishToken(types$1.braceR)
  23293. case 58: ++this.pos; return this.finishToken(types$1.colon)
  23294. case 96: // '`'
  23295. if (this.options.ecmaVersion < 6) { break }
  23296. ++this.pos;
  23297. return this.finishToken(types$1.backQuote)
  23298. case 48: // '0'
  23299. var next = this.input.charCodeAt(this.pos + 1);
  23300. if (next === 120 || next === 88) { return this.readRadixNumber(16) } // '0x', '0X' - hex number
  23301. if (this.options.ecmaVersion >= 6) {
  23302. if (next === 111 || next === 79) { return this.readRadixNumber(8) } // '0o', '0O' - octal number
  23303. if (next === 98 || next === 66) { return this.readRadixNumber(2) } // '0b', '0B' - binary number
  23304. }
  23305. // Anything else beginning with a digit is an integer, octal
  23306. // number, or float.
  23307. case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9
  23308. return this.readNumber(false)
  23309. // Quotes produce strings.
  23310. case 34: case 39: // '"', "'"
  23311. return this.readString(code)
  23312. // Operators are parsed inline in tiny state machines. '=' (61) is
  23313. // often referred to. `finishOp` simply skips the amount of
  23314. // characters it is given as second argument, and returns a token
  23315. // of the type given by its first argument.
  23316. case 47: // '/'
  23317. return this.readToken_slash()
  23318. case 37: case 42: // '%*'
  23319. return this.readToken_mult_modulo_exp(code)
  23320. case 124: case 38: // '|&'
  23321. return this.readToken_pipe_amp(code)
  23322. case 94: // '^'
  23323. return this.readToken_caret()
  23324. case 43: case 45: // '+-'
  23325. return this.readToken_plus_min(code)
  23326. case 60: case 62: // '<>'
  23327. return this.readToken_lt_gt(code)
  23328. case 61: case 33: // '=!'
  23329. return this.readToken_eq_excl(code)
  23330. case 63: // '?'
  23331. return this.readToken_question()
  23332. case 126: // '~'
  23333. return this.finishOp(types$1.prefix, 1)
  23334. case 35: // '#'
  23335. return this.readToken_numberSign()
  23336. }
  23337. this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
  23338. };
  23339. pp.finishOp = function(type, size) {
  23340. var str = this.input.slice(this.pos, this.pos + size);
  23341. this.pos += size;
  23342. return this.finishToken(type, str)
  23343. };
  23344. pp.readRegexp = function() {
  23345. var escaped, inClass, start = this.pos;
  23346. for (;;) {
  23347. if (this.pos >= this.input.length) { this.raise(start, "Unterminated regular expression"); }
  23348. var ch = this.input.charAt(this.pos);
  23349. if (lineBreak.test(ch)) { this.raise(start, "Unterminated regular expression"); }
  23350. if (!escaped) {
  23351. if (ch === "[") { inClass = true; }
  23352. else if (ch === "]" && inClass) { inClass = false; }
  23353. else if (ch === "/" && !inClass) { break }
  23354. escaped = ch === "\\";
  23355. } else { escaped = false; }
  23356. ++this.pos;
  23357. }
  23358. var pattern = this.input.slice(start, this.pos);
  23359. ++this.pos;
  23360. var flagsStart = this.pos;
  23361. var flags = this.readWord1();
  23362. if (this.containsEsc) { this.unexpected(flagsStart); }
  23363. // Validate pattern
  23364. var state = this.regexpState || (this.regexpState = new RegExpValidationState(this));
  23365. state.reset(start, pattern, flags);
  23366. this.validateRegExpFlags(state);
  23367. this.validateRegExpPattern(state);
  23368. // Create Literal#value property value.
  23369. var value = null;
  23370. try {
  23371. value = new RegExp(pattern, flags);
  23372. } catch (e) {
  23373. // ESTree requires null if it failed to instantiate RegExp object.
  23374. // https://github.com/estree/estree/blob/a27003adf4fd7bfad44de9cef372a2eacd527b1c/es5.md#regexpliteral
  23375. }
  23376. return this.finishToken(types$1.regexp, {pattern: pattern, flags: flags, value: value})
  23377. };
  23378. // Read an integer in the given radix. Return null if zero digits
  23379. // were read, the integer value otherwise. When `len` is given, this
  23380. // will return `null` unless the integer has exactly `len` digits.
  23381. pp.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) {
  23382. // `len` is used for character escape sequences. In that case, disallow separators.
  23383. var allowSeparators = this.options.ecmaVersion >= 12 && len === undefined;
  23384. // `maybeLegacyOctalNumericLiteral` is true if it doesn't have prefix (0x,0o,0b)
  23385. // and isn't fraction part nor exponent part. In that case, if the first digit
  23386. // is zero then disallow separators.
  23387. var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48;
  23388. var start = this.pos, total = 0, lastCode = 0;
  23389. for (var i = 0, e = len == null ? Infinity : len; i < e; ++i, ++this.pos) {
  23390. var code = this.input.charCodeAt(this.pos), val = (void 0);
  23391. if (allowSeparators && code === 95) {
  23392. if (isLegacyOctalNumericLiteral) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals"); }
  23393. if (lastCode === 95) { this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore"); }
  23394. if (i === 0) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits"); }
  23395. lastCode = code;
  23396. continue
  23397. }
  23398. if (code >= 97) { val = code - 97 + 10; } // a
  23399. else if (code >= 65) { val = code - 65 + 10; } // A
  23400. else if (code >= 48 && code <= 57) { val = code - 48; } // 0-9
  23401. else { val = Infinity; }
  23402. if (val >= radix) { break }
  23403. lastCode = code;
  23404. total = total * radix + val;
  23405. }
  23406. if (allowSeparators && lastCode === 95) { this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits"); }
  23407. if (this.pos === start || len != null && this.pos - start !== len) { return null }
  23408. return total
  23409. };
  23410. function stringToNumber(str, isLegacyOctalNumericLiteral) {
  23411. if (isLegacyOctalNumericLiteral) {
  23412. return parseInt(str, 8)
  23413. }
  23414. // `parseFloat(value)` stops parsing at the first numeric separator then returns a wrong value.
  23415. return parseFloat(str.replace(/_/g, ""))
  23416. }
  23417. function stringToBigInt(str) {
  23418. if (typeof BigInt !== "function") {
  23419. return null
  23420. }
  23421. // `BigInt(value)` throws syntax error if the string contains numeric separators.
  23422. return BigInt(str.replace(/_/g, ""))
  23423. }
  23424. pp.readRadixNumber = function(radix) {
  23425. var start = this.pos;
  23426. this.pos += 2; // 0x
  23427. var val = this.readInt(radix);
  23428. if (val == null) { this.raise(this.start + 2, "Expected number in radix " + radix); }
  23429. if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
  23430. val = stringToBigInt(this.input.slice(start, this.pos));
  23431. ++this.pos;
  23432. } else if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  23433. return this.finishToken(types$1.num, val)
  23434. };
  23435. // Read an integer, octal integer, or floating-point number.
  23436. pp.readNumber = function(startsWithDot) {
  23437. var start = this.pos;
  23438. if (!startsWithDot && this.readInt(10, undefined, true) === null) { this.raise(start, "Invalid number"); }
  23439. var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  23440. if (octal && this.strict) { this.raise(start, "Invalid number"); }
  23441. var next = this.input.charCodeAt(this.pos);
  23442. if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {
  23443. var val$1 = stringToBigInt(this.input.slice(start, this.pos));
  23444. ++this.pos;
  23445. if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  23446. return this.finishToken(types$1.num, val$1)
  23447. }
  23448. if (octal && /[89]/.test(this.input.slice(start, this.pos))) { octal = false; }
  23449. if (next === 46 && !octal) { // '.'
  23450. ++this.pos;
  23451. this.readInt(10);
  23452. next = this.input.charCodeAt(this.pos);
  23453. }
  23454. if ((next === 69 || next === 101) && !octal) { // 'eE'
  23455. next = this.input.charCodeAt(++this.pos);
  23456. if (next === 43 || next === 45) { ++this.pos; } // '+-'
  23457. if (this.readInt(10) === null) { this.raise(start, "Invalid number"); }
  23458. }
  23459. if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  23460. var val = stringToNumber(this.input.slice(start, this.pos), octal);
  23461. return this.finishToken(types$1.num, val)
  23462. };
  23463. // Read a string value, interpreting backslash-escapes.
  23464. pp.readCodePoint = function() {
  23465. var ch = this.input.charCodeAt(this.pos), code;
  23466. if (ch === 123) { // '{'
  23467. if (this.options.ecmaVersion < 6) { this.unexpected(); }
  23468. var codePos = ++this.pos;
  23469. code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
  23470. ++this.pos;
  23471. if (code > 0x10FFFF) { this.invalidStringToken(codePos, "Code point out of bounds"); }
  23472. } else {
  23473. code = this.readHexChar(4);
  23474. }
  23475. return code
  23476. };
  23477. pp.readString = function(quote) {
  23478. var out = "", chunkStart = ++this.pos;
  23479. for (;;) {
  23480. if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated string constant"); }
  23481. var ch = this.input.charCodeAt(this.pos);
  23482. if (ch === quote) { break }
  23483. if (ch === 92) { // '\'
  23484. out += this.input.slice(chunkStart, this.pos);
  23485. out += this.readEscapedChar(false);
  23486. chunkStart = this.pos;
  23487. } else if (ch === 0x2028 || ch === 0x2029) {
  23488. if (this.options.ecmaVersion < 10) { this.raise(this.start, "Unterminated string constant"); }
  23489. ++this.pos;
  23490. if (this.options.locations) {
  23491. this.curLine++;
  23492. this.lineStart = this.pos;
  23493. }
  23494. } else {
  23495. if (isNewLine(ch)) { this.raise(this.start, "Unterminated string constant"); }
  23496. ++this.pos;
  23497. }
  23498. }
  23499. out += this.input.slice(chunkStart, this.pos++);
  23500. return this.finishToken(types$1.string, out)
  23501. };
  23502. // Reads template string tokens.
  23503. var INVALID_TEMPLATE_ESCAPE_ERROR = {};
  23504. pp.tryReadTemplateToken = function() {
  23505. this.inTemplateElement = true;
  23506. try {
  23507. this.readTmplToken();
  23508. } catch (err) {
  23509. if (err === INVALID_TEMPLATE_ESCAPE_ERROR) {
  23510. this.readInvalidTemplateToken();
  23511. } else {
  23512. throw err
  23513. }
  23514. }
  23515. this.inTemplateElement = false;
  23516. };
  23517. pp.invalidStringToken = function(position, message) {
  23518. if (this.inTemplateElement && this.options.ecmaVersion >= 9) {
  23519. throw INVALID_TEMPLATE_ESCAPE_ERROR
  23520. } else {
  23521. this.raise(position, message);
  23522. }
  23523. };
  23524. pp.readTmplToken = function() {
  23525. var out = "", chunkStart = this.pos;
  23526. for (;;) {
  23527. if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated template"); }
  23528. var ch = this.input.charCodeAt(this.pos);
  23529. if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) { // '`', '${'
  23530. if (this.pos === this.start && (this.type === types$1.template || this.type === types$1.invalidTemplate)) {
  23531. if (ch === 36) {
  23532. this.pos += 2;
  23533. return this.finishToken(types$1.dollarBraceL)
  23534. } else {
  23535. ++this.pos;
  23536. return this.finishToken(types$1.backQuote)
  23537. }
  23538. }
  23539. out += this.input.slice(chunkStart, this.pos);
  23540. return this.finishToken(types$1.template, out)
  23541. }
  23542. if (ch === 92) { // '\'
  23543. out += this.input.slice(chunkStart, this.pos);
  23544. out += this.readEscapedChar(true);
  23545. chunkStart = this.pos;
  23546. } else if (isNewLine(ch)) {
  23547. out += this.input.slice(chunkStart, this.pos);
  23548. ++this.pos;
  23549. switch (ch) {
  23550. case 13:
  23551. if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; }
  23552. case 10:
  23553. out += "\n";
  23554. break
  23555. default:
  23556. out += String.fromCharCode(ch);
  23557. break
  23558. }
  23559. if (this.options.locations) {
  23560. ++this.curLine;
  23561. this.lineStart = this.pos;
  23562. }
  23563. chunkStart = this.pos;
  23564. } else {
  23565. ++this.pos;
  23566. }
  23567. }
  23568. };
  23569. // Reads a template token to search for the end, without validating any escape sequences
  23570. pp.readInvalidTemplateToken = function() {
  23571. for (; this.pos < this.input.length; this.pos++) {
  23572. switch (this.input[this.pos]) {
  23573. case "\\":
  23574. ++this.pos;
  23575. break
  23576. case "$":
  23577. if (this.input[this.pos + 1] !== "{") {
  23578. break
  23579. }
  23580. // falls through
  23581. case "`":
  23582. return this.finishToken(types$1.invalidTemplate, this.input.slice(this.start, this.pos))
  23583. // no default
  23584. }
  23585. }
  23586. this.raise(this.start, "Unterminated template");
  23587. };
  23588. // Used to read escaped characters
  23589. pp.readEscapedChar = function(inTemplate) {
  23590. var ch = this.input.charCodeAt(++this.pos);
  23591. ++this.pos;
  23592. switch (ch) {
  23593. case 110: return "\n" // 'n' -> '\n'
  23594. case 114: return "\r" // 'r' -> '\r'
  23595. case 120: return String.fromCharCode(this.readHexChar(2)) // 'x'
  23596. case 117: return codePointToString(this.readCodePoint()) // 'u'
  23597. case 116: return "\t" // 't' -> '\t'
  23598. case 98: return "\b" // 'b' -> '\b'
  23599. case 118: return "\u000b" // 'v' -> '\u000b'
  23600. case 102: return "\f" // 'f' -> '\f'
  23601. case 13: if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; } // '\r\n'
  23602. case 10: // ' \n'
  23603. if (this.options.locations) { this.lineStart = this.pos; ++this.curLine; }
  23604. return ""
  23605. case 56:
  23606. case 57:
  23607. if (this.strict) {
  23608. this.invalidStringToken(
  23609. this.pos - 1,
  23610. "Invalid escape sequence"
  23611. );
  23612. }
  23613. if (inTemplate) {
  23614. var codePos = this.pos - 1;
  23615. this.invalidStringToken(
  23616. codePos,
  23617. "Invalid escape sequence in template string"
  23618. );
  23619. }
  23620. default:
  23621. if (ch >= 48 && ch <= 55) {
  23622. var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
  23623. var octal = parseInt(octalStr, 8);
  23624. if (octal > 255) {
  23625. octalStr = octalStr.slice(0, -1);
  23626. octal = parseInt(octalStr, 8);
  23627. }
  23628. this.pos += octalStr.length - 1;
  23629. ch = this.input.charCodeAt(this.pos);
  23630. if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) {
  23631. this.invalidStringToken(
  23632. this.pos - 1 - octalStr.length,
  23633. inTemplate
  23634. ? "Octal literal in template string"
  23635. : "Octal literal in strict mode"
  23636. );
  23637. }
  23638. return String.fromCharCode(octal)
  23639. }
  23640. if (isNewLine(ch)) {
  23641. // Unicode new line characters after \ get removed from output in both
  23642. // template literals and strings
  23643. return ""
  23644. }
  23645. return String.fromCharCode(ch)
  23646. }
  23647. };
  23648. // Used to read character escape sequences ('\x', '\u', '\U').
  23649. pp.readHexChar = function(len) {
  23650. var codePos = this.pos;
  23651. var n = this.readInt(16, len);
  23652. if (n === null) { this.invalidStringToken(codePos, "Bad character escape sequence"); }
  23653. return n
  23654. };
  23655. // Read an identifier, and return it as a string. Sets `this.containsEsc`
  23656. // to whether the word contained a '\u' escape.
  23657. //
  23658. // Incrementally adds only escaped chars, adding other chunks as-is
  23659. // as a micro-optimization.
  23660. pp.readWord1 = function() {
  23661. this.containsEsc = false;
  23662. var word = "", first = true, chunkStart = this.pos;
  23663. var astral = this.options.ecmaVersion >= 6;
  23664. while (this.pos < this.input.length) {
  23665. var ch = this.fullCharCodeAtPos();
  23666. if (isIdentifierChar(ch, astral)) {
  23667. this.pos += ch <= 0xffff ? 1 : 2;
  23668. } else if (ch === 92) { // "\"
  23669. this.containsEsc = true;
  23670. word += this.input.slice(chunkStart, this.pos);
  23671. var escStart = this.pos;
  23672. if (this.input.charCodeAt(++this.pos) !== 117) // "u"
  23673. { this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX"); }
  23674. ++this.pos;
  23675. var esc = this.readCodePoint();
  23676. if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral))
  23677. { this.invalidStringToken(escStart, "Invalid Unicode escape"); }
  23678. word += codePointToString(esc);
  23679. chunkStart = this.pos;
  23680. } else {
  23681. break
  23682. }
  23683. first = false;
  23684. }
  23685. return word + this.input.slice(chunkStart, this.pos)
  23686. };
  23687. // Read an identifier or keyword token. Will check for reserved
  23688. // words when necessary.
  23689. pp.readWord = function() {
  23690. var word = this.readWord1();
  23691. var type = types$1.name;
  23692. if (this.keywords.test(word)) {
  23693. type = keywords[word];
  23694. }
  23695. return this.finishToken(type, word)
  23696. };
  23697. // Acorn is a tiny, fast JavaScript parser written in JavaScript.
  23698. //
  23699. // Acorn was written by Marijn Haverbeke, Ingvar Stepanyan, and
  23700. // various contributors and released under an MIT license.
  23701. //
  23702. // Git repositories for Acorn are available at
  23703. //
  23704. // http://marijnhaverbeke.nl/git/acorn
  23705. // https://github.com/acornjs/acorn.git
  23706. //
  23707. // Please use the [github bug tracker][ghbt] to report issues.
  23708. //
  23709. // [ghbt]: https://github.com/acornjs/acorn/issues
  23710. //
  23711. // [walk]: util/walk.js
  23712. var version = "8.10.0";
  23713. Parser.acorn = {
  23714. Parser: Parser,
  23715. version: version,
  23716. defaultOptions: defaultOptions,
  23717. Position: Position,
  23718. SourceLocation: SourceLocation,
  23719. getLineInfo: getLineInfo,
  23720. Node: Node,
  23721. TokenType: TokenType,
  23722. tokTypes: types$1,
  23723. keywordTypes: keywords,
  23724. TokContext: TokContext,
  23725. tokContexts: types,
  23726. isIdentifierChar: isIdentifierChar,
  23727. isIdentifierStart: isIdentifierStart,
  23728. Token: Token,
  23729. isNewLine: isNewLine,
  23730. lineBreak: lineBreak,
  23731. lineBreakG: lineBreakG,
  23732. nonASCIIwhitespace: nonASCIIwhitespace
  23733. };
  23734. // The main exported interface (under `self.acorn` when in the
  23735. // browser) is a `parse` function that takes a code string and
  23736. // returns an abstract syntax tree as specified by [Mozilla parser
  23737. // API][api].
  23738. //
  23739. // [api]: https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API
  23740. function parse(input, options) {
  23741. return Parser.parse(input, options)
  23742. }
  23743. // This function tries to parse a single expression at a given
  23744. // offset in a string. Useful for parsing mixed-language formats
  23745. // that embed JavaScript expressions.
  23746. function parseExpressionAt(input, pos, options) {
  23747. return Parser.parseExpressionAt(input, pos, options)
  23748. }
  23749. // Acorn is organized as a tokenizer and a recursive-descent parser.
  23750. // The `tokenizer` export provides an interface to the tokenizer.
  23751. function tokenizer(input, options) {
  23752. return Parser.tokenizer(input, options)
  23753. }
  23754. const _acorn = /*#__PURE__*/Object.defineProperty({
  23755. __proto__: null,
  23756. Node,
  23757. Parser,
  23758. Position,
  23759. SourceLocation,
  23760. TokContext,
  23761. Token,
  23762. TokenType,
  23763. defaultOptions,
  23764. getLineInfo,
  23765. isIdentifierChar,
  23766. isIdentifierStart,
  23767. isNewLine,
  23768. keywordTypes: keywords,
  23769. lineBreak,
  23770. lineBreakG,
  23771. nonASCIIwhitespace,
  23772. parse,
  23773. parseExpressionAt,
  23774. tokContexts: types,
  23775. tokTypes: types$1,
  23776. tokenizer,
  23777. version
  23778. }, Symbol.toStringTag, { value: 'Module' });
  23779. function flru (max) {
  23780. var num, curr, prev;
  23781. var limit = max || 1;
  23782. function keep(key, value) {
  23783. if (++num > limit) {
  23784. prev = curr;
  23785. reset(1);
  23786. ++num;
  23787. }
  23788. curr[key] = value;
  23789. }
  23790. function reset(isPartial) {
  23791. num = 0;
  23792. curr = Object.create(null);
  23793. isPartial || (prev=Object.create(null));
  23794. }
  23795. reset();
  23796. return {
  23797. clear: reset,
  23798. has: function (key) {
  23799. return curr[key] !== void 0 || prev[key] !== void 0;
  23800. },
  23801. get: function (key) {
  23802. var val = curr[key];
  23803. if (val !== void 0) return val;
  23804. if ((val=prev[key]) !== void 0) {
  23805. keep(key, val);
  23806. return val;
  23807. }
  23808. },
  23809. set: function (key, value) {
  23810. if (curr[key] !== void 0) {
  23811. curr[key] = value;
  23812. } else {
  23813. keep(key, value);
  23814. }
  23815. }
  23816. };
  23817. }
  23818. function resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, assertions) {
  23819. let skipped = null;
  23820. let replaceContext = null;
  23821. if (skip) {
  23822. skipped = new Set();
  23823. for (const skippedCall of skip) {
  23824. if (source === skippedCall.source && importer === skippedCall.importer) {
  23825. skipped.add(skippedCall.plugin);
  23826. }
  23827. }
  23828. replaceContext = (pluginContext, plugin) => ({
  23829. ...pluginContext,
  23830. resolve: (source, importer, { assertions, custom, isEntry, skipSelf } = BLANK) => moduleLoaderResolveId(source, importer, custom, isEntry, assertions || EMPTY_OBJECT, skipSelf ? [...skip, { importer, plugin, source }] : skip)
  23831. });
  23832. }
  23833. return pluginDriver.hookFirstAndGetPlugin('resolveId', [source, importer, { assertions, custom: customOptions, isEntry }], replaceContext, skipped);
  23834. }
  23835. async function resolveId(source, importer, preserveSymlinks, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, assertions) {
  23836. const pluginResult = await resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, assertions);
  23837. if (pluginResult != null) {
  23838. const [resolveIdResult, plugin] = pluginResult;
  23839. if (typeof resolveIdResult === 'object' && !resolveIdResult.resolvedBy) {
  23840. return {
  23841. ...resolveIdResult,
  23842. resolvedBy: plugin.name
  23843. };
  23844. }
  23845. if (typeof resolveIdResult === 'string') {
  23846. return {
  23847. id: resolveIdResult,
  23848. resolvedBy: plugin.name
  23849. };
  23850. }
  23851. return resolveIdResult;
  23852. }
  23853. // external modules (non-entry modules that start with neither '.' or '/')
  23854. // are skipped at this stage.
  23855. if (importer !== undefined && !isAbsolute(source) && source[0] !== '.')
  23856. return null;
  23857. // `resolve` processes paths from right to left, prepending them until an
  23858. // absolute path is created. Absolute importees therefore shortcircuit the
  23859. // resolve call and require no special handing on our part.
  23860. // See https://nodejs.org/api/path.html#path_path_resolve_paths
  23861. return addJsExtensionIfNecessary(importer ? node_path.resolve(node_path.dirname(importer), source) : node_path.resolve(source), preserveSymlinks);
  23862. }
  23863. async function addJsExtensionIfNecessary(file, preserveSymlinks) {
  23864. return ((await findFile(file, preserveSymlinks)) ??
  23865. (await findFile(file + '.mjs', preserveSymlinks)) ??
  23866. (await findFile(file + '.js', preserveSymlinks)));
  23867. }
  23868. async function findFile(file, preserveSymlinks) {
  23869. try {
  23870. const stats = await promises.lstat(file);
  23871. if (!preserveSymlinks && stats.isSymbolicLink())
  23872. return await findFile(await promises.realpath(file), preserveSymlinks);
  23873. if ((preserveSymlinks && stats.isSymbolicLink()) || stats.isFile()) {
  23874. // check case
  23875. const name = node_path.basename(file);
  23876. const files = await promises.readdir(node_path.dirname(file));
  23877. if (files.includes(name))
  23878. return file;
  23879. }
  23880. }
  23881. catch {
  23882. // suppress
  23883. }
  23884. }
  23885. async function transform(source, module, pluginDriver, log) {
  23886. const id = module.id;
  23887. const sourcemapChain = [];
  23888. let originalSourcemap = source.map === null ? null : decodedSourcemap(source.map);
  23889. const originalCode = source.code;
  23890. let ast = source.ast;
  23891. const transformDependencies = [];
  23892. const emittedFiles = [];
  23893. let customTransformCache = false;
  23894. const useCustomTransformCache = () => (customTransformCache = true);
  23895. let pluginName = '';
  23896. let currentSource = source.code;
  23897. function transformReducer(previousCode, result, plugin) {
  23898. let code;
  23899. let map;
  23900. if (typeof result === 'string') {
  23901. code = result;
  23902. }
  23903. else if (result && typeof result === 'object') {
  23904. module.updateOptions(result);
  23905. if (result.code == null) {
  23906. if (result.map || result.ast) {
  23907. log(LOGLEVEL_WARN, logNoTransformMapOrAstWithoutCode(plugin.name));
  23908. }
  23909. return previousCode;
  23910. }
  23911. ({ code, map, ast } = result);
  23912. }
  23913. else {
  23914. return previousCode;
  23915. }
  23916. // strict null check allows 'null' maps to not be pushed to the chain,
  23917. // while 'undefined' gets the missing map warning
  23918. if (map !== null) {
  23919. sourcemapChain.push(decodedSourcemap(typeof map === 'string' ? JSON.parse(map) : map) || {
  23920. missing: true,
  23921. plugin: plugin.name
  23922. });
  23923. }
  23924. currentSource = code;
  23925. return code;
  23926. }
  23927. const getLogHandler = (handler) => (log, pos) => {
  23928. log = normalizeLog(log);
  23929. if (pos)
  23930. augmentCodeLocation(log, pos, currentSource, id);
  23931. log.id = id;
  23932. log.hook = 'transform';
  23933. handler(log);
  23934. };
  23935. let code;
  23936. try {
  23937. code = await pluginDriver.hookReduceArg0('transform', [currentSource, id], transformReducer, (pluginContext, plugin) => {
  23938. pluginName = plugin.name;
  23939. return {
  23940. ...pluginContext,
  23941. addWatchFile(id) {
  23942. transformDependencies.push(id);
  23943. pluginContext.addWatchFile(id);
  23944. },
  23945. cache: customTransformCache
  23946. ? pluginContext.cache
  23947. : getTrackedPluginCache(pluginContext.cache, useCustomTransformCache),
  23948. debug: getLogHandler(pluginContext.debug),
  23949. emitFile(emittedFile) {
  23950. emittedFiles.push(emittedFile);
  23951. return pluginDriver.emitFile(emittedFile);
  23952. },
  23953. error(error_, pos) {
  23954. if (typeof error_ === 'string')
  23955. error_ = { message: error_ };
  23956. if (pos)
  23957. augmentCodeLocation(error_, pos, currentSource, id);
  23958. error_.id = id;
  23959. error_.hook = 'transform';
  23960. return pluginContext.error(error_);
  23961. },
  23962. getCombinedSourcemap() {
  23963. const combinedMap = collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, log);
  23964. if (!combinedMap) {
  23965. const magicString = new MagicString(originalCode);
  23966. return magicString.generateMap({ hires: true, includeContent: true, source: id });
  23967. }
  23968. if (originalSourcemap !== combinedMap) {
  23969. originalSourcemap = combinedMap;
  23970. sourcemapChain.length = 0;
  23971. }
  23972. return new SourceMap({
  23973. ...combinedMap,
  23974. file: null,
  23975. sourcesContent: combinedMap.sourcesContent
  23976. });
  23977. },
  23978. info: getLogHandler(pluginContext.info),
  23979. setAssetSource() {
  23980. return this.error(logInvalidSetAssetSourceCall());
  23981. },
  23982. warn: getLogHandler(pluginContext.warn)
  23983. };
  23984. });
  23985. }
  23986. catch (error_) {
  23987. return error(logPluginError(error_, pluginName, { hook: 'transform', id }));
  23988. }
  23989. if (!customTransformCache && // files emitted by a transform hook need to be emitted again if the hook is skipped
  23990. emittedFiles.length > 0)
  23991. module.transformFiles = emittedFiles;
  23992. return {
  23993. ast,
  23994. code,
  23995. customTransformCache,
  23996. originalCode,
  23997. originalSourcemap,
  23998. sourcemapChain,
  23999. transformDependencies
  24000. };
  24001. }
  24002. const RESOLVE_DEPENDENCIES = 'resolveDependencies';
  24003. class ModuleLoader {
  24004. constructor(graph, modulesById, options, pluginDriver) {
  24005. this.graph = graph;
  24006. this.modulesById = modulesById;
  24007. this.options = options;
  24008. this.pluginDriver = pluginDriver;
  24009. this.implicitEntryModules = new Set();
  24010. this.indexedEntryModules = [];
  24011. this.latestLoadModulesPromise = Promise.resolve();
  24012. this.moduleLoadPromises = new Map();
  24013. this.modulesWithLoadedDependencies = new Set();
  24014. this.nextChunkNamePriority = 0;
  24015. this.nextEntryModuleIndex = 0;
  24016. this.resolveId = async (source, importer, customOptions, isEntry, assertions, skip = null) => this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(this.options.external(source, importer, false)
  24017. ? false
  24018. : await resolveId(source, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, skip, customOptions, typeof isEntry === 'boolean' ? isEntry : !importer, assertions), importer, source), assertions);
  24019. this.hasModuleSideEffects = options.treeshake
  24020. ? options.treeshake.moduleSideEffects
  24021. : () => true;
  24022. }
  24023. async addAdditionalModules(unresolvedModules, isAddForManualChunks) {
  24024. const result = this.extendLoadModulesPromise(Promise.all(unresolvedModules.map(id => this.loadEntryModule(id, false, undefined, null, isAddForManualChunks))));
  24025. await this.awaitLoadModulesPromise();
  24026. return result;
  24027. }
  24028. async addEntryModules(unresolvedEntryModules, isUserDefined) {
  24029. const firstEntryModuleIndex = this.nextEntryModuleIndex;
  24030. this.nextEntryModuleIndex += unresolvedEntryModules.length;
  24031. const firstChunkNamePriority = this.nextChunkNamePriority;
  24032. this.nextChunkNamePriority += unresolvedEntryModules.length;
  24033. const newEntryModules = await this.extendLoadModulesPromise(Promise.all(unresolvedEntryModules.map(({ id, importer }) => this.loadEntryModule(id, true, importer, null))).then(entryModules => {
  24034. for (const [index, entryModule] of entryModules.entries()) {
  24035. entryModule.isUserDefinedEntryPoint =
  24036. entryModule.isUserDefinedEntryPoint || isUserDefined;
  24037. addChunkNamesToModule(entryModule, unresolvedEntryModules[index], isUserDefined, firstChunkNamePriority + index);
  24038. const existingIndexedModule = this.indexedEntryModules.find(indexedModule => indexedModule.module === entryModule);
  24039. if (existingIndexedModule) {
  24040. existingIndexedModule.index = Math.min(existingIndexedModule.index, firstEntryModuleIndex + index);
  24041. }
  24042. else {
  24043. this.indexedEntryModules.push({
  24044. index: firstEntryModuleIndex + index,
  24045. module: entryModule
  24046. });
  24047. }
  24048. }
  24049. this.indexedEntryModules.sort(({ index: indexA }, { index: indexB }) => indexA > indexB ? 1 : -1);
  24050. return entryModules;
  24051. }));
  24052. await this.awaitLoadModulesPromise();
  24053. return {
  24054. entryModules: this.indexedEntryModules.map(({ module }) => module),
  24055. implicitEntryModules: [...this.implicitEntryModules],
  24056. newEntryModules
  24057. };
  24058. }
  24059. async emitChunk({ fileName, id, importer, name, implicitlyLoadedAfterOneOf, preserveSignature }) {
  24060. const unresolvedModule = {
  24061. fileName: fileName || null,
  24062. id,
  24063. importer,
  24064. name: name || null
  24065. };
  24066. const module = implicitlyLoadedAfterOneOf
  24067. ? await this.addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfterOneOf)
  24068. : (await this.addEntryModules([unresolvedModule], false)).newEntryModules[0];
  24069. if (preserveSignature != null) {
  24070. module.preserveSignature = preserveSignature;
  24071. }
  24072. return module;
  24073. }
  24074. async preloadModule(resolvedId) {
  24075. const module = await this.fetchModule(this.getResolvedIdWithDefaults(resolvedId, EMPTY_OBJECT), undefined, false, resolvedId.resolveDependencies ? RESOLVE_DEPENDENCIES : true);
  24076. return module.info;
  24077. }
  24078. addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfter) {
  24079. const chunkNamePriority = this.nextChunkNamePriority++;
  24080. return this.extendLoadModulesPromise(this.loadEntryModule(unresolvedModule.id, false, unresolvedModule.importer, null).then(async (entryModule) => {
  24081. addChunkNamesToModule(entryModule, unresolvedModule, false, chunkNamePriority);
  24082. if (!entryModule.info.isEntry) {
  24083. this.implicitEntryModules.add(entryModule);
  24084. const implicitlyLoadedAfterModules = await Promise.all(implicitlyLoadedAfter.map(id => this.loadEntryModule(id, false, unresolvedModule.importer, entryModule.id)));
  24085. for (const module of implicitlyLoadedAfterModules) {
  24086. entryModule.implicitlyLoadedAfter.add(module);
  24087. }
  24088. for (const dependant of entryModule.implicitlyLoadedAfter) {
  24089. dependant.implicitlyLoadedBefore.add(entryModule);
  24090. }
  24091. }
  24092. return entryModule;
  24093. }));
  24094. }
  24095. async addModuleSource(id, importer, module) {
  24096. let source;
  24097. try {
  24098. source = await this.graph.fileOperationQueue.run(async () => (await this.pluginDriver.hookFirst('load', [id])) ?? (await promises.readFile(id, 'utf8')));
  24099. }
  24100. catch (error_) {
  24101. let message = `Could not load ${id}`;
  24102. if (importer)
  24103. message += ` (imported by ${relativeId(importer)})`;
  24104. message += `: ${error_.message}`;
  24105. error_.message = message;
  24106. throw error_;
  24107. }
  24108. const sourceDescription = typeof source === 'string'
  24109. ? { code: source }
  24110. : source != null && typeof source === 'object' && typeof source.code === 'string'
  24111. ? source
  24112. : error(logBadLoader(id));
  24113. const cachedModule = this.graph.cachedModules.get(id);
  24114. if (cachedModule &&
  24115. !cachedModule.customTransformCache &&
  24116. cachedModule.originalCode === sourceDescription.code &&
  24117. !(await this.pluginDriver.hookFirst('shouldTransformCachedModule', [
  24118. {
  24119. ast: cachedModule.ast,
  24120. code: cachedModule.code,
  24121. id: cachedModule.id,
  24122. meta: cachedModule.meta,
  24123. moduleSideEffects: cachedModule.moduleSideEffects,
  24124. resolvedSources: cachedModule.resolvedIds,
  24125. syntheticNamedExports: cachedModule.syntheticNamedExports
  24126. }
  24127. ]))) {
  24128. if (cachedModule.transformFiles) {
  24129. for (const emittedFile of cachedModule.transformFiles)
  24130. this.pluginDriver.emitFile(emittedFile);
  24131. }
  24132. module.setSource(cachedModule);
  24133. }
  24134. else {
  24135. module.updateOptions(sourceDescription);
  24136. module.setSource(await transform(sourceDescription, module, this.pluginDriver, this.options.onLog));
  24137. }
  24138. }
  24139. async awaitLoadModulesPromise() {
  24140. let startingPromise;
  24141. do {
  24142. startingPromise = this.latestLoadModulesPromise;
  24143. await startingPromise;
  24144. } while (startingPromise !== this.latestLoadModulesPromise);
  24145. }
  24146. extendLoadModulesPromise(loadNewModulesPromise) {
  24147. this.latestLoadModulesPromise = Promise.all([
  24148. loadNewModulesPromise,
  24149. this.latestLoadModulesPromise
  24150. ]);
  24151. this.latestLoadModulesPromise.catch(() => {
  24152. /* Avoid unhandled Promise rejections */
  24153. });
  24154. return loadNewModulesPromise;
  24155. }
  24156. async fetchDynamicDependencies(module, resolveDynamicImportPromises) {
  24157. const dependencies = await Promise.all(resolveDynamicImportPromises.map(resolveDynamicImportPromise => resolveDynamicImportPromise.then(async ([dynamicImport, resolvedId]) => {
  24158. if (resolvedId === null)
  24159. return null;
  24160. if (typeof resolvedId === 'string') {
  24161. dynamicImport.resolution = resolvedId;
  24162. return null;
  24163. }
  24164. return (dynamicImport.resolution = await this.fetchResolvedDependency(relativeId(resolvedId.id), module.id, resolvedId));
  24165. })));
  24166. for (const dependency of dependencies) {
  24167. if (dependency) {
  24168. module.dynamicDependencies.add(dependency);
  24169. dependency.dynamicImporters.push(module.id);
  24170. }
  24171. }
  24172. }
  24173. // If this is a preload, then this method always waits for the dependencies of
  24174. // the module to be resolved.
  24175. // Otherwise, if the module does not exist, it waits for the module and all
  24176. // its dependencies to be loaded.
  24177. // Otherwise, it returns immediately.
  24178. async fetchModule({ assertions, id, meta, moduleSideEffects, syntheticNamedExports }, importer, isEntry, isPreload) {
  24179. const existingModule = this.modulesById.get(id);
  24180. if (existingModule instanceof Module) {
  24181. if (importer && doAssertionsDiffer(assertions, existingModule.info.assertions)) {
  24182. this.options.onLog(LOGLEVEL_WARN, logInconsistentImportAssertions(existingModule.info.assertions, assertions, id, importer));
  24183. }
  24184. await this.handleExistingModule(existingModule, isEntry, isPreload);
  24185. return existingModule;
  24186. }
  24187. if (existingModule instanceof ExternalModule) {
  24188. return error(logExternalModulesCannotBeTransformedToModules(existingModule.id));
  24189. }
  24190. const module = new Module(this.graph, id, this.options, isEntry, moduleSideEffects, syntheticNamedExports, meta, assertions);
  24191. this.modulesById.set(id, module);
  24192. this.graph.watchFiles[id] = true;
  24193. const loadPromise = this.addModuleSource(id, importer, module).then(() => [
  24194. this.getResolveStaticDependencyPromises(module),
  24195. this.getResolveDynamicImportPromises(module),
  24196. loadAndResolveDependenciesPromise
  24197. ]);
  24198. const loadAndResolveDependenciesPromise = waitForDependencyResolution(loadPromise).then(() => this.pluginDriver.hookParallel('moduleParsed', [module.info]));
  24199. loadAndResolveDependenciesPromise.catch(() => {
  24200. /* avoid unhandled promise rejections */
  24201. });
  24202. this.moduleLoadPromises.set(module, loadPromise);
  24203. const resolveDependencyPromises = await loadPromise;
  24204. if (!isPreload) {
  24205. await this.fetchModuleDependencies(module, ...resolveDependencyPromises);
  24206. }
  24207. else if (isPreload === RESOLVE_DEPENDENCIES) {
  24208. await loadAndResolveDependenciesPromise;
  24209. }
  24210. return module;
  24211. }
  24212. async fetchModuleDependencies(module, resolveStaticDependencyPromises, resolveDynamicDependencyPromises, loadAndResolveDependenciesPromise) {
  24213. if (this.modulesWithLoadedDependencies.has(module)) {
  24214. return;
  24215. }
  24216. this.modulesWithLoadedDependencies.add(module);
  24217. await Promise.all([
  24218. this.fetchStaticDependencies(module, resolveStaticDependencyPromises),
  24219. this.fetchDynamicDependencies(module, resolveDynamicDependencyPromises)
  24220. ]);
  24221. module.linkImports();
  24222. // To handle errors when resolving dependencies or in moduleParsed
  24223. await loadAndResolveDependenciesPromise;
  24224. }
  24225. fetchResolvedDependency(source, importer, resolvedId) {
  24226. if (resolvedId.external) {
  24227. const { assertions, external, id, moduleSideEffects, meta } = resolvedId;
  24228. let externalModule = this.modulesById.get(id);
  24229. if (!externalModule) {
  24230. externalModule = new ExternalModule(this.options, id, moduleSideEffects, meta, external !== 'absolute' && isAbsolute(id), assertions);
  24231. this.modulesById.set(id, externalModule);
  24232. }
  24233. else if (!(externalModule instanceof ExternalModule)) {
  24234. return error(logInternalIdCannotBeExternal(source, importer));
  24235. }
  24236. else if (doAssertionsDiffer(externalModule.info.assertions, assertions)) {
  24237. this.options.onLog(LOGLEVEL_WARN, logInconsistentImportAssertions(externalModule.info.assertions, assertions, source, importer));
  24238. }
  24239. return Promise.resolve(externalModule);
  24240. }
  24241. return this.fetchModule(resolvedId, importer, false, false);
  24242. }
  24243. async fetchStaticDependencies(module, resolveStaticDependencyPromises) {
  24244. for (const dependency of await Promise.all(resolveStaticDependencyPromises.map(resolveStaticDependencyPromise => resolveStaticDependencyPromise.then(([source, resolvedId]) => this.fetchResolvedDependency(source, module.id, resolvedId))))) {
  24245. module.dependencies.add(dependency);
  24246. dependency.importers.push(module.id);
  24247. }
  24248. if (!this.options.treeshake || module.info.moduleSideEffects === 'no-treeshake') {
  24249. for (const dependency of module.dependencies) {
  24250. if (dependency instanceof Module) {
  24251. dependency.importedFromNotTreeshaken = true;
  24252. }
  24253. }
  24254. }
  24255. }
  24256. getNormalizedResolvedIdWithoutDefaults(resolveIdResult, importer, source) {
  24257. const { makeAbsoluteExternalsRelative } = this.options;
  24258. if (resolveIdResult) {
  24259. if (typeof resolveIdResult === 'object') {
  24260. const external = resolveIdResult.external || this.options.external(resolveIdResult.id, importer, true);
  24261. return {
  24262. ...resolveIdResult,
  24263. external: external &&
  24264. (external === 'relative' ||
  24265. !isAbsolute(resolveIdResult.id) ||
  24266. (external === true &&
  24267. isNotAbsoluteExternal(resolveIdResult.id, source, makeAbsoluteExternalsRelative)) ||
  24268. 'absolute')
  24269. };
  24270. }
  24271. const external = this.options.external(resolveIdResult, importer, true);
  24272. return {
  24273. external: external &&
  24274. (isNotAbsoluteExternal(resolveIdResult, source, makeAbsoluteExternalsRelative) ||
  24275. 'absolute'),
  24276. id: external && makeAbsoluteExternalsRelative
  24277. ? normalizeRelativeExternalId(resolveIdResult, importer)
  24278. : resolveIdResult
  24279. };
  24280. }
  24281. const id = makeAbsoluteExternalsRelative
  24282. ? normalizeRelativeExternalId(source, importer)
  24283. : source;
  24284. if (resolveIdResult !== false && !this.options.external(id, importer, true)) {
  24285. return null;
  24286. }
  24287. return {
  24288. external: isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) || 'absolute',
  24289. id
  24290. };
  24291. }
  24292. getResolveDynamicImportPromises(module) {
  24293. return module.dynamicImports.map(async (dynamicImport) => {
  24294. const resolvedId = await this.resolveDynamicImport(module, typeof dynamicImport.argument === 'string'
  24295. ? dynamicImport.argument
  24296. : dynamicImport.argument.esTreeNode, module.id, getAssertionsFromImportExpression(dynamicImport.node));
  24297. if (resolvedId && typeof resolvedId === 'object') {
  24298. dynamicImport.id = resolvedId.id;
  24299. }
  24300. return [dynamicImport, resolvedId];
  24301. });
  24302. }
  24303. getResolveStaticDependencyPromises(module) {
  24304. // eslint-disable-next-line unicorn/prefer-spread
  24305. return Array.from(module.sourcesWithAssertions, async ([source, assertions]) => [
  24306. source,
  24307. (module.resolvedIds[source] =
  24308. module.resolvedIds[source] ||
  24309. this.handleInvalidResolvedId(await this.resolveId(source, module.id, EMPTY_OBJECT, false, assertions), source, module.id, assertions))
  24310. ]);
  24311. }
  24312. getResolvedIdWithDefaults(resolvedId, assertions) {
  24313. if (!resolvedId) {
  24314. return null;
  24315. }
  24316. const external = resolvedId.external || false;
  24317. return {
  24318. assertions: resolvedId.assertions || assertions,
  24319. external,
  24320. id: resolvedId.id,
  24321. meta: resolvedId.meta || {},
  24322. moduleSideEffects: resolvedId.moduleSideEffects ?? this.hasModuleSideEffects(resolvedId.id, !!external),
  24323. resolvedBy: resolvedId.resolvedBy ?? 'rollup',
  24324. syntheticNamedExports: resolvedId.syntheticNamedExports ?? false
  24325. };
  24326. }
  24327. async handleExistingModule(module, isEntry, isPreload) {
  24328. const loadPromise = this.moduleLoadPromises.get(module);
  24329. if (isPreload) {
  24330. return isPreload === RESOLVE_DEPENDENCIES
  24331. ? waitForDependencyResolution(loadPromise)
  24332. : loadPromise;
  24333. }
  24334. if (isEntry) {
  24335. module.info.isEntry = true;
  24336. this.implicitEntryModules.delete(module);
  24337. for (const dependant of module.implicitlyLoadedAfter) {
  24338. dependant.implicitlyLoadedBefore.delete(module);
  24339. }
  24340. module.implicitlyLoadedAfter.clear();
  24341. }
  24342. return this.fetchModuleDependencies(module, ...(await loadPromise));
  24343. }
  24344. handleInvalidResolvedId(resolvedId, source, importer, assertions) {
  24345. if (resolvedId === null) {
  24346. if (isRelative(source)) {
  24347. return error(logUnresolvedImport(source, importer));
  24348. }
  24349. this.options.onLog(LOGLEVEL_WARN, logUnresolvedImportTreatedAsExternal(source, importer));
  24350. return {
  24351. assertions,
  24352. external: true,
  24353. id: source,
  24354. meta: {},
  24355. moduleSideEffects: this.hasModuleSideEffects(source, true),
  24356. resolvedBy: 'rollup',
  24357. syntheticNamedExports: false
  24358. };
  24359. }
  24360. else if (resolvedId.external && resolvedId.syntheticNamedExports) {
  24361. this.options.onLog(LOGLEVEL_WARN, logExternalSyntheticExports(source, importer));
  24362. }
  24363. return resolvedId;
  24364. }
  24365. async loadEntryModule(unresolvedId, isEntry, importer, implicitlyLoadedBefore, isLoadForManualChunks = false) {
  24366. const resolveIdResult = await resolveId(unresolvedId, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, null, EMPTY_OBJECT, true, EMPTY_OBJECT);
  24367. if (resolveIdResult == null) {
  24368. return error(implicitlyLoadedBefore === null
  24369. ? logUnresolvedEntry(unresolvedId)
  24370. : logUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore));
  24371. }
  24372. const isExternalModules = typeof resolveIdResult === 'object' && resolveIdResult.external;
  24373. if (resolveIdResult === false || isExternalModules) {
  24374. return error(implicitlyLoadedBefore === null
  24375. ? isExternalModules && isLoadForManualChunks
  24376. ? logExternalModulesCannotBeIncludedInManualChunks(unresolvedId)
  24377. : logEntryCannotBeExternal(unresolvedId)
  24378. : logImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore));
  24379. }
  24380. return this.fetchModule(this.getResolvedIdWithDefaults(typeof resolveIdResult === 'object'
  24381. ? resolveIdResult
  24382. : { id: resolveIdResult }, EMPTY_OBJECT), undefined, isEntry, false);
  24383. }
  24384. async resolveDynamicImport(module, specifier, importer, assertions) {
  24385. const resolution = await this.pluginDriver.hookFirst('resolveDynamicImport', [
  24386. specifier,
  24387. importer,
  24388. { assertions }
  24389. ]);
  24390. if (typeof specifier !== 'string') {
  24391. if (typeof resolution === 'string') {
  24392. return resolution;
  24393. }
  24394. if (!resolution) {
  24395. return null;
  24396. }
  24397. return this.getResolvedIdWithDefaults(resolution, assertions);
  24398. }
  24399. if (resolution == null) {
  24400. const existingResolution = module.resolvedIds[specifier];
  24401. if (existingResolution) {
  24402. if (doAssertionsDiffer(existingResolution.assertions, assertions)) {
  24403. this.options.onLog(LOGLEVEL_WARN, logInconsistentImportAssertions(existingResolution.assertions, assertions, specifier, importer));
  24404. }
  24405. return existingResolution;
  24406. }
  24407. return (module.resolvedIds[specifier] = this.handleInvalidResolvedId(await this.resolveId(specifier, module.id, EMPTY_OBJECT, false, assertions), specifier, module.id, assertions));
  24408. }
  24409. return this.handleInvalidResolvedId(this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(resolution, importer, specifier), assertions), specifier, importer, assertions);
  24410. }
  24411. }
  24412. function normalizeRelativeExternalId(source, importer) {
  24413. return isRelative(source)
  24414. ? importer
  24415. ? node_path.resolve(importer, '..', source)
  24416. : node_path.resolve(source)
  24417. : source;
  24418. }
  24419. function addChunkNamesToModule(module, { fileName, name }, isUserDefined, priority) {
  24420. if (fileName !== null) {
  24421. module.chunkFileNames.add(fileName);
  24422. }
  24423. else if (name !== null) {
  24424. // Always keep chunkNames sorted by priority
  24425. let namePosition = 0;
  24426. while (module.chunkNames[namePosition]?.priority < priority)
  24427. namePosition++;
  24428. module.chunkNames.splice(namePosition, 0, { isUserDefined, name, priority });
  24429. }
  24430. }
  24431. function isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) {
  24432. return (makeAbsoluteExternalsRelative === true ||
  24433. (makeAbsoluteExternalsRelative === 'ifRelativeSource' && isRelative(source)) ||
  24434. !isAbsolute(id));
  24435. }
  24436. async function waitForDependencyResolution(loadPromise) {
  24437. const [resolveStaticDependencyPromises, resolveDynamicImportPromises] = await loadPromise;
  24438. return Promise.all([...resolveStaticDependencyPromises, ...resolveDynamicImportPromises]);
  24439. }
  24440. class GlobalScope extends Scope$1 {
  24441. constructor() {
  24442. super();
  24443. this.parent = null;
  24444. this.variables.set('undefined', new UndefinedVariable());
  24445. }
  24446. findVariable(name) {
  24447. let variable = this.variables.get(name);
  24448. if (!variable) {
  24449. variable = new GlobalVariable(name);
  24450. this.variables.set(name, variable);
  24451. }
  24452. return variable;
  24453. }
  24454. }
  24455. class Queue {
  24456. constructor(maxParallel) {
  24457. this.maxParallel = maxParallel;
  24458. this.queue = [];
  24459. this.workerCount = 0;
  24460. }
  24461. run(task) {
  24462. return new Promise((resolve, reject) => {
  24463. this.queue.push({ reject, resolve, task });
  24464. this.work();
  24465. });
  24466. }
  24467. async work() {
  24468. if (this.workerCount >= this.maxParallel)
  24469. return;
  24470. this.workerCount++;
  24471. let entry;
  24472. while ((entry = this.queue.shift())) {
  24473. const { reject, resolve, task } = entry;
  24474. try {
  24475. const result = await task();
  24476. resolve(result);
  24477. }
  24478. catch (error) {
  24479. reject(error);
  24480. }
  24481. }
  24482. this.workerCount--;
  24483. }
  24484. }
  24485. function normalizeEntryModules(entryModules) {
  24486. if (Array.isArray(entryModules)) {
  24487. return entryModules.map(id => ({
  24488. fileName: null,
  24489. id,
  24490. implicitlyLoadedAfter: [],
  24491. importer: undefined,
  24492. name: null
  24493. }));
  24494. }
  24495. return Object.entries(entryModules).map(([name, id]) => ({
  24496. fileName: null,
  24497. id,
  24498. implicitlyLoadedAfter: [],
  24499. importer: undefined,
  24500. name
  24501. }));
  24502. }
  24503. class Graph {
  24504. constructor(options, watcher) {
  24505. this.options = options;
  24506. this.astLru = flru(5);
  24507. this.cachedModules = new Map();
  24508. this.deoptimizationTracker = new PathTracker();
  24509. this.entryModules = [];
  24510. this.modulesById = new Map();
  24511. this.needsTreeshakingPass = false;
  24512. this.phase = BuildPhase.LOAD_AND_PARSE;
  24513. this.scope = new GlobalScope();
  24514. this.watchFiles = Object.create(null);
  24515. this.watchMode = false;
  24516. this.externalModules = [];
  24517. this.implicitEntryModules = [];
  24518. this.modules = [];
  24519. this.getModuleInfo = (moduleId) => {
  24520. const foundModule = this.modulesById.get(moduleId);
  24521. if (!foundModule)
  24522. return null;
  24523. return foundModule.info;
  24524. };
  24525. if (options.cache !== false) {
  24526. if (options.cache?.modules) {
  24527. for (const module of options.cache.modules)
  24528. this.cachedModules.set(module.id, module);
  24529. }
  24530. this.pluginCache = options.cache?.plugins || Object.create(null);
  24531. // increment access counter
  24532. for (const name in this.pluginCache) {
  24533. const cache = this.pluginCache[name];
  24534. for (const value of Object.values(cache))
  24535. value[0]++;
  24536. }
  24537. }
  24538. if (watcher) {
  24539. this.watchMode = true;
  24540. const handleChange = (...parameters) => this.pluginDriver.hookParallel('watchChange', parameters);
  24541. const handleClose = () => this.pluginDriver.hookParallel('closeWatcher', []);
  24542. watcher.onCurrentRun('change', handleChange);
  24543. watcher.onCurrentRun('close', handleClose);
  24544. }
  24545. this.pluginDriver = new PluginDriver(this, options, options.plugins, this.pluginCache);
  24546. this.acornParser = Parser.extend(...options.acornInjectPlugins);
  24547. this.moduleLoader = new ModuleLoader(this, this.modulesById, this.options, this.pluginDriver);
  24548. this.fileOperationQueue = new Queue(options.maxParallelFileOps);
  24549. this.pureFunctions = getPureFunctions(options);
  24550. }
  24551. async build() {
  24552. timeStart('generate module graph', 2);
  24553. await this.generateModuleGraph();
  24554. timeEnd('generate module graph', 2);
  24555. timeStart('sort and bind modules', 2);
  24556. this.phase = BuildPhase.ANALYSE;
  24557. this.sortModules();
  24558. timeEnd('sort and bind modules', 2);
  24559. timeStart('mark included statements', 2);
  24560. this.includeStatements();
  24561. timeEnd('mark included statements', 2);
  24562. this.phase = BuildPhase.GENERATE;
  24563. }
  24564. contextParse(code, options = {}) {
  24565. const onCommentOrig = options.onComment;
  24566. const comments = [];
  24567. options.onComment =
  24568. onCommentOrig && typeof onCommentOrig == 'function'
  24569. ? (block, text, start, end, ...parameters) => {
  24570. comments.push({ end, start, type: block ? 'Block' : 'Line', value: text });
  24571. return onCommentOrig.call(options, block, text, start, end, ...parameters);
  24572. }
  24573. : comments;
  24574. const ast = this.acornParser.parse(code, {
  24575. ...this.options.acorn,
  24576. ...options
  24577. });
  24578. if (typeof onCommentOrig == 'object') {
  24579. onCommentOrig.push(...comments);
  24580. }
  24581. options.onComment = onCommentOrig;
  24582. addAnnotations(comments, ast, code);
  24583. return ast;
  24584. }
  24585. getCache() {
  24586. // handle plugin cache eviction
  24587. for (const name in this.pluginCache) {
  24588. const cache = this.pluginCache[name];
  24589. let allDeleted = true;
  24590. for (const [key, value] of Object.entries(cache)) {
  24591. if (value[0] >= this.options.experimentalCacheExpiry)
  24592. delete cache[key];
  24593. else
  24594. allDeleted = false;
  24595. }
  24596. if (allDeleted)
  24597. delete this.pluginCache[name];
  24598. }
  24599. return {
  24600. modules: this.modules.map(module => module.toJSON()),
  24601. plugins: this.pluginCache
  24602. };
  24603. }
  24604. async generateModuleGraph() {
  24605. ({ entryModules: this.entryModules, implicitEntryModules: this.implicitEntryModules } =
  24606. await this.moduleLoader.addEntryModules(normalizeEntryModules(this.options.input), true));
  24607. if (this.entryModules.length === 0) {
  24608. throw new Error('You must supply options.input to rollup');
  24609. }
  24610. for (const module of this.modulesById.values()) {
  24611. if (module instanceof Module) {
  24612. this.modules.push(module);
  24613. }
  24614. else {
  24615. this.externalModules.push(module);
  24616. }
  24617. }
  24618. }
  24619. includeStatements() {
  24620. const entryModules = [...this.entryModules, ...this.implicitEntryModules];
  24621. for (const module of entryModules) {
  24622. markModuleAndImpureDependenciesAsExecuted(module);
  24623. }
  24624. if (this.options.treeshake) {
  24625. let treeshakingPass = 1;
  24626. do {
  24627. timeStart(`treeshaking pass ${treeshakingPass}`, 3);
  24628. this.needsTreeshakingPass = false;
  24629. for (const module of this.modules) {
  24630. if (module.isExecuted) {
  24631. if (module.info.moduleSideEffects === 'no-treeshake') {
  24632. module.includeAllInBundle();
  24633. }
  24634. else {
  24635. module.include();
  24636. }
  24637. }
  24638. }
  24639. if (treeshakingPass === 1) {
  24640. // We only include exports after the first pass to avoid issues with
  24641. // the TDZ detection logic
  24642. for (const module of entryModules) {
  24643. if (module.preserveSignature !== false) {
  24644. module.includeAllExports(false);
  24645. this.needsTreeshakingPass = true;
  24646. }
  24647. }
  24648. }
  24649. timeEnd(`treeshaking pass ${treeshakingPass++}`, 3);
  24650. } while (this.needsTreeshakingPass);
  24651. }
  24652. else {
  24653. for (const module of this.modules)
  24654. module.includeAllInBundle();
  24655. }
  24656. for (const externalModule of this.externalModules)
  24657. externalModule.warnUnusedImports();
  24658. for (const module of this.implicitEntryModules) {
  24659. for (const dependant of module.implicitlyLoadedAfter) {
  24660. if (!(dependant.info.isEntry || dependant.isIncluded())) {
  24661. error(logImplicitDependantIsNotIncluded(dependant));
  24662. }
  24663. }
  24664. }
  24665. }
  24666. sortModules() {
  24667. const { orderedModules, cyclePaths } = analyseModuleExecution(this.entryModules);
  24668. for (const cyclePath of cyclePaths) {
  24669. this.options.onLog(LOGLEVEL_WARN, logCircularDependency(cyclePath));
  24670. }
  24671. this.modules = orderedModules;
  24672. for (const module of this.modules) {
  24673. module.bindReferences();
  24674. }
  24675. this.warnForMissingExports();
  24676. }
  24677. warnForMissingExports() {
  24678. for (const module of this.modules) {
  24679. for (const importDescription of module.importDescriptions.values()) {
  24680. if (importDescription.name !== '*' &&
  24681. !importDescription.module.getVariableForExportName(importDescription.name)[0]) {
  24682. module.log(LOGLEVEL_WARN, logMissingExport(importDescription.name, module.id, importDescription.module.id), importDescription.start);
  24683. }
  24684. }
  24685. }
  24686. }
  24687. }
  24688. function formatAction([pluginName, hookName, parameters]) {
  24689. const action = `(${pluginName}) ${hookName}`;
  24690. const s = JSON.stringify;
  24691. switch (hookName) {
  24692. case 'resolveId': {
  24693. return `${action} ${s(parameters[0])} ${s(parameters[1])}`;
  24694. }
  24695. case 'load': {
  24696. return `${action} ${s(parameters[0])}`;
  24697. }
  24698. case 'transform': {
  24699. return `${action} ${s(parameters[1])}`;
  24700. }
  24701. case 'shouldTransformCachedModule': {
  24702. return `${action} ${s(parameters[0].id)}`;
  24703. }
  24704. case 'moduleParsed': {
  24705. return `${action} ${s(parameters[0].id)}`;
  24706. }
  24707. }
  24708. return action;
  24709. }
  24710. let handleBeforeExit = null;
  24711. const rejectByPluginDriver = new Map();
  24712. async function catchUnfinishedHookActions(pluginDriver, callback) {
  24713. const emptyEventLoopPromise = new Promise((_, reject) => {
  24714. rejectByPluginDriver.set(pluginDriver, reject);
  24715. if (!handleBeforeExit) {
  24716. // We only ever create a single event listener to avoid max listener and
  24717. // other issues
  24718. handleBeforeExit = () => {
  24719. for (const [pluginDriver, reject] of rejectByPluginDriver) {
  24720. const unfulfilledActions = pluginDriver.getUnfulfilledHookActions();
  24721. reject(new Error(`Unexpected early exit. This happens when Promises returned by plugins cannot resolve. Unfinished hook action(s) on exit:\n` +
  24722. [...unfulfilledActions].map(formatAction).join('\n')));
  24723. }
  24724. };
  24725. process$1.once('beforeExit', handleBeforeExit);
  24726. }
  24727. });
  24728. try {
  24729. return await Promise.race([callback(), emptyEventLoopPromise]);
  24730. }
  24731. finally {
  24732. rejectByPluginDriver.delete(pluginDriver);
  24733. if (rejectByPluginDriver.size === 0) {
  24734. process$1.off('beforeExit', handleBeforeExit);
  24735. handleBeforeExit = null;
  24736. }
  24737. }
  24738. }
  24739. const leftCurlyBrace = "{".charCodeAt(0);
  24740. const space = " ".charCodeAt(0);
  24741. const keyword = "assert";
  24742. const FUNC_STATEMENT = 1, FUNC_NULLABLE_ID = 4;
  24743. function importAssertions(Parser) {
  24744. // Use supplied version acorn version if present, to avoid
  24745. // reference mismatches due to different acorn versions. This
  24746. // allows this plugin to be used with Rollup which supplies
  24747. // its own internal version of acorn and thereby sidesteps
  24748. // the package manager.
  24749. const acorn = Parser.acorn || _acorn;
  24750. const { tokTypes: tt, TokenType } = acorn;
  24751. return class extends Parser {
  24752. constructor(...args) {
  24753. super(...args);
  24754. this.assertToken = new TokenType(keyword);
  24755. }
  24756. _codeAt(i) {
  24757. return this.input.charCodeAt(i);
  24758. }
  24759. _eat(t) {
  24760. if (this.type !== t) {
  24761. this.unexpected();
  24762. }
  24763. this.next();
  24764. }
  24765. readToken(code) {
  24766. let i = 0;
  24767. for (; i < keyword.length; i++) {
  24768. if (this._codeAt(this.pos + i) !== keyword.charCodeAt(i)) {
  24769. return super.readToken(code);
  24770. }
  24771. }
  24772. // ensure that the keyword is at the correct location
  24773. // ie `assert{...` or `assert {...`
  24774. for (;; i++) {
  24775. if (this._codeAt(this.pos + i) === leftCurlyBrace) {
  24776. // Found '{'
  24777. break;
  24778. } else if (this._codeAt(this.pos + i) === space) {
  24779. // white space is allowed between `assert` and `{`, so continue.
  24780. continue;
  24781. } else {
  24782. return super.readToken(code);
  24783. }
  24784. }
  24785. // If we're inside a dynamic import expression we'll parse
  24786. // the `assert` keyword as a standard object property name
  24787. // ie `import(""./foo.json", { assert: { type: "json" } })`
  24788. if (this.type.label === "{") {
  24789. return super.readToken(code);
  24790. }
  24791. this.pos += keyword.length;
  24792. return this.finishToken(this.assertToken);
  24793. }
  24794. parseDynamicImport(node) {
  24795. this.next(); // skip `(`
  24796. // Parse node.source.
  24797. node.source = this.parseMaybeAssign();
  24798. if (this.eat(tt.comma)) {
  24799. const obj = this.parseObj(false);
  24800. node.arguments = [obj];
  24801. }
  24802. this._eat(tt.parenR);
  24803. return this.finishNode(node, "ImportExpression");
  24804. }
  24805. // ported from acorn/src/statement.js pp.parseExport
  24806. parseExport(node, exports) {
  24807. this.next();
  24808. // export * from '...'
  24809. if (this.eat(tt.star)) {
  24810. if (this.options.ecmaVersion >= 11) {
  24811. if (this.eatContextual("as")) {
  24812. node.exported = this.parseIdent(true);
  24813. this.checkExport(exports, node.exported.name, this.lastTokStart);
  24814. } else {
  24815. node.exported = null;
  24816. }
  24817. }
  24818. this.expectContextual("from");
  24819. if (this.type !== tt.string) { this.unexpected(); }
  24820. node.source = this.parseExprAtom();
  24821. if (this.type === this.assertToken || this.type === tt._with) {
  24822. this.next();
  24823. const assertions = this.parseImportAssertions();
  24824. if (assertions) {
  24825. node.assertions = assertions;
  24826. }
  24827. }
  24828. this.semicolon();
  24829. return this.finishNode(node, "ExportAllDeclaration")
  24830. }
  24831. if (this.eat(tt._default)) { // export default ...
  24832. this.checkExport(exports, "default", this.lastTokStart);
  24833. var isAsync;
  24834. if (this.type === tt._function || (isAsync = this.isAsyncFunction())) {
  24835. var fNode = this.startNode();
  24836. this.next();
  24837. if (isAsync) { this.next(); }
  24838. node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync);
  24839. } else if (this.type === tt._class) {
  24840. var cNode = this.startNode();
  24841. node.declaration = this.parseClass(cNode, "nullableID");
  24842. } else {
  24843. node.declaration = this.parseMaybeAssign();
  24844. this.semicolon();
  24845. }
  24846. return this.finishNode(node, "ExportDefaultDeclaration")
  24847. }
  24848. // export var|const|let|function|class ...
  24849. if (this.shouldParseExportStatement()) {
  24850. node.declaration = this.parseStatement(null);
  24851. if (node.declaration.type === "VariableDeclaration")
  24852. { this.checkVariableExport(exports, node.declaration.declarations); }
  24853. else
  24854. { this.checkExport(exports, node.declaration.id.name, node.declaration.id.start); }
  24855. node.specifiers = [];
  24856. node.source = null;
  24857. } else { // export { x, y as z } [from '...']
  24858. node.declaration = null;
  24859. node.specifiers = this.parseExportSpecifiers(exports);
  24860. if (this.eatContextual("from")) {
  24861. if (this.type !== tt.string) { this.unexpected(); }
  24862. node.source = this.parseExprAtom();
  24863. if (this.type === this.assertToken || this.type === tt._with) {
  24864. this.next();
  24865. const assertions = this.parseImportAssertions();
  24866. if (assertions) {
  24867. node.assertions = assertions;
  24868. }
  24869. }
  24870. } else {
  24871. for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
  24872. // check for keywords used as local names
  24873. var spec = list[i];
  24874. this.checkUnreserved(spec.local);
  24875. // check if export is defined
  24876. this.checkLocalExport(spec.local);
  24877. }
  24878. node.source = null;
  24879. }
  24880. this.semicolon();
  24881. }
  24882. return this.finishNode(node, "ExportNamedDeclaration")
  24883. }
  24884. parseImport(node) {
  24885. this.next();
  24886. // import '...'
  24887. if (this.type === tt.string) {
  24888. node.specifiers = [];
  24889. node.source = this.parseExprAtom();
  24890. } else {
  24891. node.specifiers = this.parseImportSpecifiers();
  24892. this.expectContextual("from");
  24893. node.source =
  24894. this.type === tt.string ? this.parseExprAtom() : this.unexpected();
  24895. }
  24896. if (this.type === this.assertToken || this.type == tt._with) {
  24897. this.next();
  24898. const assertions = this.parseImportAssertions();
  24899. if (assertions) {
  24900. node.assertions = assertions;
  24901. }
  24902. }
  24903. this.semicolon();
  24904. return this.finishNode(node, "ImportDeclaration");
  24905. }
  24906. parseImportAssertions() {
  24907. this._eat(tt.braceL);
  24908. const attrs = this.parseAssertEntries();
  24909. this._eat(tt.braceR);
  24910. return attrs;
  24911. }
  24912. parseAssertEntries() {
  24913. const attrs = [];
  24914. const attrNames = new Set();
  24915. do {
  24916. if (this.type === tt.braceR) {
  24917. break;
  24918. }
  24919. const node = this.startNode();
  24920. // parse AssertionKey : IdentifierName, StringLiteral
  24921. let assertionKeyNode;
  24922. if (this.type === tt.string) {
  24923. assertionKeyNode = this.parseLiteral(this.value);
  24924. } else {
  24925. assertionKeyNode = this.parseIdent(true);
  24926. }
  24927. this.next();
  24928. node.key = assertionKeyNode;
  24929. // check if we already have an entry for an attribute
  24930. // if a duplicate entry is found, throw an error
  24931. // for now this logic will come into play only when someone declares `type` twice
  24932. if (attrNames.has(node.key.name)) {
  24933. this.raise(this.pos, "Duplicated key in assertions");
  24934. }
  24935. attrNames.add(node.key.name);
  24936. if (this.type !== tt.string) {
  24937. this.raise(
  24938. this.pos,
  24939. "Only string is supported as an assertion value"
  24940. );
  24941. }
  24942. node.value = this.parseLiteral(this.value);
  24943. attrs.push(this.finishNode(node, "ImportAttribute"));
  24944. } while (this.eat(tt.comma));
  24945. return attrs;
  24946. }
  24947. };
  24948. }
  24949. async function normalizeInputOptions(config, watchMode) {
  24950. // These are options that may trigger special warnings or behaviour later
  24951. // if the user did not select an explicit value
  24952. const unsetOptions = new Set();
  24953. const context = config.context ?? 'undefined';
  24954. const plugins = await normalizePluginOption(config.plugins);
  24955. const logLevel = config.logLevel || LOGLEVEL_INFO;
  24956. const onLog = getLogger(plugins, getOnLog(config, logLevel), watchMode, logLevel);
  24957. const strictDeprecations = config.strictDeprecations || false;
  24958. const maxParallelFileOps = getMaxParallelFileOps(config, onLog, strictDeprecations);
  24959. const options = {
  24960. acorn: getAcorn(config),
  24961. acornInjectPlugins: getAcornInjectPlugins(config),
  24962. cache: getCache(config),
  24963. context,
  24964. experimentalCacheExpiry: config.experimentalCacheExpiry ?? 10,
  24965. experimentalLogSideEffects: config.experimentalLogSideEffects || false,
  24966. external: getIdMatcher(config.external),
  24967. inlineDynamicImports: getInlineDynamicImports$1(config, onLog, strictDeprecations),
  24968. input: getInput(config),
  24969. logLevel,
  24970. makeAbsoluteExternalsRelative: config.makeAbsoluteExternalsRelative ?? 'ifRelativeSource',
  24971. manualChunks: getManualChunks$1(config, onLog, strictDeprecations),
  24972. maxParallelFileOps,
  24973. maxParallelFileReads: maxParallelFileOps,
  24974. moduleContext: getModuleContext(config, context),
  24975. onLog,
  24976. onwarn: warning => onLog(LOGLEVEL_WARN, warning),
  24977. perf: config.perf || false,
  24978. plugins,
  24979. preserveEntrySignatures: config.preserveEntrySignatures ?? 'exports-only',
  24980. preserveModules: getPreserveModules$1(config, onLog, strictDeprecations),
  24981. preserveSymlinks: config.preserveSymlinks || false,
  24982. shimMissingExports: config.shimMissingExports || false,
  24983. strictDeprecations,
  24984. treeshake: getTreeshake(config)
  24985. };
  24986. warnUnknownOptions(config, [...Object.keys(options), 'watch'], 'input options', onLog, /^(output)$/);
  24987. return { options, unsetOptions };
  24988. }
  24989. const getAcorn = (config) => ({
  24990. ecmaVersion: 'latest',
  24991. sourceType: 'module',
  24992. ...config.acorn
  24993. });
  24994. const getAcornInjectPlugins = (config) => [
  24995. importAssertions,
  24996. ...ensureArray$1(config.acornInjectPlugins)
  24997. ];
  24998. const getCache = (config) => config.cache === true // `true` is the default
  24999. ? undefined
  25000. : config.cache?.cache || config.cache;
  25001. const getIdMatcher = (option) => {
  25002. if (option === true) {
  25003. return () => true;
  25004. }
  25005. if (typeof option === 'function') {
  25006. return (id, ...parameters) => (!id.startsWith('\0') && option(id, ...parameters)) || false;
  25007. }
  25008. if (option) {
  25009. const ids = new Set();
  25010. const matchers = [];
  25011. for (const value of ensureArray$1(option)) {
  25012. if (value instanceof RegExp) {
  25013. matchers.push(value);
  25014. }
  25015. else {
  25016. ids.add(value);
  25017. }
  25018. }
  25019. return (id, ..._arguments) => ids.has(id) || matchers.some(matcher => matcher.test(id));
  25020. }
  25021. return () => false;
  25022. };
  25023. const getInlineDynamicImports$1 = (config, log, strictDeprecations) => {
  25024. const configInlineDynamicImports = config.inlineDynamicImports;
  25025. if (configInlineDynamicImports) {
  25026. warnDeprecationWithOptions('The "inlineDynamicImports" option is deprecated. Use the "output.inlineDynamicImports" option instead.', URL_OUTPUT_INLINEDYNAMICIMPORTS, true, log, strictDeprecations);
  25027. }
  25028. return configInlineDynamicImports;
  25029. };
  25030. const getInput = (config) => {
  25031. const configInput = config.input;
  25032. return configInput == null ? [] : typeof configInput === 'string' ? [configInput] : configInput;
  25033. };
  25034. const getManualChunks$1 = (config, log, strictDeprecations) => {
  25035. const configManualChunks = config.manualChunks;
  25036. if (configManualChunks) {
  25037. warnDeprecationWithOptions('The "manualChunks" option is deprecated. Use the "output.manualChunks" option instead.', URL_OUTPUT_MANUALCHUNKS, true, log, strictDeprecations);
  25038. }
  25039. return configManualChunks;
  25040. };
  25041. const getMaxParallelFileOps = (config, log, strictDeprecations) => {
  25042. const maxParallelFileReads = config.maxParallelFileReads;
  25043. if (typeof maxParallelFileReads === 'number') {
  25044. warnDeprecationWithOptions('The "maxParallelFileReads" option is deprecated. Use the "maxParallelFileOps" option instead.', URL_MAXPARALLELFILEOPS, true, log, strictDeprecations);
  25045. }
  25046. const maxParallelFileOps = config.maxParallelFileOps ?? maxParallelFileReads;
  25047. if (typeof maxParallelFileOps === 'number') {
  25048. if (maxParallelFileOps <= 0)
  25049. return Infinity;
  25050. return maxParallelFileOps;
  25051. }
  25052. return 20;
  25053. };
  25054. const getModuleContext = (config, context) => {
  25055. const configModuleContext = config.moduleContext;
  25056. if (typeof configModuleContext === 'function') {
  25057. return id => configModuleContext(id) ?? context;
  25058. }
  25059. if (configModuleContext) {
  25060. const contextByModuleId = Object.create(null);
  25061. for (const [key, moduleContext] of Object.entries(configModuleContext)) {
  25062. contextByModuleId[node_path.resolve(key)] = moduleContext;
  25063. }
  25064. return id => contextByModuleId[id] ?? context;
  25065. }
  25066. return () => context;
  25067. };
  25068. const getPreserveModules$1 = (config, log, strictDeprecations) => {
  25069. const configPreserveModules = config.preserveModules;
  25070. if (configPreserveModules) {
  25071. warnDeprecationWithOptions('The "preserveModules" option is deprecated. Use the "output.preserveModules" option instead.', URL_OUTPUT_PRESERVEMODULES, true, log, strictDeprecations);
  25072. }
  25073. return configPreserveModules;
  25074. };
  25075. const getTreeshake = (config) => {
  25076. const configTreeshake = config.treeshake;
  25077. if (configTreeshake === false) {
  25078. return false;
  25079. }
  25080. const configWithPreset = getOptionWithPreset(config.treeshake, treeshakePresets, 'treeshake', URL_TREESHAKE, 'false, true, ');
  25081. return {
  25082. annotations: configWithPreset.annotations !== false,
  25083. correctVarValueBeforeDeclaration: configWithPreset.correctVarValueBeforeDeclaration === true,
  25084. manualPureFunctions: configWithPreset.manualPureFunctions ?? EMPTY_ARRAY,
  25085. moduleSideEffects: getHasModuleSideEffects(configWithPreset.moduleSideEffects),
  25086. propertyReadSideEffects: configWithPreset.propertyReadSideEffects === 'always'
  25087. ? 'always'
  25088. : configWithPreset.propertyReadSideEffects !== false,
  25089. tryCatchDeoptimization: configWithPreset.tryCatchDeoptimization !== false,
  25090. unknownGlobalSideEffects: configWithPreset.unknownGlobalSideEffects !== false
  25091. };
  25092. };
  25093. const getHasModuleSideEffects = (moduleSideEffectsOption) => {
  25094. if (typeof moduleSideEffectsOption === 'boolean') {
  25095. return () => moduleSideEffectsOption;
  25096. }
  25097. if (moduleSideEffectsOption === 'no-external') {
  25098. return (_id, external) => !external;
  25099. }
  25100. if (typeof moduleSideEffectsOption === 'function') {
  25101. return (id, external) => id.startsWith('\0') ? true : moduleSideEffectsOption(id, external) !== false;
  25102. }
  25103. if (Array.isArray(moduleSideEffectsOption)) {
  25104. const ids = new Set(moduleSideEffectsOption);
  25105. return id => ids.has(id);
  25106. }
  25107. if (moduleSideEffectsOption) {
  25108. error(logInvalidOption('treeshake.moduleSideEffects', URL_TREESHAKE_MODULESIDEEFFECTS, 'please use one of false, "no-external", a function or an array'));
  25109. }
  25110. return () => true;
  25111. };
  25112. // https://datatracker.ietf.org/doc/html/rfc2396
  25113. // eslint-disable-next-line no-control-regex
  25114. const INVALID_CHAR_REGEX = /[\u0000-\u001F"#$&*+,:;<=>?[\]^`{|}\u007F]/g;
  25115. const DRIVE_LETTER_REGEX = /^[a-z]:/i;
  25116. function sanitizeFileName(name) {
  25117. const match = DRIVE_LETTER_REGEX.exec(name);
  25118. const driveLetter = match ? match[0] : '';
  25119. // A `:` is only allowed as part of a windows drive letter (ex: C:\foo)
  25120. // Otherwise, avoid them because they can refer to NTFS alternate data streams.
  25121. return driveLetter + name.slice(driveLetter.length).replace(INVALID_CHAR_REGEX, '_');
  25122. }
  25123. async function normalizeOutputOptions(config, inputOptions, unsetInputOptions) {
  25124. // These are options that may trigger special warnings or behaviour later
  25125. // if the user did not select an explicit value
  25126. const unsetOptions = new Set(unsetInputOptions);
  25127. const compact = config.compact || false;
  25128. const format = getFormat(config);
  25129. const inlineDynamicImports = getInlineDynamicImports(config, inputOptions);
  25130. const preserveModules = getPreserveModules(config, inlineDynamicImports, inputOptions);
  25131. const file = getFile(config, preserveModules, inputOptions);
  25132. const preferConst = getPreferConst(config, inputOptions);
  25133. const generatedCode = getGeneratedCode(config, preferConst);
  25134. const outputOptions = {
  25135. amd: getAmd(config),
  25136. assetFileNames: config.assetFileNames ?? 'assets/[name]-[hash][extname]',
  25137. banner: getAddon(config, 'banner'),
  25138. chunkFileNames: config.chunkFileNames ?? '[name]-[hash].js',
  25139. compact,
  25140. dir: getDir(config, file),
  25141. dynamicImportFunction: getDynamicImportFunction(config, inputOptions, format),
  25142. dynamicImportInCjs: config.dynamicImportInCjs ?? true,
  25143. entryFileNames: getEntryFileNames(config, unsetOptions),
  25144. esModule: config.esModule ?? 'if-default-prop',
  25145. experimentalDeepDynamicChunkOptimization: getExperimentalDeepDynamicChunkOptimization(config, inputOptions),
  25146. experimentalMinChunkSize: config.experimentalMinChunkSize ?? 1,
  25147. exports: getExports(config, unsetOptions),
  25148. extend: config.extend || false,
  25149. externalImportAssertions: config.externalImportAssertions ?? true,
  25150. externalLiveBindings: config.externalLiveBindings ?? true,
  25151. file,
  25152. footer: getAddon(config, 'footer'),
  25153. format,
  25154. freeze: config.freeze ?? true,
  25155. generatedCode,
  25156. globals: config.globals || {},
  25157. hoistTransitiveImports: config.hoistTransitiveImports ?? true,
  25158. indent: getIndent(config, compact),
  25159. inlineDynamicImports,
  25160. interop: getInterop(config),
  25161. intro: getAddon(config, 'intro'),
  25162. manualChunks: getManualChunks(config, inlineDynamicImports, preserveModules, inputOptions),
  25163. minifyInternalExports: getMinifyInternalExports(config, format, compact),
  25164. name: config.name,
  25165. namespaceToStringTag: getNamespaceToStringTag(config, generatedCode, inputOptions),
  25166. noConflict: config.noConflict || false,
  25167. outro: getAddon(config, 'outro'),
  25168. paths: config.paths || {},
  25169. plugins: await normalizePluginOption(config.plugins),
  25170. preferConst,
  25171. preserveModules,
  25172. preserveModulesRoot: getPreserveModulesRoot(config),
  25173. sanitizeFileName: typeof config.sanitizeFileName === 'function'
  25174. ? config.sanitizeFileName
  25175. : config.sanitizeFileName === false
  25176. ? id => id
  25177. : sanitizeFileName,
  25178. sourcemap: config.sourcemap || false,
  25179. sourcemapBaseUrl: getSourcemapBaseUrl(config),
  25180. sourcemapExcludeSources: config.sourcemapExcludeSources || false,
  25181. sourcemapFile: config.sourcemapFile,
  25182. sourcemapFileNames: getSourcemapFileNames(config, unsetOptions),
  25183. sourcemapIgnoreList: typeof config.sourcemapIgnoreList === 'function'
  25184. ? config.sourcemapIgnoreList
  25185. : config.sourcemapIgnoreList === false
  25186. ? () => false
  25187. : relativeSourcePath => relativeSourcePath.includes('node_modules'),
  25188. sourcemapPathTransform: config.sourcemapPathTransform,
  25189. strict: config.strict ?? true,
  25190. systemNullSetters: config.systemNullSetters ?? true,
  25191. validate: config.validate || false
  25192. };
  25193. warnUnknownOptions(config, Object.keys(outputOptions), 'output options', inputOptions.onLog);
  25194. return { options: outputOptions, unsetOptions };
  25195. }
  25196. const getFile = (config, preserveModules, inputOptions) => {
  25197. const { file } = config;
  25198. if (typeof file === 'string') {
  25199. if (preserveModules) {
  25200. return error(logInvalidOption('output.file', URL_OUTPUT_DIR, 'you must set "output.dir" instead of "output.file" when using the "output.preserveModules" option'));
  25201. }
  25202. if (!Array.isArray(inputOptions.input))
  25203. return error(logInvalidOption('output.file', URL_OUTPUT_DIR, 'you must set "output.dir" instead of "output.file" when providing named inputs'));
  25204. }
  25205. return file;
  25206. };
  25207. const getFormat = (config) => {
  25208. const configFormat = config.format;
  25209. switch (configFormat) {
  25210. case undefined:
  25211. case 'es':
  25212. case 'esm':
  25213. case 'module': {
  25214. return 'es';
  25215. }
  25216. case 'cjs':
  25217. case 'commonjs': {
  25218. return 'cjs';
  25219. }
  25220. case 'system':
  25221. case 'systemjs': {
  25222. return 'system';
  25223. }
  25224. case 'amd':
  25225. case 'iife':
  25226. case 'umd': {
  25227. return configFormat;
  25228. }
  25229. default: {
  25230. return error(logInvalidOption('output.format', URL_OUTPUT_FORMAT, `Valid values are "amd", "cjs", "system", "es", "iife" or "umd"`, configFormat));
  25231. }
  25232. }
  25233. };
  25234. const getInlineDynamicImports = (config, inputOptions) => {
  25235. const inlineDynamicImports = (config.inlineDynamicImports ?? inputOptions.inlineDynamicImports) || false;
  25236. const { input } = inputOptions;
  25237. if (inlineDynamicImports && (Array.isArray(input) ? input : Object.keys(input)).length > 1) {
  25238. return error(logInvalidOption('output.inlineDynamicImports', URL_OUTPUT_INLINEDYNAMICIMPORTS, 'multiple inputs are not supported when "output.inlineDynamicImports" is true'));
  25239. }
  25240. return inlineDynamicImports;
  25241. };
  25242. const getPreserveModules = (config, inlineDynamicImports, inputOptions) => {
  25243. const preserveModules = (config.preserveModules ?? inputOptions.preserveModules) || false;
  25244. if (preserveModules) {
  25245. if (inlineDynamicImports) {
  25246. return error(logInvalidOption('output.inlineDynamicImports', URL_OUTPUT_INLINEDYNAMICIMPORTS, `this option is not supported for "output.preserveModules"`));
  25247. }
  25248. if (inputOptions.preserveEntrySignatures === false) {
  25249. return error(logInvalidOption('preserveEntrySignatures', URL_PRESERVEENTRYSIGNATURES, 'setting this option to false is not supported for "output.preserveModules"'));
  25250. }
  25251. }
  25252. return preserveModules;
  25253. };
  25254. const getPreferConst = (config, inputOptions) => {
  25255. const configPreferConst = config.preferConst;
  25256. if (configPreferConst != null) {
  25257. warnDeprecation(`The "output.preferConst" option is deprecated. Use the "output.generatedCode.constBindings" option instead.`, URL_OUTPUT_GENERATEDCODE_CONSTBINDINGS, true, inputOptions);
  25258. }
  25259. return !!configPreferConst;
  25260. };
  25261. const getPreserveModulesRoot = (config) => {
  25262. const { preserveModulesRoot } = config;
  25263. if (preserveModulesRoot === null || preserveModulesRoot === undefined) {
  25264. return undefined;
  25265. }
  25266. return node_path.resolve(preserveModulesRoot);
  25267. };
  25268. const getAmd = (config) => {
  25269. const mergedOption = {
  25270. autoId: false,
  25271. basePath: '',
  25272. define: 'define',
  25273. forceJsExtensionForImports: false,
  25274. ...config.amd
  25275. };
  25276. if ((mergedOption.autoId || mergedOption.basePath) && mergedOption.id) {
  25277. return error(logInvalidOption('output.amd.id', URL_OUTPUT_AMD_ID, 'this option cannot be used together with "output.amd.autoId"/"output.amd.basePath"'));
  25278. }
  25279. if (mergedOption.basePath && !mergedOption.autoId) {
  25280. return error(logInvalidOption('output.amd.basePath', URL_OUTPUT_AMD_BASEPATH, 'this option only works with "output.amd.autoId"'));
  25281. }
  25282. return mergedOption.autoId
  25283. ? {
  25284. autoId: true,
  25285. basePath: mergedOption.basePath,
  25286. define: mergedOption.define,
  25287. forceJsExtensionForImports: mergedOption.forceJsExtensionForImports
  25288. }
  25289. : {
  25290. autoId: false,
  25291. define: mergedOption.define,
  25292. forceJsExtensionForImports: mergedOption.forceJsExtensionForImports,
  25293. id: mergedOption.id
  25294. };
  25295. };
  25296. const getAddon = (config, name) => {
  25297. const configAddon = config[name];
  25298. if (typeof configAddon === 'function') {
  25299. return configAddon;
  25300. }
  25301. return () => configAddon || '';
  25302. };
  25303. // eslint-disable-next-line unicorn/prevent-abbreviations
  25304. const getDir = (config, file) => {
  25305. const { dir } = config;
  25306. if (typeof dir === 'string' && typeof file === 'string') {
  25307. return error(logInvalidOption('output.dir', URL_OUTPUT_DIR, 'you must set either "output.file" for a single-file build or "output.dir" when generating multiple chunks'));
  25308. }
  25309. return dir;
  25310. };
  25311. const getDynamicImportFunction = (config, inputOptions, format) => {
  25312. const configDynamicImportFunction = config.dynamicImportFunction;
  25313. if (configDynamicImportFunction) {
  25314. warnDeprecation(`The "output.dynamicImportFunction" option is deprecated. Use the "renderDynamicImport" plugin hook instead.`, URL_RENDERDYNAMICIMPORT, true, inputOptions);
  25315. if (format !== 'es') {
  25316. inputOptions.onLog(LOGLEVEL_WARN, logInvalidOption('output.dynamicImportFunction', URL_OUTPUT_DYNAMICIMPORTFUNCTION, 'this option is ignored for formats other than "es"'));
  25317. }
  25318. }
  25319. return configDynamicImportFunction;
  25320. };
  25321. const getEntryFileNames = (config, unsetOptions) => {
  25322. const configEntryFileNames = config.entryFileNames;
  25323. if (configEntryFileNames == null) {
  25324. unsetOptions.add('entryFileNames');
  25325. }
  25326. return configEntryFileNames ?? '[name].js';
  25327. };
  25328. function getExperimentalDeepDynamicChunkOptimization(config, inputOptions) {
  25329. const configExperimentalDeepDynamicChunkOptimization = config.experimentalDeepDynamicChunkOptimization;
  25330. if (configExperimentalDeepDynamicChunkOptimization != null) {
  25331. warnDeprecation(`The "output.experimentalDeepDynamicChunkOptimization" option is deprecated as Rollup always runs the full chunking algorithm now. The option should be removed.`, URL_OUTPUT_EXPERIMENTALDEEPCHUNKOPTIMIZATION, true, inputOptions);
  25332. }
  25333. return configExperimentalDeepDynamicChunkOptimization || false;
  25334. }
  25335. function getExports(config, unsetOptions) {
  25336. const configExports = config.exports;
  25337. if (configExports == null) {
  25338. unsetOptions.add('exports');
  25339. }
  25340. else if (!['default', 'named', 'none', 'auto'].includes(configExports)) {
  25341. return error(logInvalidExportOptionValue(configExports));
  25342. }
  25343. return configExports || 'auto';
  25344. }
  25345. const getGeneratedCode = (config, preferConst) => {
  25346. const configWithPreset = getOptionWithPreset(config.generatedCode, generatedCodePresets, 'output.generatedCode', URL_OUTPUT_GENERATEDCODE, '');
  25347. return {
  25348. arrowFunctions: configWithPreset.arrowFunctions === true,
  25349. constBindings: configWithPreset.constBindings === true || preferConst,
  25350. objectShorthand: configWithPreset.objectShorthand === true,
  25351. reservedNamesAsProps: configWithPreset.reservedNamesAsProps !== false,
  25352. symbols: configWithPreset.symbols === true
  25353. };
  25354. };
  25355. const getIndent = (config, compact) => {
  25356. if (compact) {
  25357. return '';
  25358. }
  25359. const configIndent = config.indent;
  25360. return configIndent === false ? '' : configIndent ?? true;
  25361. };
  25362. const ALLOWED_INTEROP_TYPES = new Set([
  25363. 'compat',
  25364. 'auto',
  25365. 'esModule',
  25366. 'default',
  25367. 'defaultOnly'
  25368. ]);
  25369. const getInterop = (config) => {
  25370. const configInterop = config.interop;
  25371. if (typeof configInterop === 'function') {
  25372. const interopPerId = Object.create(null);
  25373. let defaultInterop = null;
  25374. return id => id === null
  25375. ? defaultInterop || validateInterop((defaultInterop = configInterop(id)))
  25376. : id in interopPerId
  25377. ? interopPerId[id]
  25378. : validateInterop((interopPerId[id] = configInterop(id)));
  25379. }
  25380. return configInterop === undefined ? () => 'default' : () => validateInterop(configInterop);
  25381. };
  25382. const validateInterop = (interop) => {
  25383. if (!ALLOWED_INTEROP_TYPES.has(interop)) {
  25384. return error(logInvalidOption('output.interop', URL_OUTPUT_INTEROP,
  25385. // eslint-disable-next-line unicorn/prefer-spread
  25386. `use one of ${Array.from(ALLOWED_INTEROP_TYPES, value => JSON.stringify(value)).join(', ')}`, interop));
  25387. }
  25388. return interop;
  25389. };
  25390. const getManualChunks = (config, inlineDynamicImports, preserveModules, inputOptions) => {
  25391. const configManualChunks = config.manualChunks || inputOptions.manualChunks;
  25392. if (configManualChunks) {
  25393. if (inlineDynamicImports) {
  25394. return error(logInvalidOption('output.manualChunks', URL_OUTPUT_MANUALCHUNKS, 'this option is not supported for "output.inlineDynamicImports"'));
  25395. }
  25396. if (preserveModules) {
  25397. return error(logInvalidOption('output.manualChunks', URL_OUTPUT_MANUALCHUNKS, 'this option is not supported for "output.preserveModules"'));
  25398. }
  25399. }
  25400. return configManualChunks || {};
  25401. };
  25402. const getMinifyInternalExports = (config, format, compact) => config.minifyInternalExports ?? (compact || format === 'es' || format === 'system');
  25403. const getNamespaceToStringTag = (config, generatedCode, inputOptions) => {
  25404. const configNamespaceToStringTag = config.namespaceToStringTag;
  25405. if (configNamespaceToStringTag != null) {
  25406. warnDeprecation(`The "output.namespaceToStringTag" option is deprecated. Use the "output.generatedCode.symbols" option instead.`, URL_OUTPUT_GENERATEDCODE_SYMBOLS, true, inputOptions);
  25407. return configNamespaceToStringTag;
  25408. }
  25409. return generatedCode.symbols || false;
  25410. };
  25411. const getSourcemapFileNames = (config, unsetOptions) => {
  25412. const configSourcemapFileNames = config.sourcemapFileNames;
  25413. if (configSourcemapFileNames == null) {
  25414. unsetOptions.add('sourcemapFileNames');
  25415. }
  25416. return configSourcemapFileNames;
  25417. };
  25418. const getSourcemapBaseUrl = (config) => {
  25419. const { sourcemapBaseUrl } = config;
  25420. if (sourcemapBaseUrl) {
  25421. if (isValidUrl(sourcemapBaseUrl)) {
  25422. return addTrailingSlashIfMissed(sourcemapBaseUrl);
  25423. }
  25424. return error(logInvalidOption('output.sourcemapBaseUrl', URL_OUTPUT_SOURCEMAPBASEURL, `must be a valid URL, received ${JSON.stringify(sourcemapBaseUrl)}`));
  25425. }
  25426. };
  25427. function rollup(rawInputOptions) {
  25428. return rollupInternal(rawInputOptions, null);
  25429. }
  25430. async function rollupInternal(rawInputOptions, watcher) {
  25431. const { options: inputOptions, unsetOptions: unsetInputOptions } = await getInputOptions(rawInputOptions, watcher !== null);
  25432. initialiseTimers(inputOptions);
  25433. const graph = new Graph(inputOptions, watcher);
  25434. // remove the cache object from the memory after graph creation (cache is not used anymore)
  25435. const useCache = rawInputOptions.cache !== false;
  25436. if (rawInputOptions.cache) {
  25437. inputOptions.cache = undefined;
  25438. rawInputOptions.cache = undefined;
  25439. }
  25440. timeStart('BUILD', 1);
  25441. await catchUnfinishedHookActions(graph.pluginDriver, async () => {
  25442. try {
  25443. timeStart('initialize', 2);
  25444. await graph.pluginDriver.hookParallel('buildStart', [inputOptions]);
  25445. timeEnd('initialize', 2);
  25446. await graph.build();
  25447. }
  25448. catch (error_) {
  25449. const watchFiles = Object.keys(graph.watchFiles);
  25450. if (watchFiles.length > 0) {
  25451. error_.watchFiles = watchFiles;
  25452. }
  25453. await graph.pluginDriver.hookParallel('buildEnd', [error_]);
  25454. await graph.pluginDriver.hookParallel('closeBundle', []);
  25455. throw error_;
  25456. }
  25457. await graph.pluginDriver.hookParallel('buildEnd', []);
  25458. });
  25459. timeEnd('BUILD', 1);
  25460. const result = {
  25461. cache: useCache ? graph.getCache() : undefined,
  25462. async close() {
  25463. if (result.closed)
  25464. return;
  25465. result.closed = true;
  25466. await graph.pluginDriver.hookParallel('closeBundle', []);
  25467. },
  25468. closed: false,
  25469. async generate(rawOutputOptions) {
  25470. if (result.closed)
  25471. return error(logAlreadyClosed());
  25472. return handleGenerateWrite(false, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  25473. },
  25474. watchFiles: Object.keys(graph.watchFiles),
  25475. async write(rawOutputOptions) {
  25476. if (result.closed)
  25477. return error(logAlreadyClosed());
  25478. return handleGenerateWrite(true, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  25479. }
  25480. };
  25481. if (inputOptions.perf)
  25482. result.getTimings = getTimings;
  25483. return result;
  25484. }
  25485. async function getInputOptions(initialInputOptions, watchMode) {
  25486. if (!initialInputOptions) {
  25487. throw new Error('You must supply an options object to rollup');
  25488. }
  25489. const processedInputOptions = await getProcessedInputOptions(initialInputOptions, watchMode);
  25490. const { options, unsetOptions } = await normalizeInputOptions(processedInputOptions, watchMode);
  25491. normalizePlugins(options.plugins, ANONYMOUS_PLUGIN_PREFIX);
  25492. return { options, unsetOptions };
  25493. }
  25494. async function getProcessedInputOptions(inputOptions, watchMode) {
  25495. const plugins = getSortedValidatedPlugins('options', await normalizePluginOption(inputOptions.plugins));
  25496. const logLevel = inputOptions.logLevel || LOGLEVEL_INFO;
  25497. const logger = getLogger(plugins, getOnLog(inputOptions, logLevel), watchMode, logLevel);
  25498. for (const plugin of plugins) {
  25499. const { name, options } = plugin;
  25500. const handler = 'handler' in options ? options.handler : options;
  25501. const processedOptions = await handler.call({
  25502. debug: getLogHandler(LOGLEVEL_DEBUG, 'PLUGIN_LOG', logger, name, logLevel),
  25503. error: (error_) => error(logPluginError(normalizeLog(error_), name, { hook: 'onLog' })),
  25504. info: getLogHandler(LOGLEVEL_INFO, 'PLUGIN_LOG', logger, name, logLevel),
  25505. meta: { rollupVersion: version$1, watchMode },
  25506. warn: getLogHandler(LOGLEVEL_WARN, 'PLUGIN_WARNING', logger, name, logLevel)
  25507. }, inputOptions);
  25508. if (processedOptions) {
  25509. inputOptions = processedOptions;
  25510. }
  25511. }
  25512. return inputOptions;
  25513. }
  25514. function normalizePlugins(plugins, anonymousPrefix) {
  25515. for (const [index, plugin] of plugins.entries()) {
  25516. if (!plugin.name) {
  25517. plugin.name = `${anonymousPrefix}${index + 1}`;
  25518. }
  25519. }
  25520. }
  25521. async function handleGenerateWrite(isWrite, inputOptions, unsetInputOptions, rawOutputOptions, graph) {
  25522. const { options: outputOptions, outputPluginDriver, unsetOptions } = await getOutputOptionsAndPluginDriver(rawOutputOptions, graph.pluginDriver, inputOptions, unsetInputOptions);
  25523. return catchUnfinishedHookActions(outputPluginDriver, async () => {
  25524. const bundle = new Bundle(outputOptions, unsetOptions, inputOptions, outputPluginDriver, graph);
  25525. const generated = await bundle.generate(isWrite);
  25526. if (isWrite) {
  25527. timeStart('WRITE', 1);
  25528. if (!outputOptions.dir && !outputOptions.file) {
  25529. return error(logMissingFileOrDirOption());
  25530. }
  25531. await Promise.all(Object.values(generated).map(chunk => graph.fileOperationQueue.run(() => writeOutputFile(chunk, outputOptions))));
  25532. await outputPluginDriver.hookParallel('writeBundle', [outputOptions, generated]);
  25533. timeEnd('WRITE', 1);
  25534. }
  25535. return createOutput(generated);
  25536. });
  25537. }
  25538. async function getOutputOptionsAndPluginDriver(rawOutputOptions, inputPluginDriver, inputOptions, unsetInputOptions) {
  25539. if (!rawOutputOptions) {
  25540. throw new Error('You must supply an options object');
  25541. }
  25542. const rawPlugins = await normalizePluginOption(rawOutputOptions.plugins);
  25543. normalizePlugins(rawPlugins, ANONYMOUS_OUTPUT_PLUGIN_PREFIX);
  25544. const outputPluginDriver = inputPluginDriver.createOutputPluginDriver(rawPlugins);
  25545. return {
  25546. ...(await getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver)),
  25547. outputPluginDriver
  25548. };
  25549. }
  25550. function getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver) {
  25551. return normalizeOutputOptions(outputPluginDriver.hookReduceArg0Sync('outputOptions', [rawOutputOptions], (outputOptions, result) => result || outputOptions, pluginContext => {
  25552. const emitError = () => pluginContext.error(logCannotEmitFromOptionsHook());
  25553. return {
  25554. ...pluginContext,
  25555. emitFile: emitError,
  25556. setAssetSource: emitError
  25557. };
  25558. }), inputOptions, unsetInputOptions);
  25559. }
  25560. function createOutput(outputBundle) {
  25561. return {
  25562. output: Object.values(outputBundle).filter(outputFile => Object.keys(outputFile).length > 0).sort((outputFileA, outputFileB) => getSortingFileType(outputFileA) - getSortingFileType(outputFileB))
  25563. };
  25564. }
  25565. var SortingFileType;
  25566. (function (SortingFileType) {
  25567. SortingFileType[SortingFileType["ENTRY_CHUNK"] = 0] = "ENTRY_CHUNK";
  25568. SortingFileType[SortingFileType["SECONDARY_CHUNK"] = 1] = "SECONDARY_CHUNK";
  25569. SortingFileType[SortingFileType["ASSET"] = 2] = "ASSET";
  25570. })(SortingFileType || (SortingFileType = {}));
  25571. function getSortingFileType(file) {
  25572. if (file.type === 'asset') {
  25573. return SortingFileType.ASSET;
  25574. }
  25575. if (file.isEntry) {
  25576. return SortingFileType.ENTRY_CHUNK;
  25577. }
  25578. return SortingFileType.SECONDARY_CHUNK;
  25579. }
  25580. async function writeOutputFile(outputFile, outputOptions) {
  25581. const fileName = node_path.resolve(outputOptions.dir || node_path.dirname(outputOptions.file), outputFile.fileName);
  25582. // 'recursive: true' does not throw if the folder structure, or parts of it, already exist
  25583. await promises.mkdir(node_path.dirname(fileName), { recursive: true });
  25584. return promises.writeFile(fileName, outputFile.type === 'asset' ? outputFile.source : outputFile.code);
  25585. }
  25586. /**
  25587. * Auxiliary function for defining rollup configuration
  25588. * Mainly to facilitate IDE code prompts, after all, export default does not
  25589. * prompt, even if you add @type annotations, it is not accurate
  25590. * @param options
  25591. */
  25592. function defineConfig(options) {
  25593. return options;
  25594. }
  25595. exports.LOGLEVEL_DEBUG = LOGLEVEL_DEBUG;
  25596. exports.LOGLEVEL_WARN = LOGLEVEL_WARN;
  25597. exports.URL_AVOIDING_EVAL = URL_AVOIDING_EVAL;
  25598. exports.URL_NAME_IS_NOT_EXPORTED = URL_NAME_IS_NOT_EXPORTED;
  25599. exports.URL_OUTPUT_EXPORTS = URL_OUTPUT_EXPORTS;
  25600. exports.URL_OUTPUT_GLOBALS = URL_OUTPUT_GLOBALS;
  25601. exports.URL_SOURCEMAP_IS_LIKELY_TO_BE_INCORRECT = URL_SOURCEMAP_IS_LIKELY_TO_BE_INCORRECT;
  25602. exports.URL_THIS_IS_UNDEFINED = URL_THIS_IS_UNDEFINED;
  25603. exports.URL_TREATING_MODULE_AS_EXTERNAL_DEPENDENCY = URL_TREATING_MODULE_AS_EXTERNAL_DEPENDENCY;
  25604. exports.URL_WATCH = URL_WATCH;
  25605. exports.blue = blue;
  25606. exports.bold = bold;
  25607. exports.commandAliases = commandAliases;
  25608. exports.createFilter = createFilter;
  25609. exports.cyan = cyan$1;
  25610. exports.cyan$1 = cyan;
  25611. exports.defineConfig = defineConfig;
  25612. exports.ensureArray = ensureArray$1;
  25613. exports.error = error;
  25614. exports.getAliasName = getAliasName;
  25615. exports.getAugmentedNamespace = getAugmentedNamespace;
  25616. exports.getNewArray = getNewArray;
  25617. exports.getOrCreate = getOrCreate;
  25618. exports.getRollupUrl = getRollupUrl;
  25619. exports.gray = gray;
  25620. exports.green = green;
  25621. exports.handleError = handleError;
  25622. exports.isWatchEnabled = isWatchEnabled;
  25623. exports.logCannotBundleConfigAsEsm = logCannotBundleConfigAsEsm;
  25624. exports.logCannotLoadConfigAsCjs = logCannotLoadConfigAsCjs;
  25625. exports.logCannotLoadConfigAsEsm = logCannotLoadConfigAsEsm;
  25626. exports.logDuplicateImportOptions = logDuplicateImportOptions;
  25627. exports.logFailAfterWarnings = logFailAfterWarnings;
  25628. exports.logInvalidOption = logInvalidOption;
  25629. exports.logMissingConfig = logMissingConfig;
  25630. exports.logMissingExternalConfig = logMissingExternalConfig;
  25631. exports.logOnlyInlineSourcemapsForStdout = logOnlyInlineSourcemapsForStdout;
  25632. exports.mergeOptions = mergeOptions;
  25633. exports.normalizePluginOption = normalizePluginOption;
  25634. exports.picomatch = picomatch;
  25635. exports.printQuotedStringList = printQuotedStringList;
  25636. exports.relativeId = relativeId;
  25637. exports.rollup = rollup;
  25638. exports.rollupInternal = rollupInternal;
  25639. exports.stderr = stderr;
  25640. exports.underline = underline;
  25641. exports.version = version$1;
  25642. exports.yellow = yellow;
  25643. //# sourceMappingURL=rollup.js.map