rollup.js 1004 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380
  1. /*
  2. @license
  3. Rollup.js v3.30.0
  4. Sun, 22 Feb 2026 06:50:42 GMT - commit 967740910dc90f3c928c91642f2b80c1ed40d60b
  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.30.0";
  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_NAME_OUTSIDE_OUTPUT_DIRECTORY = 'FILE_NAME_OUTSIDE_OUTPUT_DIRECTORY', 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 logFileNameOutsideOutputDirectory(fileName) {
  503. return {
  504. code: FILE_NAME_OUTSIDE_OUTPUT_DIRECTORY,
  505. message: `The output file name "${fileName}" is not contained in the output directory. Make sure all file names are relative paths without ".." segments.`
  506. };
  507. }
  508. function logFileReferenceIdNotFoundForFilename(assetReferenceId) {
  509. return {
  510. code: FILE_NOT_FOUND,
  511. message: `Plugin error - Unable to get file name for unknown file "${assetReferenceId}".`
  512. };
  513. }
  514. function logFirstSideEffect(source, id, { line, column }) {
  515. return {
  516. code: FIRST_SIDE_EFFECT,
  517. message: `First side effect in ${relativeId(id)} is at (${line}:${column})\n${getCodeFrame(source, line, column)}`
  518. };
  519. }
  520. function logIllegalIdentifierAsName(name) {
  521. return {
  522. code: ILLEGAL_IDENTIFIER_AS_NAME,
  523. message: `Given name "${name}" is not a legal JS identifier. If you need this, you can try "output.extend: true".`,
  524. url: getRollupUrl(URL_OUTPUT_EXTEND)
  525. };
  526. }
  527. function logIllegalImportReassignment(name, importingId) {
  528. return {
  529. code: ILLEGAL_REASSIGNMENT,
  530. message: `Illegal reassignment of import "${name}" in "${relativeId(importingId)}".`
  531. };
  532. }
  533. function logInconsistentImportAssertions(existingAssertions, newAssertions, source, importer) {
  534. return {
  535. code: INCONSISTENT_IMPORT_ASSERTIONS,
  536. 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.`
  537. };
  538. }
  539. const formatAssertions$1 = (assertions) => {
  540. const entries = Object.entries(assertions);
  541. if (entries.length === 0)
  542. return 'no';
  543. return entries.map(([key, value]) => `"${key}": "${value}"`).join(', ');
  544. };
  545. function logInputHookInOutputPlugin(pluginName, hookName) {
  546. return {
  547. code: INPUT_HOOK_IN_OUTPUT_PLUGIN,
  548. 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.`
  549. };
  550. }
  551. function logCannotAssignModuleToChunk(moduleId, assignToAlias, currentAlias) {
  552. return {
  553. code: INVALID_CHUNK,
  554. message: `Cannot assign "${relativeId(moduleId)}" to the "${assignToAlias}" chunk as it is already in the "${currentAlias}" chunk.`
  555. };
  556. }
  557. function logCannotBundleConfigAsEsm(originalError) {
  558. return {
  559. cause: originalError,
  560. code: INVALID_CONFIG_MODULE_FORMAT,
  561. 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}`,
  562. stack: originalError.stack,
  563. url: getRollupUrl(URL_BUNDLE_CONFIG_AS_CJS)
  564. };
  565. }
  566. function logCannotLoadConfigAsCjs(originalError) {
  567. return {
  568. cause: originalError,
  569. code: INVALID_CONFIG_MODULE_FORMAT,
  570. 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}`,
  571. stack: originalError.stack,
  572. url: getRollupUrl(URL_BUNDLE_CONFIG_AS_CJS)
  573. };
  574. }
  575. function logCannotLoadConfigAsEsm(originalError) {
  576. return {
  577. cause: originalError,
  578. code: INVALID_CONFIG_MODULE_FORMAT,
  579. 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}`,
  580. stack: originalError.stack,
  581. url: getRollupUrl(URL_BUNDLE_CONFIG_AS_CJS)
  582. };
  583. }
  584. function logInvalidExportOptionValue(optionValue) {
  585. return {
  586. code: INVALID_EXPORT_OPTION,
  587. message: `"output.exports" must be "default", "named", "none", "auto", or left unspecified (defaults to "auto"), received "${optionValue}".`,
  588. url: getRollupUrl(URL_OUTPUT_EXPORTS)
  589. };
  590. }
  591. function logIncompatibleExportOptionValue(optionValue, keys, entryModule) {
  592. return {
  593. code: INVALID_EXPORT_OPTION,
  594. message: `"${optionValue}" was specified for "output.exports", but entry module "${relativeId(entryModule)}" has the following exports: ${printQuotedStringList(keys)}`,
  595. url: getRollupUrl(URL_OUTPUT_EXPORTS)
  596. };
  597. }
  598. function logInternalIdCannotBeExternal(source, importer) {
  599. return {
  600. code: INVALID_EXTERNAL_ID,
  601. message: `"${source}" is imported as an external by "${relativeId(importer)}", but is already an existing non-external module id.`
  602. };
  603. }
  604. function logInvalidLogPosition(plugin) {
  605. return {
  606. code: INVALID_LOG_POSITION,
  607. 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.`
  608. };
  609. }
  610. function logInvalidOption(option, urlSnippet, explanation, value) {
  611. return {
  612. code: INVALID_OPTION,
  613. message: `Invalid value ${value === undefined ? '' : `${JSON.stringify(value)} `}for option "${option}" - ${explanation}.`,
  614. url: getRollupUrl(urlSnippet)
  615. };
  616. }
  617. function logInvalidAddonPluginHook(hook, plugin) {
  618. return {
  619. code: INVALID_PLUGIN_HOOK,
  620. hook,
  621. message: `Error running plugin hook "${hook}" for plugin "${plugin}", expected a string, a function hook or an object with a "handler" string or function.`,
  622. plugin
  623. };
  624. }
  625. function logInvalidFunctionPluginHook(hook, plugin) {
  626. return {
  627. code: INVALID_PLUGIN_HOOK,
  628. hook,
  629. message: `Error running plugin hook "${hook}" for plugin "${plugin}", expected a function hook or an object with a "handler" function.`,
  630. plugin
  631. };
  632. }
  633. function logInvalidRollupPhaseForAddWatchFile() {
  634. return {
  635. code: INVALID_ROLLUP_PHASE,
  636. message: `Cannot call "addWatchFile" after the build has finished.`
  637. };
  638. }
  639. function logInvalidRollupPhaseForChunkEmission() {
  640. return {
  641. code: INVALID_ROLLUP_PHASE,
  642. message: `Cannot emit chunks after module loading has finished.`
  643. };
  644. }
  645. function logInvalidSetAssetSourceCall() {
  646. return {
  647. code: INVALID_SETASSETSOURCE,
  648. message: `setAssetSource cannot be called in transform for caching reasons. Use emitFile with a source, or call setAssetSource in another hook.`
  649. };
  650. }
  651. function logInvalidFormatForTopLevelAwait(id, format) {
  652. return {
  653. code: INVALID_TLA_FORMAT,
  654. id,
  655. message: `Module format "${format}" does not support top-level await. Use the "es" or "system" output formats rather.`
  656. };
  657. }
  658. function logMissingConfig() {
  659. return {
  660. code: MISSING_CONFIG,
  661. message: 'Config file must export an options object, or an array of options objects',
  662. url: getRollupUrl(URL_CONFIGURATION_FILES)
  663. };
  664. }
  665. function logMissingExport(binding, importingModule, exporter) {
  666. const isJson = node_path.extname(exporter) === '.json';
  667. return {
  668. binding,
  669. code: MISSING_EXPORT,
  670. exporter,
  671. id: importingModule,
  672. message: `"${binding}" is not exported by "${relativeId(exporter)}", imported by "${relativeId(importingModule)}".${isJson ? ' (Note that you need @rollup/plugin-json to import JSON files)' : ''}`,
  673. url: getRollupUrl(URL_NAME_IS_NOT_EXPORTED)
  674. };
  675. }
  676. function logMissingExternalConfig(file) {
  677. return {
  678. code: MISSING_EXTERNAL_CONFIG,
  679. message: `Could not resolve config file "${file}"`
  680. };
  681. }
  682. function logMissingGlobalName(externalId, guess) {
  683. return {
  684. code: MISSING_GLOBAL_NAME,
  685. id: externalId,
  686. message: `No name was provided for external module "${externalId}" in "output.globals" – guessing "${guess}".`,
  687. names: [guess],
  688. url: getRollupUrl(URL_OUTPUT_GLOBALS)
  689. };
  690. }
  691. function logImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore) {
  692. return {
  693. code: MISSING_IMPLICIT_DEPENDANT,
  694. message: `Module "${relativeId(unresolvedId)}" that should be implicitly loaded before "${relativeId(implicitlyLoadedBefore)}" cannot be external.`
  695. };
  696. }
  697. function logUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore) {
  698. return {
  699. code: MISSING_IMPLICIT_DEPENDANT,
  700. message: `Module "${relativeId(unresolvedId)}" that should be implicitly loaded before "${relativeId(implicitlyLoadedBefore)}" could not be resolved.`
  701. };
  702. }
  703. function logImplicitDependantIsNotIncluded(module) {
  704. const implicitDependencies = [...module.implicitlyLoadedBefore]
  705. .map(dependency => relativeId(dependency.id))
  706. .sort();
  707. return {
  708. code: MISSING_IMPLICIT_DEPENDANT,
  709. 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.`
  710. };
  711. }
  712. function logMissingNameOptionForIifeExport() {
  713. return {
  714. code: MISSING_NAME_OPTION_FOR_IIFE_EXPORT,
  715. message: `If you do not supply "output.name", you may not be able to access the exports of an IIFE bundle.`,
  716. url: getRollupUrl(URL_OUTPUT_NAME)
  717. };
  718. }
  719. function logMissingNameOptionForUmdExport() {
  720. return {
  721. code: MISSING_NAME_OPTION_FOR_IIFE_EXPORT,
  722. message: 'You must supply "output.name" for UMD bundles that have exports so that the exports are accessible in environments without a module loader.',
  723. url: getRollupUrl(URL_OUTPUT_NAME)
  724. };
  725. }
  726. function logMissingNodeBuiltins(externalBuiltins) {
  727. return {
  728. code: MISSING_NODE_BUILTINS,
  729. ids: externalBuiltins,
  730. 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`
  731. };
  732. }
  733. // eslint-disable-next-line unicorn/prevent-abbreviations
  734. function logMissingFileOrDirOption() {
  735. return {
  736. code: MISSING_OPTION,
  737. message: 'You must specify "output.file" or "output.dir" for the build.',
  738. url: getRollupUrl(URL_OUTPUT_DIR)
  739. };
  740. }
  741. function logMixedExport(facadeModuleId, name) {
  742. return {
  743. code: MIXED_EXPORTS,
  744. id: facadeModuleId,
  745. 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.`,
  746. url: getRollupUrl(URL_OUTPUT_EXPORTS)
  747. };
  748. }
  749. function logModuleLevelDirective(directive, id) {
  750. return {
  751. code: MODULE_LEVEL_DIRECTIVE,
  752. id,
  753. message: `Module level directives cause errors when bundled, "${directive}" in "${relativeId(id)}" was ignored.`
  754. };
  755. }
  756. function logNamespaceConflict(binding, reexportingModuleId, sources) {
  757. return {
  758. binding,
  759. code: NAMESPACE_CONFLICT,
  760. ids: sources,
  761. message: `Conflicting namespaces: "${relativeId(reexportingModuleId)}" re-exports "${binding}" from one of the modules ${printQuotedStringList(sources.map(moduleId => relativeId(moduleId)))} (will be ignored).`,
  762. reexporter: reexportingModuleId
  763. };
  764. }
  765. function logNoTransformMapOrAstWithoutCode(pluginName) {
  766. return {
  767. code: NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE,
  768. message: `The plugin "${pluginName}" returned a "map" or "ast" without returning ` +
  769. 'a "code". This will be ignored.'
  770. };
  771. }
  772. function logOnlyInlineSourcemapsForStdout() {
  773. return {
  774. code: ONLY_INLINE_SOURCEMAPS,
  775. message: 'Only inline sourcemaps are supported when bundling to stdout.'
  776. };
  777. }
  778. function logOptimizeChunkStatus(chunks, smallChunks, pointInTime) {
  779. return {
  780. code: OPTIMIZE_CHUNK_STATUS,
  781. message: `${pointInTime}, there are\n` +
  782. `${chunks} chunks, of which\n` +
  783. `${smallChunks} are below minChunkSize.`
  784. };
  785. }
  786. function logParseError(error, moduleId) {
  787. let message = error.message.replace(/ \(\d+:\d+\)$/, '');
  788. if (moduleId.endsWith('.json')) {
  789. message += ' (Note that you need @rollup/plugin-json to import JSON files)';
  790. }
  791. else if (!moduleId.endsWith('.js')) {
  792. message += ' (Note that you need plugins to import files that are not JavaScript)';
  793. }
  794. return {
  795. cause: error,
  796. code: PARSE_ERROR,
  797. id: moduleId,
  798. message
  799. };
  800. }
  801. function logPluginError(error, plugin, { hook, id } = {}) {
  802. const code = error.code;
  803. if (!error.pluginCode &&
  804. code != null &&
  805. (typeof code !== 'string' || (typeof code === 'string' && !code.startsWith('PLUGIN_')))) {
  806. error.pluginCode = code;
  807. }
  808. error.code = PLUGIN_ERROR;
  809. error.plugin = plugin;
  810. if (hook) {
  811. error.hook = hook;
  812. }
  813. if (id) {
  814. error.id = id;
  815. }
  816. return error;
  817. }
  818. function logShimmedExport(id, binding) {
  819. return {
  820. binding,
  821. code: SHIMMED_EXPORT,
  822. exporter: id,
  823. message: `Missing export "${binding}" has been shimmed in module "${relativeId(id)}".`
  824. };
  825. }
  826. function logSourcemapBroken(plugin) {
  827. return {
  828. code: SOURCEMAP_BROKEN,
  829. 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`,
  830. plugin,
  831. url: getRollupUrl(URL_SOURCEMAP_IS_LIKELY_TO_BE_INCORRECT)
  832. };
  833. }
  834. function logConflictingSourcemapSources(filename) {
  835. return {
  836. code: SOURCEMAP_BROKEN,
  837. message: `Multiple conflicting contents for sourcemap source ${filename}`
  838. };
  839. }
  840. function logInvalidSourcemapForError(error, id, column, line, pos) {
  841. return {
  842. cause: error,
  843. code: SOURCEMAP_ERROR,
  844. id,
  845. loc: {
  846. column,
  847. file: id,
  848. line
  849. },
  850. message: `Error when using sourcemap for reporting an error: ${error.message}`,
  851. pos
  852. };
  853. }
  854. function logSyntheticNamedExportsNeedNamespaceExport(id, syntheticNamedExportsOption) {
  855. return {
  856. code: SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT,
  857. exporter: id,
  858. message: `Module "${relativeId(id)}" that is marked with \`syntheticNamedExports: ${JSON.stringify(syntheticNamedExportsOption)}\` needs ${typeof syntheticNamedExportsOption === 'string' && syntheticNamedExportsOption !== 'default'
  859. ? `an explicit export named "${syntheticNamedExportsOption}"`
  860. : 'a default export'} that does not reexport an unresolved named export of the same module.`
  861. };
  862. }
  863. function logThisIsUndefined() {
  864. return {
  865. code: THIS_IS_UNDEFINED,
  866. message: `The 'this' keyword is equivalent to 'undefined' at the top level of an ES module, and has been rewritten`,
  867. url: getRollupUrl(URL_THIS_IS_UNDEFINED)
  868. };
  869. }
  870. function logUnexpectedNamedImport(id, imported, isReexport) {
  871. const importType = isReexport ? 'reexport' : 'import';
  872. return {
  873. code: UNEXPECTED_NAMED_IMPORT,
  874. exporter: id,
  875. 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.`,
  876. url: getRollupUrl(URL_OUTPUT_INTEROP)
  877. };
  878. }
  879. function logUnexpectedNamespaceReexport(id) {
  880. return {
  881. code: UNEXPECTED_NAMED_IMPORT,
  882. exporter: id,
  883. 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.`,
  884. url: getRollupUrl(URL_OUTPUT_INTEROP)
  885. };
  886. }
  887. function logUnknownOption(optionType, unknownOptions, validOptions) {
  888. return {
  889. code: UNKNOWN_OPTION,
  890. message: `Unknown ${optionType}: ${unknownOptions.join(', ')}. Allowed options: ${validOptions.join(', ')}`
  891. };
  892. }
  893. function logEntryCannotBeExternal(unresolvedId) {
  894. return {
  895. code: UNRESOLVED_ENTRY,
  896. message: `Entry module "${relativeId(unresolvedId)}" cannot be external.`
  897. };
  898. }
  899. function logExternalModulesCannotBeIncludedInManualChunks(source) {
  900. return {
  901. code: EXTERNAL_MODULES_CANNOT_BE_INCLUDED_IN_MANUAL_CHUNKS,
  902. message: `"${source}" cannot be included in manualChunks because it is resolved as an external module by the "external" option or plugins.`
  903. };
  904. }
  905. function logExternalModulesCannotBeTransformedToModules(source) {
  906. return {
  907. code: EXTERNAL_MODULES_CANNOT_BE_TRANSFORMED_TO_MODULES,
  908. 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.`
  909. };
  910. }
  911. function logUnresolvedEntry(unresolvedId) {
  912. return {
  913. code: UNRESOLVED_ENTRY,
  914. message: `Could not resolve entry module "${relativeId(unresolvedId)}".`
  915. };
  916. }
  917. function logUnresolvedImport(source, importer) {
  918. return {
  919. code: UNRESOLVED_IMPORT,
  920. exporter: source,
  921. id: importer,
  922. message: `Could not resolve "${source}" from "${relativeId(importer)}"`
  923. };
  924. }
  925. function logUnresolvedImportTreatedAsExternal(source, importer) {
  926. return {
  927. code: UNRESOLVED_IMPORT,
  928. exporter: source,
  929. id: importer,
  930. message: `"${source}" is imported by "${relativeId(importer)}", but could not be resolved – treating it as an external dependency.`,
  931. url: getRollupUrl(URL_TREATING_MODULE_AS_EXTERNAL_DEPENDENCY)
  932. };
  933. }
  934. function logUnusedExternalImports(externalId, names, importers) {
  935. return {
  936. code: UNUSED_EXTERNAL_IMPORT,
  937. exporter: externalId,
  938. ids: importers,
  939. message: `${printQuotedStringList(names, [
  940. 'is',
  941. 'are'
  942. ])} imported from external module "${externalId}" but never used in ${printQuotedStringList(importers.map(importer => relativeId(importer)))}.`,
  943. names
  944. };
  945. }
  946. function logFailedValidation(message) {
  947. return {
  948. code: VALIDATION_ERROR,
  949. message
  950. };
  951. }
  952. function warnDeprecation(deprecation, urlSnippet, activeDeprecation, options, plugin) {
  953. warnDeprecationWithOptions(deprecation, urlSnippet, activeDeprecation, options.onLog, options.strictDeprecations, plugin);
  954. }
  955. function warnDeprecationWithOptions(deprecation, urlSnippet, activeDeprecation, log, strictDeprecations, plugin) {
  956. if (activeDeprecation || strictDeprecations) {
  957. const warning = logDeprecation(deprecation, urlSnippet, plugin);
  958. if (strictDeprecations) {
  959. return error(warning);
  960. }
  961. log(LOGLEVEL_WARN, warning);
  962. }
  963. }
  964. // Four random characters from the private use area to minimize risk of
  965. // conflicts
  966. const hashPlaceholderLeft = '!~{';
  967. const hashPlaceholderRight = '}~';
  968. const hashPlaceholderOverhead = hashPlaceholderLeft.length + hashPlaceholderRight.length;
  969. // This is the size of a sha256
  970. const maxHashSize = 64;
  971. const defaultHashSize = 8;
  972. const getHashPlaceholderGenerator = () => {
  973. let nextIndex = 0;
  974. return (optionName, hashSize = defaultHashSize) => {
  975. if (hashSize > maxHashSize) {
  976. return error(logFailedValidation(`Hashes cannot be longer than ${maxHashSize} characters, received ${hashSize}. Check the "${optionName}" option.`));
  977. }
  978. const placeholder = `${hashPlaceholderLeft}${toBase64(++nextIndex).padStart(hashSize - hashPlaceholderOverhead, '0')}${hashPlaceholderRight}`;
  979. if (placeholder.length > hashSize) {
  980. 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.`));
  981. }
  982. return placeholder;
  983. };
  984. };
  985. const REPLACER_REGEX = new RegExp(`${hashPlaceholderLeft}[0-9a-zA-Z_$]{1,${maxHashSize - hashPlaceholderOverhead}}${hashPlaceholderRight}`, 'g');
  986. const replacePlaceholders = (code, hashesByPlaceholder) => code.replace(REPLACER_REGEX, placeholder => hashesByPlaceholder.get(placeholder) || placeholder);
  987. const replaceSinglePlaceholder = (code, placeholder, value) => code.replace(REPLACER_REGEX, match => (match === placeholder ? value : match));
  988. const replacePlaceholdersWithDefaultAndGetContainedPlaceholders = (code, placeholders) => {
  989. const containedPlaceholders = new Set();
  990. const transformedCode = code.replace(REPLACER_REGEX, placeholder => {
  991. if (placeholders.has(placeholder)) {
  992. containedPlaceholders.add(placeholder);
  993. return `${hashPlaceholderLeft}${'0'.repeat(placeholder.length - hashPlaceholderOverhead)}${hashPlaceholderRight}`;
  994. }
  995. return placeholder;
  996. });
  997. return { containedPlaceholders, transformedCode };
  998. };
  999. const lowercaseBundleKeys = Symbol('bundleKeys');
  1000. const FILE_PLACEHOLDER = {
  1001. type: 'placeholder'
  1002. };
  1003. const getOutputBundle = (outputBundleBase) => {
  1004. const reservedLowercaseBundleKeys = new Set();
  1005. return new Proxy(outputBundleBase, {
  1006. deleteProperty(target, key) {
  1007. if (typeof key === 'string') {
  1008. reservedLowercaseBundleKeys.delete(key.toLowerCase());
  1009. }
  1010. return Reflect.deleteProperty(target, key);
  1011. },
  1012. get(target, key) {
  1013. if (key === lowercaseBundleKeys) {
  1014. return reservedLowercaseBundleKeys;
  1015. }
  1016. return Reflect.get(target, key);
  1017. },
  1018. set(target, key, value) {
  1019. if (typeof key === 'string') {
  1020. reservedLowercaseBundleKeys.add(key.toLowerCase());
  1021. }
  1022. return Reflect.set(target, key, value);
  1023. }
  1024. });
  1025. };
  1026. const removeUnreferencedAssets = (outputBundle) => {
  1027. const unreferencedAssets = new Set();
  1028. const bundleEntries = Object.values(outputBundle);
  1029. for (const asset of bundleEntries) {
  1030. asset.type === 'asset' && asset.needsCodeReference && unreferencedAssets.add(asset.fileName);
  1031. }
  1032. for (const chunk of bundleEntries) {
  1033. if (chunk.type === 'chunk') {
  1034. for (const referencedFile of chunk.referencedFiles) {
  1035. unreferencedAssets.has(referencedFile) && unreferencedAssets.delete(referencedFile);
  1036. }
  1037. }
  1038. }
  1039. for (const file of unreferencedAssets) {
  1040. delete outputBundle[file];
  1041. }
  1042. };
  1043. function renderNamePattern(pattern, patternName, replacements) {
  1044. if (isPathFragment(pattern))
  1045. 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.`));
  1046. return pattern.replace(/\[(\w+)(:\d+)?]/g, (_match, type, size) => {
  1047. if (!replacements.hasOwnProperty(type) || (size && type !== 'hash')) {
  1048. return error(logFailedValidation(`"[${type}${size || ''}]" is not a valid placeholder in the "${patternName}" pattern.`));
  1049. }
  1050. const replacement = replacements[type](size && Number.parseInt(size.slice(1)));
  1051. if (isPathFragment(replacement))
  1052. return error(logFailedValidation(`Invalid substitution "${replacement}" for placeholder "[${type}]" in "${patternName}" pattern, can be neither absolute nor relative path.`));
  1053. return replacement;
  1054. });
  1055. }
  1056. function makeUnique(name, { [lowercaseBundleKeys]: reservedLowercaseBundleKeys }) {
  1057. if (!reservedLowercaseBundleKeys.has(name.toLowerCase()))
  1058. return name;
  1059. const extension = node_path.extname(name);
  1060. name = name.slice(0, Math.max(0, name.length - extension.length));
  1061. let uniqueName, uniqueIndex = 1;
  1062. while (reservedLowercaseBundleKeys.has((uniqueName = name + ++uniqueIndex + extension).toLowerCase()))
  1063. ;
  1064. return uniqueName;
  1065. }
  1066. function getSourceHash(source) {
  1067. return createHash().update(source).digest('hex');
  1068. }
  1069. function generateAssetFileName(name, source, sourceHash, outputOptions, bundle) {
  1070. const emittedName = outputOptions.sanitizeFileName(name || 'asset');
  1071. return makeUnique(renderNamePattern(typeof outputOptions.assetFileNames === 'function'
  1072. ? outputOptions.assetFileNames({ name, source, type: 'asset' })
  1073. : outputOptions.assetFileNames, 'output.assetFileNames', {
  1074. ext: () => node_path.extname(emittedName).slice(1),
  1075. extname: () => node_path.extname(emittedName),
  1076. hash: size => sourceHash.slice(0, Math.max(0, size || defaultHashSize)),
  1077. name: () => emittedName.slice(0, Math.max(0, emittedName.length - node_path.extname(emittedName).length))
  1078. }), bundle);
  1079. }
  1080. function reserveFileNameInBundle(fileName, { bundle }, log) {
  1081. if (bundle[lowercaseBundleKeys].has(fileName.toLowerCase())) {
  1082. log(LOGLEVEL_WARN, logFileNameConflict(fileName));
  1083. }
  1084. else {
  1085. bundle[fileName] = FILE_PLACEHOLDER;
  1086. }
  1087. }
  1088. const emittedFileTypes = new Set(['chunk', 'asset', 'prebuilt-chunk']);
  1089. function hasValidType(emittedFile) {
  1090. return Boolean(emittedFile &&
  1091. emittedFileTypes.has(emittedFile.type));
  1092. }
  1093. function hasValidName(emittedFile) {
  1094. const validatedName = emittedFile.fileName || emittedFile.name;
  1095. return !validatedName || (typeof validatedName === 'string' && !isPathFragment(validatedName));
  1096. }
  1097. function getValidSource(source, emittedFile, fileReferenceId) {
  1098. if (!(typeof source === 'string' || source instanceof Uint8Array)) {
  1099. const assetName = emittedFile.fileName || emittedFile.name || fileReferenceId;
  1100. 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.`));
  1101. }
  1102. return source;
  1103. }
  1104. function getAssetFileName(file, referenceId) {
  1105. if (typeof file.fileName !== 'string') {
  1106. return error(logAssetNotFinalisedForFileName(file.name || referenceId));
  1107. }
  1108. return file.fileName;
  1109. }
  1110. function getChunkFileName(file, facadeChunkByModule) {
  1111. if (file.fileName) {
  1112. return file.fileName;
  1113. }
  1114. if (facadeChunkByModule) {
  1115. return facadeChunkByModule.get(file.module).getFileName();
  1116. }
  1117. return error(logChunkNotGeneratedForFileName(file.fileName || file.name));
  1118. }
  1119. class FileEmitter {
  1120. constructor(graph, options, baseFileEmitter) {
  1121. this.graph = graph;
  1122. this.options = options;
  1123. this.facadeChunkByModule = null;
  1124. this.nextIdBase = 1;
  1125. this.output = null;
  1126. this.outputFileEmitters = [];
  1127. this.emitFile = (emittedFile) => {
  1128. if (!hasValidType(emittedFile)) {
  1129. return error(logFailedValidation(`Emitted files must be of type "asset", "chunk" or "prebuilt-chunk", received "${emittedFile && emittedFile.type}".`));
  1130. }
  1131. if (emittedFile.type === 'prebuilt-chunk') {
  1132. return this.emitPrebuiltChunk(emittedFile);
  1133. }
  1134. if (!hasValidName(emittedFile)) {
  1135. 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}".`));
  1136. }
  1137. if (emittedFile.type === 'chunk') {
  1138. return this.emitChunk(emittedFile);
  1139. }
  1140. return this.emitAsset(emittedFile);
  1141. };
  1142. this.finaliseAssets = () => {
  1143. for (const [referenceId, emittedFile] of this.filesByReferenceId) {
  1144. if (emittedFile.type === 'asset' && typeof emittedFile.fileName !== 'string')
  1145. return error(logNoAssetSourceSet(emittedFile.name || referenceId));
  1146. }
  1147. };
  1148. this.getFileName = (fileReferenceId) => {
  1149. const emittedFile = this.filesByReferenceId.get(fileReferenceId);
  1150. if (!emittedFile)
  1151. return error(logFileReferenceIdNotFoundForFilename(fileReferenceId));
  1152. if (emittedFile.type === 'chunk') {
  1153. return getChunkFileName(emittedFile, this.facadeChunkByModule);
  1154. }
  1155. if (emittedFile.type === 'prebuilt-chunk') {
  1156. return emittedFile.fileName;
  1157. }
  1158. return getAssetFileName(emittedFile, fileReferenceId);
  1159. };
  1160. this.setAssetSource = (referenceId, requestedSource) => {
  1161. const consumedFile = this.filesByReferenceId.get(referenceId);
  1162. if (!consumedFile)
  1163. return error(logAssetReferenceIdNotFoundForSetSource(referenceId));
  1164. if (consumedFile.type !== 'asset') {
  1165. return error(logFailedValidation(`Asset sources can only be set for emitted assets but "${referenceId}" is an emitted chunk.`));
  1166. }
  1167. if (consumedFile.source !== undefined) {
  1168. return error(logAssetSourceAlreadySet(consumedFile.name || referenceId));
  1169. }
  1170. const source = getValidSource(requestedSource, consumedFile, referenceId);
  1171. if (this.output) {
  1172. this.finalizeAdditionalAsset(consumedFile, source, this.output);
  1173. }
  1174. else {
  1175. consumedFile.source = source;
  1176. for (const emitter of this.outputFileEmitters) {
  1177. emitter.finalizeAdditionalAsset(consumedFile, source, emitter.output);
  1178. }
  1179. }
  1180. };
  1181. this.setChunkInformation = (facadeChunkByModule) => {
  1182. this.facadeChunkByModule = facadeChunkByModule;
  1183. };
  1184. this.setOutputBundle = (bundle, outputOptions) => {
  1185. const output = (this.output = {
  1186. bundle,
  1187. fileNamesBySource: new Map(),
  1188. outputOptions
  1189. });
  1190. for (const emittedFile of this.filesByReferenceId.values()) {
  1191. if (emittedFile.fileName) {
  1192. reserveFileNameInBundle(emittedFile.fileName, output, this.options.onLog);
  1193. }
  1194. }
  1195. const consumedAssetsByHash = new Map();
  1196. for (const consumedFile of this.filesByReferenceId.values()) {
  1197. if (consumedFile.type === 'asset' && consumedFile.source !== undefined) {
  1198. if (consumedFile.fileName) {
  1199. this.finalizeAdditionalAsset(consumedFile, consumedFile.source, output);
  1200. }
  1201. else {
  1202. const sourceHash = getSourceHash(consumedFile.source);
  1203. getOrCreate(consumedAssetsByHash, sourceHash, () => []).push(consumedFile);
  1204. }
  1205. }
  1206. else if (consumedFile.type === 'prebuilt-chunk') {
  1207. this.output.bundle[consumedFile.fileName] = this.createPrebuiltChunk(consumedFile);
  1208. }
  1209. }
  1210. for (const [sourceHash, consumedFiles] of consumedAssetsByHash) {
  1211. this.finalizeAssetsWithSameSource(consumedFiles, sourceHash, output);
  1212. }
  1213. };
  1214. this.filesByReferenceId = baseFileEmitter
  1215. ? new Map(baseFileEmitter.filesByReferenceId)
  1216. : new Map();
  1217. baseFileEmitter?.addOutputFileEmitter(this);
  1218. }
  1219. addOutputFileEmitter(outputFileEmitter) {
  1220. this.outputFileEmitters.push(outputFileEmitter);
  1221. }
  1222. assignReferenceId(file, idBase) {
  1223. let referenceId = idBase;
  1224. do {
  1225. referenceId = createHash().update(referenceId).digest('hex').slice(0, 8);
  1226. } while (this.filesByReferenceId.has(referenceId) ||
  1227. this.outputFileEmitters.some(({ filesByReferenceId }) => filesByReferenceId.has(referenceId)));
  1228. file.referenceId = referenceId;
  1229. this.filesByReferenceId.set(referenceId, file);
  1230. for (const { filesByReferenceId } of this.outputFileEmitters) {
  1231. filesByReferenceId.set(referenceId, file);
  1232. }
  1233. return referenceId;
  1234. }
  1235. createPrebuiltChunk(prebuiltChunk) {
  1236. return {
  1237. code: prebuiltChunk.code,
  1238. dynamicImports: [],
  1239. exports: prebuiltChunk.exports || [],
  1240. facadeModuleId: null,
  1241. fileName: prebuiltChunk.fileName,
  1242. implicitlyLoadedBefore: [],
  1243. importedBindings: {},
  1244. imports: [],
  1245. isDynamicEntry: false,
  1246. isEntry: false,
  1247. isImplicitEntry: false,
  1248. map: prebuiltChunk.map || null,
  1249. moduleIds: [],
  1250. modules: {},
  1251. name: prebuiltChunk.fileName,
  1252. preliminaryFileName: prebuiltChunk.fileName,
  1253. referencedFiles: [],
  1254. sourcemapFileName: prebuiltChunk.sourcemapFileName || null,
  1255. type: 'chunk'
  1256. };
  1257. }
  1258. emitAsset(emittedAsset) {
  1259. const source = emittedAsset.source === undefined
  1260. ? undefined
  1261. : getValidSource(emittedAsset.source, emittedAsset, null);
  1262. const consumedAsset = {
  1263. fileName: emittedAsset.fileName,
  1264. name: emittedAsset.name,
  1265. needsCodeReference: !!emittedAsset.needsCodeReference,
  1266. referenceId: '',
  1267. source,
  1268. type: 'asset'
  1269. };
  1270. const referenceId = this.assignReferenceId(consumedAsset, emittedAsset.fileName || emittedAsset.name || String(this.nextIdBase++));
  1271. if (this.output) {
  1272. this.emitAssetWithReferenceId(consumedAsset, this.output);
  1273. }
  1274. else {
  1275. for (const fileEmitter of this.outputFileEmitters) {
  1276. fileEmitter.emitAssetWithReferenceId(consumedAsset, fileEmitter.output);
  1277. }
  1278. }
  1279. return referenceId;
  1280. }
  1281. emitAssetWithReferenceId(consumedAsset, output) {
  1282. const { fileName, source } = consumedAsset;
  1283. if (fileName) {
  1284. reserveFileNameInBundle(fileName, output, this.options.onLog);
  1285. }
  1286. if (source !== undefined) {
  1287. this.finalizeAdditionalAsset(consumedAsset, source, output);
  1288. }
  1289. }
  1290. emitChunk(emittedChunk) {
  1291. if (this.graph.phase > BuildPhase.LOAD_AND_PARSE) {
  1292. return error(logInvalidRollupPhaseForChunkEmission());
  1293. }
  1294. if (typeof emittedChunk.id !== 'string') {
  1295. return error(logFailedValidation(`Emitted chunks need to have a valid string id, received "${emittedChunk.id}"`));
  1296. }
  1297. const consumedChunk = {
  1298. fileName: emittedChunk.fileName,
  1299. module: null,
  1300. name: emittedChunk.name || emittedChunk.id,
  1301. referenceId: '',
  1302. type: 'chunk'
  1303. };
  1304. this.graph.moduleLoader
  1305. .emitChunk(emittedChunk)
  1306. .then(module => (consumedChunk.module = module))
  1307. .catch(() => {
  1308. // Avoid unhandled Promise rejection as the error will be thrown later
  1309. // once module loading has finished
  1310. });
  1311. return this.assignReferenceId(consumedChunk, emittedChunk.id);
  1312. }
  1313. emitPrebuiltChunk(emitPrebuiltChunk) {
  1314. if (typeof emitPrebuiltChunk.code !== 'string') {
  1315. return error(logFailedValidation(`Emitted prebuilt chunks need to have a valid string code, received "${emitPrebuiltChunk.code}".`));
  1316. }
  1317. if (typeof emitPrebuiltChunk.fileName !== 'string' ||
  1318. isPathFragment(emitPrebuiltChunk.fileName)) {
  1319. return error(logFailedValidation(`The "fileName" property of emitted prebuilt chunks must be strings that are neither absolute nor relative paths, received "${emitPrebuiltChunk.fileName}".`));
  1320. }
  1321. const consumedPrebuiltChunk = {
  1322. code: emitPrebuiltChunk.code,
  1323. exports: emitPrebuiltChunk.exports,
  1324. fileName: emitPrebuiltChunk.fileName,
  1325. map: emitPrebuiltChunk.map,
  1326. referenceId: '',
  1327. type: 'prebuilt-chunk'
  1328. };
  1329. const referenceId = this.assignReferenceId(consumedPrebuiltChunk, consumedPrebuiltChunk.fileName);
  1330. if (this.output) {
  1331. this.output.bundle[consumedPrebuiltChunk.fileName] =
  1332. this.createPrebuiltChunk(consumedPrebuiltChunk);
  1333. }
  1334. return referenceId;
  1335. }
  1336. finalizeAdditionalAsset(consumedFile, source, { bundle, fileNamesBySource, outputOptions }) {
  1337. let { fileName, needsCodeReference, referenceId } = consumedFile;
  1338. // Deduplicate assets if an explicit fileName is not provided
  1339. if (!fileName) {
  1340. const sourceHash = getSourceHash(source);
  1341. fileName = fileNamesBySource.get(sourceHash);
  1342. if (!fileName) {
  1343. fileName = generateAssetFileName(consumedFile.name, source, sourceHash, outputOptions, bundle);
  1344. fileNamesBySource.set(sourceHash, fileName);
  1345. }
  1346. }
  1347. // We must not modify the original assets to avoid interaction between outputs
  1348. const assetWithFileName = { ...consumedFile, fileName, source };
  1349. this.filesByReferenceId.set(referenceId, assetWithFileName);
  1350. const existingAsset = bundle[fileName];
  1351. if (existingAsset?.type === 'asset') {
  1352. existingAsset.needsCodeReference && (existingAsset.needsCodeReference = needsCodeReference);
  1353. }
  1354. else {
  1355. bundle[fileName] = {
  1356. fileName,
  1357. name: consumedFile.name,
  1358. needsCodeReference,
  1359. source,
  1360. type: 'asset'
  1361. };
  1362. }
  1363. }
  1364. finalizeAssetsWithSameSource(consumedFiles, sourceHash, { bundle, fileNamesBySource, outputOptions }) {
  1365. let fileName = '';
  1366. let usedConsumedFile;
  1367. let needsCodeReference = true;
  1368. for (const consumedFile of consumedFiles) {
  1369. needsCodeReference && (needsCodeReference = consumedFile.needsCodeReference);
  1370. const assetFileName = generateAssetFileName(consumedFile.name, consumedFile.source, sourceHash, outputOptions, bundle);
  1371. if (!fileName ||
  1372. assetFileName.length < fileName.length ||
  1373. (assetFileName.length === fileName.length && assetFileName < fileName)) {
  1374. fileName = assetFileName;
  1375. usedConsumedFile = consumedFile;
  1376. }
  1377. }
  1378. fileNamesBySource.set(sourceHash, fileName);
  1379. for (const consumedFile of consumedFiles) {
  1380. // We must not modify the original assets to avoid interaction between outputs
  1381. const assetWithFileName = { ...consumedFile, fileName };
  1382. this.filesByReferenceId.set(consumedFile.referenceId, assetWithFileName);
  1383. }
  1384. bundle[fileName] = {
  1385. fileName,
  1386. name: usedConsumedFile.name,
  1387. needsCodeReference,
  1388. source: usedConsumedFile.source,
  1389. type: 'asset'
  1390. };
  1391. }
  1392. }
  1393. const ANONYMOUS_PLUGIN_PREFIX = 'at position ';
  1394. const ANONYMOUS_OUTPUT_PLUGIN_PREFIX = 'at output position ';
  1395. function createPluginCache(cache) {
  1396. return {
  1397. delete(id) {
  1398. return delete cache[id];
  1399. },
  1400. get(id) {
  1401. const item = cache[id];
  1402. if (!item)
  1403. return;
  1404. item[0] = 0;
  1405. return item[1];
  1406. },
  1407. has(id) {
  1408. const item = cache[id];
  1409. if (!item)
  1410. return false;
  1411. item[0] = 0;
  1412. return true;
  1413. },
  1414. set(id, value) {
  1415. cache[id] = [0, value];
  1416. }
  1417. };
  1418. }
  1419. function getTrackedPluginCache(pluginCache, onUse) {
  1420. return {
  1421. delete(id) {
  1422. onUse();
  1423. return pluginCache.delete(id);
  1424. },
  1425. get(id) {
  1426. onUse();
  1427. return pluginCache.get(id);
  1428. },
  1429. has(id) {
  1430. onUse();
  1431. return pluginCache.has(id);
  1432. },
  1433. set(id, value) {
  1434. onUse();
  1435. return pluginCache.set(id, value);
  1436. }
  1437. };
  1438. }
  1439. const NO_CACHE = {
  1440. delete() {
  1441. return false;
  1442. },
  1443. get() {
  1444. return undefined;
  1445. },
  1446. has() {
  1447. return false;
  1448. },
  1449. set() { }
  1450. };
  1451. function uncacheablePluginError(pluginName) {
  1452. if (pluginName.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  1453. pluginName.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX)) {
  1454. return error(logAnonymousPluginCache());
  1455. }
  1456. return error(logDuplicatePluginName(pluginName));
  1457. }
  1458. function getCacheForUncacheablePlugin(pluginName) {
  1459. return {
  1460. delete() {
  1461. return uncacheablePluginError(pluginName);
  1462. },
  1463. get() {
  1464. return uncacheablePluginError(pluginName);
  1465. },
  1466. has() {
  1467. return uncacheablePluginError(pluginName);
  1468. },
  1469. set() {
  1470. return uncacheablePluginError(pluginName);
  1471. }
  1472. };
  1473. }
  1474. const BLANK = Object.freeze(Object.create(null));
  1475. const EMPTY_OBJECT = Object.freeze({});
  1476. const EMPTY_ARRAY = Object.freeze([]);
  1477. const EMPTY_SET = Object.freeze(new (class extends Set {
  1478. add() {
  1479. throw new Error('Cannot add to empty set');
  1480. }
  1481. })());
  1482. const doNothing = () => { };
  1483. async function asyncFlatten(array) {
  1484. do {
  1485. array = (await Promise.all(array)).flat(Infinity);
  1486. } while (array.some((v) => v?.then));
  1487. return array;
  1488. }
  1489. const getOnLog = (config, logLevel, printLog = defaultPrintLog) => {
  1490. const { onwarn, onLog } = config;
  1491. const defaultOnLog = getDefaultOnLog(printLog, onwarn);
  1492. if (onLog) {
  1493. const minimalPriority = logLevelPriority[logLevel];
  1494. return (level, log) => onLog(level, addLogToString(log), (level, handledLog) => {
  1495. if (level === LOGLEVEL_ERROR) {
  1496. return error(normalizeLog(handledLog));
  1497. }
  1498. if (logLevelPriority[level] >= minimalPriority) {
  1499. defaultOnLog(level, normalizeLog(handledLog));
  1500. }
  1501. });
  1502. }
  1503. return defaultOnLog;
  1504. };
  1505. const getDefaultOnLog = (printLog, onwarn) => onwarn
  1506. ? (level, log) => {
  1507. if (level === LOGLEVEL_WARN) {
  1508. onwarn(addLogToString(log), warning => printLog(LOGLEVEL_WARN, normalizeLog(warning)));
  1509. }
  1510. else {
  1511. printLog(level, log);
  1512. }
  1513. }
  1514. : printLog;
  1515. const addLogToString = (log) => {
  1516. Object.defineProperty(log, 'toString', {
  1517. value: () => getExtendedLogMessage(log),
  1518. writable: true
  1519. });
  1520. return log;
  1521. };
  1522. const normalizeLog = (log) => typeof log === 'string'
  1523. ? { message: log }
  1524. : typeof log === 'function'
  1525. ? normalizeLog(log())
  1526. : log;
  1527. const getExtendedLogMessage = (log) => {
  1528. let prefix = '';
  1529. if (log.plugin) {
  1530. prefix += `(${log.plugin} plugin) `;
  1531. }
  1532. if (log.loc) {
  1533. prefix += `${relativeId(log.loc.file)} (${log.loc.line}:${log.loc.column}) `;
  1534. }
  1535. return prefix + log.message;
  1536. };
  1537. const defaultPrintLog = (level, log) => {
  1538. const message = getExtendedLogMessage(log);
  1539. switch (level) {
  1540. case LOGLEVEL_WARN: {
  1541. return console.warn(message);
  1542. }
  1543. case LOGLEVEL_DEBUG: {
  1544. return console.debug(message);
  1545. }
  1546. default: {
  1547. return console.info(message);
  1548. }
  1549. }
  1550. };
  1551. function warnUnknownOptions(passedOptions, validOptions, optionType, log, ignoredKeys = /$./) {
  1552. const validOptionSet = new Set(validOptions);
  1553. const unknownOptions = Object.keys(passedOptions).filter(key => !(validOptionSet.has(key) || ignoredKeys.test(key)));
  1554. if (unknownOptions.length > 0) {
  1555. log(LOGLEVEL_WARN, logUnknownOption(optionType, unknownOptions, [...validOptionSet].sort()));
  1556. }
  1557. }
  1558. const treeshakePresets = {
  1559. recommended: {
  1560. annotations: true,
  1561. correctVarValueBeforeDeclaration: false,
  1562. manualPureFunctions: EMPTY_ARRAY,
  1563. moduleSideEffects: () => true,
  1564. propertyReadSideEffects: true,
  1565. tryCatchDeoptimization: true,
  1566. unknownGlobalSideEffects: false
  1567. },
  1568. safest: {
  1569. annotations: true,
  1570. correctVarValueBeforeDeclaration: true,
  1571. manualPureFunctions: EMPTY_ARRAY,
  1572. moduleSideEffects: () => true,
  1573. propertyReadSideEffects: true,
  1574. tryCatchDeoptimization: true,
  1575. unknownGlobalSideEffects: true
  1576. },
  1577. smallest: {
  1578. annotations: true,
  1579. correctVarValueBeforeDeclaration: false,
  1580. manualPureFunctions: EMPTY_ARRAY,
  1581. moduleSideEffects: () => false,
  1582. propertyReadSideEffects: false,
  1583. tryCatchDeoptimization: false,
  1584. unknownGlobalSideEffects: false
  1585. }
  1586. };
  1587. const generatedCodePresets = {
  1588. es2015: {
  1589. arrowFunctions: true,
  1590. constBindings: true,
  1591. objectShorthand: true,
  1592. reservedNamesAsProps: true,
  1593. symbols: true
  1594. },
  1595. es5: {
  1596. arrowFunctions: false,
  1597. constBindings: false,
  1598. objectShorthand: false,
  1599. reservedNamesAsProps: true,
  1600. symbols: false
  1601. }
  1602. };
  1603. const objectifyOption = (value) => value && typeof value === 'object' ? value : {};
  1604. const objectifyOptionWithPresets = (presets, optionName, urlSnippet, additionalValues) => (value) => {
  1605. if (typeof value === 'string') {
  1606. const preset = presets[value];
  1607. if (preset) {
  1608. return preset;
  1609. }
  1610. error(logInvalidOption(optionName, urlSnippet, `valid values are ${additionalValues}${printQuotedStringList(Object.keys(presets))}. You can also supply an object for more fine-grained control`, value));
  1611. }
  1612. return objectifyOption(value);
  1613. };
  1614. const getOptionWithPreset = (value, presets, optionName, urlSnippet, additionalValues) => {
  1615. const presetName = value?.preset;
  1616. if (presetName) {
  1617. const preset = presets[presetName];
  1618. if (preset) {
  1619. return { ...preset, ...value };
  1620. }
  1621. else {
  1622. error(logInvalidOption(`${optionName}.preset`, urlSnippet, `valid values are ${printQuotedStringList(Object.keys(presets))}`, presetName));
  1623. }
  1624. }
  1625. return objectifyOptionWithPresets(presets, optionName, urlSnippet, additionalValues)(value);
  1626. };
  1627. const normalizePluginOption = async (plugins) => (await asyncFlatten([plugins])).filter(Boolean);
  1628. function getLogHandler(level, code, logger, pluginName, logLevel) {
  1629. if (logLevelPriority[level] < logLevelPriority[logLevel]) {
  1630. return doNothing;
  1631. }
  1632. return (log, pos) => {
  1633. if (pos != null) {
  1634. logger(LOGLEVEL_WARN, logInvalidLogPosition(pluginName));
  1635. }
  1636. log = normalizeLog(log);
  1637. if (log.code && !log.pluginCode) {
  1638. log.pluginCode = log.code;
  1639. }
  1640. log.code = code;
  1641. log.plugin = pluginName;
  1642. logger(level, log);
  1643. };
  1644. }
  1645. function getPluginContext(plugin, pluginCache, graph, options, fileEmitter, existingPluginNames) {
  1646. const { logLevel, onLog } = options;
  1647. let cacheable = true;
  1648. if (typeof plugin.cacheKey !== 'string') {
  1649. if (plugin.name.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  1650. plugin.name.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX) ||
  1651. existingPluginNames.has(plugin.name)) {
  1652. cacheable = false;
  1653. }
  1654. else {
  1655. existingPluginNames.add(plugin.name);
  1656. }
  1657. }
  1658. let cacheInstance;
  1659. if (!pluginCache) {
  1660. cacheInstance = NO_CACHE;
  1661. }
  1662. else if (cacheable) {
  1663. const cacheKey = plugin.cacheKey || plugin.name;
  1664. cacheInstance = createPluginCache(pluginCache[cacheKey] || (pluginCache[cacheKey] = Object.create(null)));
  1665. }
  1666. else {
  1667. cacheInstance = getCacheForUncacheablePlugin(plugin.name);
  1668. }
  1669. return {
  1670. addWatchFile(id) {
  1671. if (graph.phase >= BuildPhase.GENERATE) {
  1672. return this.error(logInvalidRollupPhaseForAddWatchFile());
  1673. }
  1674. graph.watchFiles[id] = true;
  1675. },
  1676. cache: cacheInstance,
  1677. debug: getLogHandler(LOGLEVEL_DEBUG, 'PLUGIN_LOG', onLog, plugin.name, logLevel),
  1678. emitFile: fileEmitter.emitFile.bind(fileEmitter),
  1679. error(error_) {
  1680. return error(logPluginError(normalizeLog(error_), plugin.name));
  1681. },
  1682. getFileName: fileEmitter.getFileName,
  1683. getModuleIds: () => graph.modulesById.keys(),
  1684. getModuleInfo: graph.getModuleInfo,
  1685. getWatchFiles: () => Object.keys(graph.watchFiles),
  1686. info: getLogHandler(LOGLEVEL_INFO, 'PLUGIN_LOG', onLog, plugin.name, logLevel),
  1687. load(resolvedId) {
  1688. return graph.moduleLoader.preloadModule(resolvedId);
  1689. },
  1690. meta: {
  1691. rollupVersion: version$1,
  1692. watchMode: graph.watchMode
  1693. },
  1694. get moduleIds() {
  1695. function* wrappedModuleIds() {
  1696. // We are wrapping this in a generator to only show the message once we are actually iterating
  1697. 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);
  1698. yield* moduleIds;
  1699. }
  1700. const moduleIds = graph.modulesById.keys();
  1701. return wrappedModuleIds();
  1702. },
  1703. parse: graph.contextParse.bind(graph),
  1704. resolve(source, importer, { assertions, custom, isEntry, skipSelf } = BLANK) {
  1705. return graph.moduleLoader.resolveId(source, importer, custom, isEntry, assertions || EMPTY_OBJECT, skipSelf ? [{ importer, plugin, source }] : null);
  1706. },
  1707. setAssetSource: fileEmitter.setAssetSource,
  1708. warn: getLogHandler(LOGLEVEL_WARN, 'PLUGIN_WARNING', onLog, plugin.name, logLevel)
  1709. };
  1710. }
  1711. // This will make sure no input hook is omitted
  1712. const inputHookNames = {
  1713. buildEnd: 1,
  1714. buildStart: 1,
  1715. closeBundle: 1,
  1716. closeWatcher: 1,
  1717. load: 1,
  1718. moduleParsed: 1,
  1719. onLog: 1,
  1720. options: 1,
  1721. resolveDynamicImport: 1,
  1722. resolveId: 1,
  1723. shouldTransformCachedModule: 1,
  1724. transform: 1,
  1725. watchChange: 1
  1726. };
  1727. const inputHooks = Object.keys(inputHookNames);
  1728. class PluginDriver {
  1729. constructor(graph, options, userPlugins, pluginCache, basePluginDriver) {
  1730. this.graph = graph;
  1731. this.options = options;
  1732. this.pluginCache = pluginCache;
  1733. this.sortedPlugins = new Map();
  1734. this.unfulfilledActions = new Set();
  1735. this.fileEmitter = new FileEmitter(graph, options, basePluginDriver && basePluginDriver.fileEmitter);
  1736. this.emitFile = this.fileEmitter.emitFile.bind(this.fileEmitter);
  1737. this.getFileName = this.fileEmitter.getFileName.bind(this.fileEmitter);
  1738. this.finaliseAssets = this.fileEmitter.finaliseAssets.bind(this.fileEmitter);
  1739. this.setChunkInformation = this.fileEmitter.setChunkInformation.bind(this.fileEmitter);
  1740. this.setOutputBundle = this.fileEmitter.setOutputBundle.bind(this.fileEmitter);
  1741. this.plugins = [...(basePluginDriver ? basePluginDriver.plugins : []), ...userPlugins];
  1742. const existingPluginNames = new Set();
  1743. this.pluginContexts = new Map(this.plugins.map(plugin => [
  1744. plugin,
  1745. getPluginContext(plugin, pluginCache, graph, options, this.fileEmitter, existingPluginNames)
  1746. ]));
  1747. if (basePluginDriver) {
  1748. for (const plugin of userPlugins) {
  1749. for (const hook of inputHooks) {
  1750. if (hook in plugin) {
  1751. options.onLog(LOGLEVEL_WARN, logInputHookInOutputPlugin(plugin.name, hook));
  1752. }
  1753. }
  1754. }
  1755. }
  1756. }
  1757. createOutputPluginDriver(plugins) {
  1758. return new PluginDriver(this.graph, this.options, plugins, this.pluginCache, this);
  1759. }
  1760. getUnfulfilledHookActions() {
  1761. return this.unfulfilledActions;
  1762. }
  1763. // chains, first non-null result stops and returns
  1764. hookFirst(hookName, parameters, replaceContext, skipped) {
  1765. return this.hookFirstAndGetPlugin(hookName, parameters, replaceContext, skipped).then(result => result && result[0]);
  1766. }
  1767. // chains, first non-null result stops and returns result and last plugin
  1768. async hookFirstAndGetPlugin(hookName, parameters, replaceContext, skipped) {
  1769. for (const plugin of this.getSortedPlugins(hookName)) {
  1770. if (skipped?.has(plugin))
  1771. continue;
  1772. const result = await this.runHook(hookName, parameters, plugin, replaceContext);
  1773. if (result != null)
  1774. return [result, plugin];
  1775. }
  1776. return null;
  1777. }
  1778. // chains synchronously, first non-null result stops and returns
  1779. hookFirstSync(hookName, parameters, replaceContext) {
  1780. for (const plugin of this.getSortedPlugins(hookName)) {
  1781. const result = this.runHookSync(hookName, parameters, plugin, replaceContext);
  1782. if (result != null)
  1783. return result;
  1784. }
  1785. return null;
  1786. }
  1787. // parallel, ignores returns
  1788. async hookParallel(hookName, parameters, replaceContext) {
  1789. const parallelPromises = [];
  1790. for (const plugin of this.getSortedPlugins(hookName)) {
  1791. if (plugin[hookName].sequential) {
  1792. await Promise.all(parallelPromises);
  1793. parallelPromises.length = 0;
  1794. await this.runHook(hookName, parameters, plugin, replaceContext);
  1795. }
  1796. else {
  1797. parallelPromises.push(this.runHook(hookName, parameters, plugin, replaceContext));
  1798. }
  1799. }
  1800. await Promise.all(parallelPromises);
  1801. }
  1802. // chains, reduces returned value, handling the reduced value as the first hook argument
  1803. hookReduceArg0(hookName, [argument0, ...rest], reduce, replaceContext) {
  1804. let promise = Promise.resolve(argument0);
  1805. for (const plugin of this.getSortedPlugins(hookName)) {
  1806. promise = promise.then(argument0 => this.runHook(hookName, [argument0, ...rest], plugin, replaceContext).then(result => reduce.call(this.pluginContexts.get(plugin), argument0, result, plugin)));
  1807. }
  1808. return promise;
  1809. }
  1810. // chains synchronously, reduces returned value, handling the reduced value as the first hook argument
  1811. hookReduceArg0Sync(hookName, [argument0, ...rest], reduce, replaceContext) {
  1812. for (const plugin of this.getSortedPlugins(hookName)) {
  1813. const parameters = [argument0, ...rest];
  1814. const result = this.runHookSync(hookName, parameters, plugin, replaceContext);
  1815. argument0 = reduce.call(this.pluginContexts.get(plugin), argument0, result, plugin);
  1816. }
  1817. return argument0;
  1818. }
  1819. // chains, reduces returned value to type string, handling the reduced value separately. permits hooks as values.
  1820. async hookReduceValue(hookName, initialValue, parameters, reducer) {
  1821. const results = [];
  1822. const parallelResults = [];
  1823. for (const plugin of this.getSortedPlugins(hookName, validateAddonPluginHandler)) {
  1824. if (plugin[hookName].sequential) {
  1825. results.push(...(await Promise.all(parallelResults)));
  1826. parallelResults.length = 0;
  1827. results.push(await this.runHook(hookName, parameters, plugin));
  1828. }
  1829. else {
  1830. parallelResults.push(this.runHook(hookName, parameters, plugin));
  1831. }
  1832. }
  1833. results.push(...(await Promise.all(parallelResults)));
  1834. return results.reduce(reducer, await initialValue);
  1835. }
  1836. // chains synchronously, reduces returned value to type T, handling the reduced value separately. permits hooks as values.
  1837. hookReduceValueSync(hookName, initialValue, parameters, reduce, replaceContext) {
  1838. let accumulator = initialValue;
  1839. for (const plugin of this.getSortedPlugins(hookName)) {
  1840. const result = this.runHookSync(hookName, parameters, plugin, replaceContext);
  1841. accumulator = reduce.call(this.pluginContexts.get(plugin), accumulator, result, plugin);
  1842. }
  1843. return accumulator;
  1844. }
  1845. // chains, ignores returns
  1846. hookSeq(hookName, parameters, replaceContext) {
  1847. let promise = Promise.resolve();
  1848. for (const plugin of this.getSortedPlugins(hookName)) {
  1849. promise = promise.then(() => this.runHook(hookName, parameters, plugin, replaceContext));
  1850. }
  1851. return promise.then(noReturn);
  1852. }
  1853. getSortedPlugins(hookName, validateHandler) {
  1854. return getOrCreate(this.sortedPlugins, hookName, () => getSortedValidatedPlugins(hookName, this.plugins, validateHandler));
  1855. }
  1856. // Implementation signature
  1857. runHook(hookName, parameters, plugin, replaceContext) {
  1858. // We always filter for plugins that support the hook before running it
  1859. const hook = plugin[hookName];
  1860. const handler = typeof hook === 'object' ? hook.handler : hook;
  1861. let context = this.pluginContexts.get(plugin);
  1862. if (replaceContext) {
  1863. context = replaceContext(context, plugin);
  1864. }
  1865. let action = null;
  1866. return Promise.resolve()
  1867. .then(() => {
  1868. if (typeof handler !== 'function') {
  1869. return handler;
  1870. }
  1871. // eslint-disable-next-line @typescript-eslint/ban-types
  1872. const hookResult = handler.apply(context, parameters);
  1873. if (!hookResult?.then) {
  1874. // short circuit for non-thenables and non-Promises
  1875. return hookResult;
  1876. }
  1877. // Track pending hook actions to properly error out when
  1878. // unfulfilled promises cause rollup to abruptly and confusingly
  1879. // exit with a successful 0 return code but without producing any
  1880. // output, errors or warnings.
  1881. action = [plugin.name, hookName, parameters];
  1882. this.unfulfilledActions.add(action);
  1883. // Although it would be more elegant to just return hookResult here
  1884. // and put the .then() handler just above the .catch() handler below,
  1885. // doing so would subtly change the defacto async event dispatch order
  1886. // which at least one test and some plugins in the wild may depend on.
  1887. return Promise.resolve(hookResult).then(result => {
  1888. // action was fulfilled
  1889. this.unfulfilledActions.delete(action);
  1890. return result;
  1891. });
  1892. })
  1893. .catch(error_ => {
  1894. if (action !== null) {
  1895. // action considered to be fulfilled since error being handled
  1896. this.unfulfilledActions.delete(action);
  1897. }
  1898. return error(logPluginError(error_, plugin.name, { hook: hookName }));
  1899. });
  1900. }
  1901. /**
  1902. * Run a sync plugin hook and return the result.
  1903. * @param hookName Name of the plugin hook. Must be in `PluginHooks`.
  1904. * @param args Arguments passed to the plugin hook.
  1905. * @param plugin The acutal plugin
  1906. * @param replaceContext When passed, the plugin context can be overridden.
  1907. */
  1908. runHookSync(hookName, parameters, plugin, replaceContext) {
  1909. const hook = plugin[hookName];
  1910. const handler = typeof hook === 'object' ? hook.handler : hook;
  1911. let context = this.pluginContexts.get(plugin);
  1912. if (replaceContext) {
  1913. context = replaceContext(context, plugin);
  1914. }
  1915. try {
  1916. // eslint-disable-next-line @typescript-eslint/ban-types
  1917. return handler.apply(context, parameters);
  1918. }
  1919. catch (error_) {
  1920. return error(logPluginError(error_, plugin.name, { hook: hookName }));
  1921. }
  1922. }
  1923. }
  1924. function getSortedValidatedPlugins(hookName, plugins, validateHandler = validateFunctionPluginHandler) {
  1925. const pre = [];
  1926. const normal = [];
  1927. const post = [];
  1928. for (const plugin of plugins) {
  1929. const hook = plugin[hookName];
  1930. if (hook) {
  1931. if (typeof hook === 'object') {
  1932. validateHandler(hook.handler, hookName, plugin);
  1933. if (hook.order === 'pre') {
  1934. pre.push(plugin);
  1935. continue;
  1936. }
  1937. if (hook.order === 'post') {
  1938. post.push(plugin);
  1939. continue;
  1940. }
  1941. }
  1942. else {
  1943. validateHandler(hook, hookName, plugin);
  1944. }
  1945. normal.push(plugin);
  1946. }
  1947. }
  1948. return [...pre, ...normal, ...post];
  1949. }
  1950. function validateFunctionPluginHandler(handler, hookName, plugin) {
  1951. if (typeof handler !== 'function') {
  1952. error(logInvalidFunctionPluginHook(hookName, plugin.name));
  1953. }
  1954. }
  1955. function validateAddonPluginHandler(handler, hookName, plugin) {
  1956. if (typeof handler !== 'string' && typeof handler !== 'function') {
  1957. return error(logInvalidAddonPluginHook(hookName, plugin.name));
  1958. }
  1959. }
  1960. function noReturn() { }
  1961. function getLogger(plugins, onLog, watchMode, logLevel) {
  1962. plugins = getSortedValidatedPlugins('onLog', plugins);
  1963. const minimalPriority = logLevelPriority[logLevel];
  1964. const logger = (level, log, skipped = EMPTY_SET) => {
  1965. const logPriority = logLevelPriority[level];
  1966. if (logPriority < minimalPriority) {
  1967. return;
  1968. }
  1969. for (const plugin of plugins) {
  1970. if (skipped.has(plugin))
  1971. continue;
  1972. const { onLog: pluginOnLog } = plugin;
  1973. const getLogHandler = (level) => {
  1974. if (logLevelPriority[level] < minimalPriority) {
  1975. return doNothing;
  1976. }
  1977. return log => logger(level, normalizeLog(log), new Set(skipped).add(plugin));
  1978. };
  1979. const handler = 'handler' in pluginOnLog ? pluginOnLog.handler : pluginOnLog;
  1980. if (handler.call({
  1981. debug: getLogHandler(LOGLEVEL_DEBUG),
  1982. error: (log) => error(normalizeLog(log)),
  1983. info: getLogHandler(LOGLEVEL_INFO),
  1984. meta: { rollupVersion: version$1, watchMode },
  1985. warn: getLogHandler(LOGLEVEL_WARN)
  1986. }, level, log) === false) {
  1987. return;
  1988. }
  1989. }
  1990. onLog(level, log);
  1991. };
  1992. return logger;
  1993. }
  1994. const commandAliases = {
  1995. c: 'config',
  1996. d: 'dir',
  1997. e: 'external',
  1998. f: 'format',
  1999. g: 'globals',
  2000. h: 'help',
  2001. i: 'input',
  2002. m: 'sourcemap',
  2003. n: 'name',
  2004. o: 'file',
  2005. p: 'plugin',
  2006. v: 'version',
  2007. w: 'watch'
  2008. };
  2009. const EMPTY_COMMAND_OPTIONS = { external: [], globals: undefined };
  2010. async function mergeOptions(config, watchMode, rawCommandOptions = EMPTY_COMMAND_OPTIONS, printLog) {
  2011. const command = getCommandOptions(rawCommandOptions);
  2012. const plugins = await normalizePluginOption(config.plugins);
  2013. const logLevel = config.logLevel || LOGLEVEL_INFO;
  2014. const onLog = getOnLog(config, logLevel, printLog);
  2015. const log = getLogger(plugins, onLog, watchMode, logLevel);
  2016. const inputOptions = await mergeInputOptions(config, command, plugins, log, onLog);
  2017. if (command.output) {
  2018. Object.assign(command, command.output);
  2019. }
  2020. const outputOptionsArray = ensureArray$1(config.output);
  2021. if (outputOptionsArray.length === 0)
  2022. outputOptionsArray.push({});
  2023. const outputOptions = await Promise.all(outputOptionsArray.map(singleOutputOptions => mergeOutputOptions(singleOutputOptions, command, log)));
  2024. warnUnknownOptions(command, [
  2025. ...Object.keys(inputOptions),
  2026. ...Object.keys(outputOptions[0]).filter(option => option !== 'sourcemapIgnoreList' && option !== 'sourcemapPathTransform'),
  2027. ...Object.keys(commandAliases),
  2028. 'bundleConfigAsCjs',
  2029. 'config',
  2030. 'environment',
  2031. 'filterLogs',
  2032. 'plugin',
  2033. 'silent',
  2034. 'failAfterWarnings',
  2035. 'stdin',
  2036. 'waitForBundleInput',
  2037. 'configPlugin'
  2038. ], 'CLI flags', log, /^_$|output$|config/);
  2039. inputOptions.output = outputOptions;
  2040. return inputOptions;
  2041. }
  2042. function getCommandOptions(rawCommandOptions) {
  2043. const external = rawCommandOptions.external && typeof rawCommandOptions.external === 'string'
  2044. ? rawCommandOptions.external.split(',')
  2045. : [];
  2046. return {
  2047. ...rawCommandOptions,
  2048. external,
  2049. globals: typeof rawCommandOptions.globals === 'string'
  2050. ? rawCommandOptions.globals.split(',').reduce((globals, globalDefinition) => {
  2051. const [id, variableName] = globalDefinition.split(':');
  2052. globals[id] = variableName;
  2053. if (!external.includes(id)) {
  2054. external.push(id);
  2055. }
  2056. return globals;
  2057. }, Object.create(null))
  2058. : undefined
  2059. };
  2060. }
  2061. function mergeInputOptions(config, overrides, plugins, log, onLog) {
  2062. const getOption = (name) => overrides[name] ?? config[name];
  2063. const inputOptions = {
  2064. acorn: getOption('acorn'),
  2065. acornInjectPlugins: config.acornInjectPlugins,
  2066. cache: config.cache,
  2067. context: getOption('context'),
  2068. experimentalCacheExpiry: getOption('experimentalCacheExpiry'),
  2069. experimentalLogSideEffects: getOption('experimentalLogSideEffects'),
  2070. external: getExternal(config, overrides),
  2071. inlineDynamicImports: getOption('inlineDynamicImports'),
  2072. input: getOption('input') || [],
  2073. logLevel: getOption('logLevel'),
  2074. makeAbsoluteExternalsRelative: getOption('makeAbsoluteExternalsRelative'),
  2075. manualChunks: getOption('manualChunks'),
  2076. maxParallelFileOps: getOption('maxParallelFileOps'),
  2077. maxParallelFileReads: getOption('maxParallelFileReads'),
  2078. moduleContext: getOption('moduleContext'),
  2079. onLog,
  2080. onwarn: undefined,
  2081. perf: getOption('perf'),
  2082. plugins,
  2083. preserveEntrySignatures: getOption('preserveEntrySignatures'),
  2084. preserveModules: getOption('preserveModules'),
  2085. preserveSymlinks: getOption('preserveSymlinks'),
  2086. shimMissingExports: getOption('shimMissingExports'),
  2087. strictDeprecations: getOption('strictDeprecations'),
  2088. treeshake: getObjectOption(config, overrides, 'treeshake', objectifyOptionWithPresets(treeshakePresets, 'treeshake', URL_TREESHAKE, 'false, true, ')),
  2089. watch: getWatch(config, overrides)
  2090. };
  2091. warnUnknownOptions(config, Object.keys(inputOptions), 'input options', log, /^output$/);
  2092. return inputOptions;
  2093. }
  2094. const getExternal = (config, overrides) => {
  2095. const configExternal = config.external;
  2096. return typeof configExternal === 'function'
  2097. ? (source, importer, isResolved) => configExternal(source, importer, isResolved) || overrides.external.includes(source)
  2098. : [...ensureArray$1(configExternal), ...overrides.external];
  2099. };
  2100. const getObjectOption = (config, overrides, name, objectifyValue = objectifyOption) => {
  2101. const commandOption = normalizeObjectOptionValue(overrides[name], objectifyValue);
  2102. const configOption = normalizeObjectOptionValue(config[name], objectifyValue);
  2103. if (commandOption !== undefined) {
  2104. return commandOption && { ...configOption, ...commandOption };
  2105. }
  2106. return configOption;
  2107. };
  2108. const getWatch = (config, overrides) => config.watch !== false && getObjectOption(config, overrides, 'watch');
  2109. const isWatchEnabled = (optionValue) => {
  2110. if (Array.isArray(optionValue)) {
  2111. return optionValue.reduce((result, value) => (typeof value === 'boolean' ? value : result), false);
  2112. }
  2113. return optionValue === true;
  2114. };
  2115. const normalizeObjectOptionValue = (optionValue, objectifyValue) => {
  2116. if (!optionValue) {
  2117. return optionValue;
  2118. }
  2119. if (Array.isArray(optionValue)) {
  2120. return optionValue.reduce((result, value) => value && result && { ...result, ...objectifyValue(value) }, {});
  2121. }
  2122. return objectifyValue(optionValue);
  2123. };
  2124. async function mergeOutputOptions(config, overrides, log) {
  2125. const getOption = (name) => overrides[name] ?? config[name];
  2126. const outputOptions = {
  2127. amd: getObjectOption(config, overrides, 'amd'),
  2128. assetFileNames: getOption('assetFileNames'),
  2129. banner: getOption('banner'),
  2130. chunkFileNames: getOption('chunkFileNames'),
  2131. compact: getOption('compact'),
  2132. dir: getOption('dir'),
  2133. dynamicImportFunction: getOption('dynamicImportFunction'),
  2134. dynamicImportInCjs: getOption('dynamicImportInCjs'),
  2135. entryFileNames: getOption('entryFileNames'),
  2136. esModule: getOption('esModule'),
  2137. experimentalDeepDynamicChunkOptimization: getOption('experimentalDeepDynamicChunkOptimization'),
  2138. experimentalMinChunkSize: getOption('experimentalMinChunkSize'),
  2139. exports: getOption('exports'),
  2140. extend: getOption('extend'),
  2141. externalImportAssertions: getOption('externalImportAssertions'),
  2142. externalLiveBindings: getOption('externalLiveBindings'),
  2143. file: getOption('file'),
  2144. footer: getOption('footer'),
  2145. format: getOption('format'),
  2146. freeze: getOption('freeze'),
  2147. generatedCode: getObjectOption(config, overrides, 'generatedCode', objectifyOptionWithPresets(generatedCodePresets, 'output.generatedCode', URL_OUTPUT_GENERATEDCODE, '')),
  2148. globals: getOption('globals'),
  2149. hoistTransitiveImports: getOption('hoistTransitiveImports'),
  2150. indent: getOption('indent'),
  2151. inlineDynamicImports: getOption('inlineDynamicImports'),
  2152. interop: getOption('interop'),
  2153. intro: getOption('intro'),
  2154. manualChunks: getOption('manualChunks'),
  2155. minifyInternalExports: getOption('minifyInternalExports'),
  2156. name: getOption('name'),
  2157. namespaceToStringTag: getOption('namespaceToStringTag'),
  2158. noConflict: getOption('noConflict'),
  2159. outro: getOption('outro'),
  2160. paths: getOption('paths'),
  2161. plugins: await normalizePluginOption(config.plugins),
  2162. preferConst: getOption('preferConst'),
  2163. preserveModules: getOption('preserveModules'),
  2164. preserveModulesRoot: getOption('preserveModulesRoot'),
  2165. sanitizeFileName: getOption('sanitizeFileName'),
  2166. sourcemap: getOption('sourcemap'),
  2167. sourcemapBaseUrl: getOption('sourcemapBaseUrl'),
  2168. sourcemapExcludeSources: getOption('sourcemapExcludeSources'),
  2169. sourcemapFile: getOption('sourcemapFile'),
  2170. sourcemapFileNames: getOption('sourcemapFileNames'),
  2171. sourcemapIgnoreList: getOption('sourcemapIgnoreList'),
  2172. sourcemapPathTransform: getOption('sourcemapPathTransform'),
  2173. strict: getOption('strict'),
  2174. systemNullSetters: getOption('systemNullSetters'),
  2175. validate: getOption('validate')
  2176. };
  2177. warnUnknownOptions(config, Object.keys(outputOptions), 'output options', log);
  2178. return outputOptions;
  2179. }
  2180. const {
  2181. env = {},
  2182. argv = [],
  2183. platform = "",
  2184. } = typeof process === "undefined" ? {} : process;
  2185. const isDisabled = "NO_COLOR" in env || argv.includes("--no-color");
  2186. const isForced = "FORCE_COLOR" in env || argv.includes("--color");
  2187. const isWindows = platform === "win32";
  2188. const isDumbTerminal = env.TERM === "dumb";
  2189. const isCompatibleTerminal =
  2190. tty__namespace && tty__namespace.isatty && tty__namespace.isatty(1) && env.TERM && !isDumbTerminal;
  2191. const isCI =
  2192. "CI" in env &&
  2193. ("GITHUB_ACTIONS" in env || "GITLAB_CI" in env || "CIRCLECI" in env);
  2194. const isColorSupported =
  2195. !isDisabled &&
  2196. (isForced || (isWindows && !isDumbTerminal) || isCompatibleTerminal || isCI);
  2197. const replaceClose = (
  2198. index,
  2199. string,
  2200. close,
  2201. replace,
  2202. head = string.substring(0, index) + replace,
  2203. tail = string.substring(index + close.length),
  2204. next = tail.indexOf(close)
  2205. ) => head + (next < 0 ? tail : replaceClose(next, tail, close, replace));
  2206. const clearBleed = (index, string, open, close, replace) =>
  2207. index < 0
  2208. ? open + string + close
  2209. : open + replaceClose(index, string, close, replace) + close;
  2210. const filterEmpty =
  2211. (open, close, replace = open, at = open.length + 1) =>
  2212. (string) =>
  2213. string || !(string === "" || string === undefined)
  2214. ? clearBleed(
  2215. ("" + string).indexOf(close, at),
  2216. string,
  2217. open,
  2218. close,
  2219. replace
  2220. )
  2221. : "";
  2222. const init = (open, close, replace) =>
  2223. filterEmpty(`\x1b[${open}m`, `\x1b[${close}m`, replace);
  2224. const colors = {
  2225. reset: init(0, 0),
  2226. bold: init(1, 22, "\x1b[22m\x1b[1m"),
  2227. dim: init(2, 22, "\x1b[22m\x1b[2m"),
  2228. italic: init(3, 23),
  2229. underline: init(4, 24),
  2230. inverse: init(7, 27),
  2231. hidden: init(8, 28),
  2232. strikethrough: init(9, 29),
  2233. black: init(30, 39),
  2234. red: init(31, 39),
  2235. green: init(32, 39),
  2236. yellow: init(33, 39),
  2237. blue: init(34, 39),
  2238. magenta: init(35, 39),
  2239. cyan: init(36, 39),
  2240. white: init(37, 39),
  2241. gray: init(90, 39),
  2242. bgBlack: init(40, 49),
  2243. bgRed: init(41, 49),
  2244. bgGreen: init(42, 49),
  2245. bgYellow: init(43, 49),
  2246. bgBlue: init(44, 49),
  2247. bgMagenta: init(45, 49),
  2248. bgCyan: init(46, 49),
  2249. bgWhite: init(47, 49),
  2250. blackBright: init(90, 39),
  2251. redBright: init(91, 39),
  2252. greenBright: init(92, 39),
  2253. yellowBright: init(93, 39),
  2254. blueBright: init(94, 39),
  2255. magentaBright: init(95, 39),
  2256. cyanBright: init(96, 39),
  2257. whiteBright: init(97, 39),
  2258. bgBlackBright: init(100, 49),
  2259. bgRedBright: init(101, 49),
  2260. bgGreenBright: init(102, 49),
  2261. bgYellowBright: init(103, 49),
  2262. bgBlueBright: init(104, 49),
  2263. bgMagentaBright: init(105, 49),
  2264. bgCyanBright: init(106, 49),
  2265. bgWhiteBright: init(107, 49),
  2266. };
  2267. const createColors = ({ useColor = isColorSupported } = {}) =>
  2268. useColor
  2269. ? colors
  2270. : Object.keys(colors).reduce(
  2271. (colors, key) => ({ ...colors, [key]: String }),
  2272. {}
  2273. );
  2274. const {
  2275. reset,
  2276. bold: bold$1,
  2277. dim: dim$1,
  2278. italic,
  2279. underline: underline$1,
  2280. inverse,
  2281. hidden,
  2282. strikethrough,
  2283. black,
  2284. red: red$1,
  2285. green: green$1,
  2286. yellow: yellow$1,
  2287. blue,
  2288. magenta,
  2289. cyan: cyan$1,
  2290. white,
  2291. gray: gray$1,
  2292. bgBlack,
  2293. bgRed,
  2294. bgGreen,
  2295. bgYellow,
  2296. bgBlue,
  2297. bgMagenta,
  2298. bgCyan,
  2299. bgWhite,
  2300. blackBright,
  2301. redBright,
  2302. greenBright,
  2303. yellowBright,
  2304. blueBright,
  2305. magentaBright,
  2306. cyanBright,
  2307. whiteBright,
  2308. bgBlackBright,
  2309. bgRedBright,
  2310. bgGreenBright,
  2311. bgYellowBright,
  2312. bgBlueBright,
  2313. bgMagentaBright,
  2314. bgCyanBright,
  2315. bgWhiteBright,
  2316. } = createColors();
  2317. // @see https://no-color.org
  2318. // @see https://www.npmjs.com/package/chalk
  2319. const { bold, cyan, dim, gray, green, red, underline, yellow } = createColors({
  2320. useColor: process$1.env.FORCE_COLOR !== '0' && !process$1.env.NO_COLOR
  2321. });
  2322. // log to stderr to keep `rollup main.js > bundle.js` from breaking
  2323. const stderr = (...parameters) => process$1.stderr.write(`${parameters.join('')}\n`);
  2324. function handleError(error, recover = false) {
  2325. const name = error.name || error.cause?.name;
  2326. const nameSection = name ? `${name}: ` : '';
  2327. const pluginSection = error.plugin ? `(plugin ${error.plugin}) ` : '';
  2328. const message = `${pluginSection}${nameSection}${error.message}`;
  2329. const outputLines = [bold(red(`[!] ${bold(message.toString())}`))];
  2330. if (error.url) {
  2331. outputLines.push(cyan(error.url));
  2332. }
  2333. if (error.loc) {
  2334. outputLines.push(`${relativeId((error.loc.file || error.id))} (${error.loc.line}:${error.loc.column})`);
  2335. }
  2336. else if (error.id) {
  2337. outputLines.push(relativeId(error.id));
  2338. }
  2339. if (error.frame) {
  2340. outputLines.push(dim(error.frame));
  2341. }
  2342. if (error.stack) {
  2343. outputLines.push(dim(error.stack?.replace(`${nameSection}${error.message}\n`, '')));
  2344. }
  2345. outputLines.push('', '');
  2346. stderr(outputLines.join('\n'));
  2347. if (!recover)
  2348. process$1.exit(1);
  2349. }
  2350. const comma = ','.charCodeAt(0);
  2351. const semicolon = ';'.charCodeAt(0);
  2352. const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  2353. const intToChar = new Uint8Array(64); // 64 possible chars.
  2354. const charToInt = new Uint8Array(128); // z is 122 in ASCII
  2355. for (let i = 0; i < chars.length; i++) {
  2356. const c = chars.charCodeAt(i);
  2357. intToChar[i] = c;
  2358. charToInt[c] = i;
  2359. }
  2360. // Provide a fallback for older environments.
  2361. const td = typeof TextDecoder !== 'undefined'
  2362. ? /* #__PURE__ */ new TextDecoder()
  2363. : typeof Buffer !== 'undefined'
  2364. ? {
  2365. decode(buf) {
  2366. const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
  2367. return out.toString();
  2368. },
  2369. }
  2370. : {
  2371. decode(buf) {
  2372. let out = '';
  2373. for (let i = 0; i < buf.length; i++) {
  2374. out += String.fromCharCode(buf[i]);
  2375. }
  2376. return out;
  2377. },
  2378. };
  2379. function decode(mappings) {
  2380. const state = new Int32Array(5);
  2381. const decoded = [];
  2382. let index = 0;
  2383. do {
  2384. const semi = indexOf(mappings, index);
  2385. const line = [];
  2386. let sorted = true;
  2387. let lastCol = 0;
  2388. state[0] = 0;
  2389. for (let i = index; i < semi; i++) {
  2390. let seg;
  2391. i = decodeInteger(mappings, i, state, 0); // genColumn
  2392. const col = state[0];
  2393. if (col < lastCol)
  2394. sorted = false;
  2395. lastCol = col;
  2396. if (hasMoreVlq(mappings, i, semi)) {
  2397. i = decodeInteger(mappings, i, state, 1); // sourcesIndex
  2398. i = decodeInteger(mappings, i, state, 2); // sourceLine
  2399. i = decodeInteger(mappings, i, state, 3); // sourceColumn
  2400. if (hasMoreVlq(mappings, i, semi)) {
  2401. i = decodeInteger(mappings, i, state, 4); // namesIndex
  2402. seg = [col, state[1], state[2], state[3], state[4]];
  2403. }
  2404. else {
  2405. seg = [col, state[1], state[2], state[3]];
  2406. }
  2407. }
  2408. else {
  2409. seg = [col];
  2410. }
  2411. line.push(seg);
  2412. }
  2413. if (!sorted)
  2414. sort(line);
  2415. decoded.push(line);
  2416. index = semi + 1;
  2417. } while (index <= mappings.length);
  2418. return decoded;
  2419. }
  2420. function indexOf(mappings, index) {
  2421. const idx = mappings.indexOf(';', index);
  2422. return idx === -1 ? mappings.length : idx;
  2423. }
  2424. function decodeInteger(mappings, pos, state, j) {
  2425. let value = 0;
  2426. let shift = 0;
  2427. let integer = 0;
  2428. do {
  2429. const c = mappings.charCodeAt(pos++);
  2430. integer = charToInt[c];
  2431. value |= (integer & 31) << shift;
  2432. shift += 5;
  2433. } while (integer & 32);
  2434. const shouldNegate = value & 1;
  2435. value >>>= 1;
  2436. if (shouldNegate) {
  2437. value = -0x80000000 | -value;
  2438. }
  2439. state[j] += value;
  2440. return pos;
  2441. }
  2442. function hasMoreVlq(mappings, i, length) {
  2443. if (i >= length)
  2444. return false;
  2445. return mappings.charCodeAt(i) !== comma;
  2446. }
  2447. function sort(line) {
  2448. line.sort(sortComparator);
  2449. }
  2450. function sortComparator(a, b) {
  2451. return a[0] - b[0];
  2452. }
  2453. function encode(decoded) {
  2454. const state = new Int32Array(5);
  2455. const bufLength = 1024 * 16;
  2456. const subLength = bufLength - 36;
  2457. const buf = new Uint8Array(bufLength);
  2458. const sub = buf.subarray(0, subLength);
  2459. let pos = 0;
  2460. let out = '';
  2461. for (let i = 0; i < decoded.length; i++) {
  2462. const line = decoded[i];
  2463. if (i > 0) {
  2464. if (pos === bufLength) {
  2465. out += td.decode(buf);
  2466. pos = 0;
  2467. }
  2468. buf[pos++] = semicolon;
  2469. }
  2470. if (line.length === 0)
  2471. continue;
  2472. state[0] = 0;
  2473. for (let j = 0; j < line.length; j++) {
  2474. const segment = line[j];
  2475. // We can push up to 5 ints, each int can take at most 7 chars, and we
  2476. // may push a comma.
  2477. if (pos > subLength) {
  2478. out += td.decode(sub);
  2479. buf.copyWithin(0, subLength, pos);
  2480. pos -= subLength;
  2481. }
  2482. if (j > 0)
  2483. buf[pos++] = comma;
  2484. pos = encodeInteger(buf, pos, state, segment, 0); // genColumn
  2485. if (segment.length === 1)
  2486. continue;
  2487. pos = encodeInteger(buf, pos, state, segment, 1); // sourcesIndex
  2488. pos = encodeInteger(buf, pos, state, segment, 2); // sourceLine
  2489. pos = encodeInteger(buf, pos, state, segment, 3); // sourceColumn
  2490. if (segment.length === 4)
  2491. continue;
  2492. pos = encodeInteger(buf, pos, state, segment, 4); // namesIndex
  2493. }
  2494. }
  2495. return out + td.decode(buf.subarray(0, pos));
  2496. }
  2497. function encodeInteger(buf, pos, state, segment, j) {
  2498. const next = segment[j];
  2499. let num = next - state[j];
  2500. state[j] = next;
  2501. num = num < 0 ? (-num << 1) | 1 : num << 1;
  2502. do {
  2503. let clamped = num & 0b011111;
  2504. num >>>= 5;
  2505. if (num > 0)
  2506. clamped |= 0b100000;
  2507. buf[pos++] = intToChar[clamped];
  2508. } while (num > 0);
  2509. return pos;
  2510. }
  2511. class BitSet {
  2512. constructor(arg) {
  2513. this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
  2514. }
  2515. add(n) {
  2516. this.bits[n >> 5] |= 1 << (n & 31);
  2517. }
  2518. has(n) {
  2519. return !!(this.bits[n >> 5] & (1 << (n & 31)));
  2520. }
  2521. }
  2522. let Chunk$1 = class Chunk {
  2523. constructor(start, end, content) {
  2524. this.start = start;
  2525. this.end = end;
  2526. this.original = content;
  2527. this.intro = '';
  2528. this.outro = '';
  2529. this.content = content;
  2530. this.storeName = false;
  2531. this.edited = false;
  2532. {
  2533. this.previous = null;
  2534. this.next = null;
  2535. }
  2536. }
  2537. appendLeft(content) {
  2538. this.outro += content;
  2539. }
  2540. appendRight(content) {
  2541. this.intro = this.intro + content;
  2542. }
  2543. clone() {
  2544. const chunk = new Chunk(this.start, this.end, this.original);
  2545. chunk.intro = this.intro;
  2546. chunk.outro = this.outro;
  2547. chunk.content = this.content;
  2548. chunk.storeName = this.storeName;
  2549. chunk.edited = this.edited;
  2550. return chunk;
  2551. }
  2552. contains(index) {
  2553. return this.start < index && index < this.end;
  2554. }
  2555. eachNext(fn) {
  2556. let chunk = this;
  2557. while (chunk) {
  2558. fn(chunk);
  2559. chunk = chunk.next;
  2560. }
  2561. }
  2562. eachPrevious(fn) {
  2563. let chunk = this;
  2564. while (chunk) {
  2565. fn(chunk);
  2566. chunk = chunk.previous;
  2567. }
  2568. }
  2569. edit(content, storeName, contentOnly) {
  2570. this.content = content;
  2571. if (!contentOnly) {
  2572. this.intro = '';
  2573. this.outro = '';
  2574. }
  2575. this.storeName = storeName;
  2576. this.edited = true;
  2577. return this;
  2578. }
  2579. prependLeft(content) {
  2580. this.outro = content + this.outro;
  2581. }
  2582. prependRight(content) {
  2583. this.intro = content + this.intro;
  2584. }
  2585. split(index) {
  2586. const sliceIndex = index - this.start;
  2587. const originalBefore = this.original.slice(0, sliceIndex);
  2588. const originalAfter = this.original.slice(sliceIndex);
  2589. this.original = originalBefore;
  2590. const newChunk = new Chunk(index, this.end, originalAfter);
  2591. newChunk.outro = this.outro;
  2592. this.outro = '';
  2593. this.end = index;
  2594. if (this.edited) {
  2595. // after split we should save the edit content record into the correct chunk
  2596. // to make sure sourcemap correct
  2597. // For example:
  2598. // ' test'.trim()
  2599. // split -> ' ' + 'test'
  2600. // ✔️ edit -> '' + 'test'
  2601. // ✖️ edit -> 'test' + ''
  2602. // TODO is this block necessary?...
  2603. newChunk.edit('', false);
  2604. this.content = '';
  2605. } else {
  2606. this.content = originalBefore;
  2607. }
  2608. newChunk.next = this.next;
  2609. if (newChunk.next) newChunk.next.previous = newChunk;
  2610. newChunk.previous = this;
  2611. this.next = newChunk;
  2612. return newChunk;
  2613. }
  2614. toString() {
  2615. return this.intro + this.content + this.outro;
  2616. }
  2617. trimEnd(rx) {
  2618. this.outro = this.outro.replace(rx, '');
  2619. if (this.outro.length) return true;
  2620. const trimmed = this.content.replace(rx, '');
  2621. if (trimmed.length) {
  2622. if (trimmed !== this.content) {
  2623. this.split(this.start + trimmed.length).edit('', undefined, true);
  2624. if (this.edited) {
  2625. // save the change, if it has been edited
  2626. this.edit(trimmed, this.storeName, true);
  2627. }
  2628. }
  2629. return true;
  2630. } else {
  2631. this.edit('', undefined, true);
  2632. this.intro = this.intro.replace(rx, '');
  2633. if (this.intro.length) return true;
  2634. }
  2635. }
  2636. trimStart(rx) {
  2637. this.intro = this.intro.replace(rx, '');
  2638. if (this.intro.length) return true;
  2639. const trimmed = this.content.replace(rx, '');
  2640. if (trimmed.length) {
  2641. if (trimmed !== this.content) {
  2642. const newChunk = this.split(this.end - trimmed.length);
  2643. if (this.edited) {
  2644. // save the change, if it has been edited
  2645. newChunk.edit(trimmed, this.storeName, true);
  2646. }
  2647. this.edit('', undefined, true);
  2648. }
  2649. return true;
  2650. } else {
  2651. this.edit('', undefined, true);
  2652. this.outro = this.outro.replace(rx, '');
  2653. if (this.outro.length) return true;
  2654. }
  2655. }
  2656. };
  2657. function getBtoa() {
  2658. if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
  2659. return (str) => window.btoa(unescape(encodeURIComponent(str)));
  2660. } else if (typeof Buffer === 'function') {
  2661. return (str) => Buffer.from(str, 'utf-8').toString('base64');
  2662. } else {
  2663. return () => {
  2664. throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
  2665. };
  2666. }
  2667. }
  2668. const btoa = /*#__PURE__*/ getBtoa();
  2669. class SourceMap {
  2670. constructor(properties) {
  2671. this.version = 3;
  2672. this.file = properties.file;
  2673. this.sources = properties.sources;
  2674. this.sourcesContent = properties.sourcesContent;
  2675. this.names = properties.names;
  2676. this.mappings = encode(properties.mappings);
  2677. if (typeof properties.x_google_ignoreList !== 'undefined') {
  2678. this.x_google_ignoreList = properties.x_google_ignoreList;
  2679. }
  2680. }
  2681. toString() {
  2682. return JSON.stringify(this);
  2683. }
  2684. toUrl() {
  2685. return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
  2686. }
  2687. }
  2688. function guessIndent(code) {
  2689. const lines = code.split('\n');
  2690. const tabbed = lines.filter((line) => /^\t+/.test(line));
  2691. const spaced = lines.filter((line) => /^ {2,}/.test(line));
  2692. if (tabbed.length === 0 && spaced.length === 0) {
  2693. return null;
  2694. }
  2695. // More lines tabbed than spaced? Assume tabs, and
  2696. // default to tabs in the case of a tie (or nothing
  2697. // to go on)
  2698. if (tabbed.length >= spaced.length) {
  2699. return '\t';
  2700. }
  2701. // Otherwise, we need to guess the multiple
  2702. const min = spaced.reduce((previous, current) => {
  2703. const numSpaces = /^ +/.exec(current)[0].length;
  2704. return Math.min(numSpaces, previous);
  2705. }, Infinity);
  2706. return new Array(min + 1).join(' ');
  2707. }
  2708. function getRelativePath(from, to) {
  2709. const fromParts = from.split(/[/\\]/);
  2710. const toParts = to.split(/[/\\]/);
  2711. fromParts.pop(); // get dirname
  2712. while (fromParts[0] === toParts[0]) {
  2713. fromParts.shift();
  2714. toParts.shift();
  2715. }
  2716. if (fromParts.length) {
  2717. let i = fromParts.length;
  2718. while (i--) fromParts[i] = '..';
  2719. }
  2720. return fromParts.concat(toParts).join('/');
  2721. }
  2722. const toString$1 = Object.prototype.toString;
  2723. function isObject$1(thing) {
  2724. return toString$1.call(thing) === '[object Object]';
  2725. }
  2726. function getLocator(source) {
  2727. const originalLines = source.split('\n');
  2728. const lineOffsets = [];
  2729. for (let i = 0, pos = 0; i < originalLines.length; i++) {
  2730. lineOffsets.push(pos);
  2731. pos += originalLines[i].length + 1;
  2732. }
  2733. return function locate(index) {
  2734. let i = 0;
  2735. let j = lineOffsets.length;
  2736. while (i < j) {
  2737. const m = (i + j) >> 1;
  2738. if (index < lineOffsets[m]) {
  2739. j = m;
  2740. } else {
  2741. i = m + 1;
  2742. }
  2743. }
  2744. const line = i - 1;
  2745. const column = index - lineOffsets[line];
  2746. return { line, column };
  2747. };
  2748. }
  2749. const wordRegex = /\w/;
  2750. class Mappings {
  2751. constructor(hires) {
  2752. this.hires = hires;
  2753. this.generatedCodeLine = 0;
  2754. this.generatedCodeColumn = 0;
  2755. this.raw = [];
  2756. this.rawSegments = this.raw[this.generatedCodeLine] = [];
  2757. this.pending = null;
  2758. }
  2759. addEdit(sourceIndex, content, loc, nameIndex) {
  2760. if (content.length) {
  2761. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  2762. if (nameIndex >= 0) {
  2763. segment.push(nameIndex);
  2764. }
  2765. this.rawSegments.push(segment);
  2766. } else if (this.pending) {
  2767. this.rawSegments.push(this.pending);
  2768. }
  2769. this.advance(content);
  2770. this.pending = null;
  2771. }
  2772. addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
  2773. let originalCharIndex = chunk.start;
  2774. let first = true;
  2775. // when iterating each char, check if it's in a word boundary
  2776. let charInHiresBoundary = false;
  2777. while (originalCharIndex < chunk.end) {
  2778. if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
  2779. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  2780. if (this.hires === 'boundary') {
  2781. // in hires "boundary", group segments per word boundary than per char
  2782. if (wordRegex.test(original[originalCharIndex])) {
  2783. // for first char in the boundary found, start the boundary by pushing a segment
  2784. if (!charInHiresBoundary) {
  2785. this.rawSegments.push(segment);
  2786. charInHiresBoundary = true;
  2787. }
  2788. } else {
  2789. // for non-word char, end the boundary by pushing a segment
  2790. this.rawSegments.push(segment);
  2791. charInHiresBoundary = false;
  2792. }
  2793. } else {
  2794. this.rawSegments.push(segment);
  2795. }
  2796. }
  2797. if (original[originalCharIndex] === '\n') {
  2798. loc.line += 1;
  2799. loc.column = 0;
  2800. this.generatedCodeLine += 1;
  2801. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  2802. this.generatedCodeColumn = 0;
  2803. first = true;
  2804. } else {
  2805. loc.column += 1;
  2806. this.generatedCodeColumn += 1;
  2807. first = false;
  2808. }
  2809. originalCharIndex += 1;
  2810. }
  2811. this.pending = null;
  2812. }
  2813. advance(str) {
  2814. if (!str) return;
  2815. const lines = str.split('\n');
  2816. if (lines.length > 1) {
  2817. for (let i = 0; i < lines.length - 1; i++) {
  2818. this.generatedCodeLine++;
  2819. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  2820. }
  2821. this.generatedCodeColumn = 0;
  2822. }
  2823. this.generatedCodeColumn += lines[lines.length - 1].length;
  2824. }
  2825. }
  2826. const n = '\n';
  2827. const warned = {
  2828. insertLeft: false,
  2829. insertRight: false,
  2830. storeName: false,
  2831. };
  2832. class MagicString {
  2833. constructor(string, options = {}) {
  2834. const chunk = new Chunk$1(0, string.length, string);
  2835. Object.defineProperties(this, {
  2836. original: { writable: true, value: string },
  2837. outro: { writable: true, value: '' },
  2838. intro: { writable: true, value: '' },
  2839. firstChunk: { writable: true, value: chunk },
  2840. lastChunk: { writable: true, value: chunk },
  2841. lastSearchedChunk: { writable: true, value: chunk },
  2842. byStart: { writable: true, value: {} },
  2843. byEnd: { writable: true, value: {} },
  2844. filename: { writable: true, value: options.filename },
  2845. indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
  2846. sourcemapLocations: { writable: true, value: new BitSet() },
  2847. storedNames: { writable: true, value: {} },
  2848. indentStr: { writable: true, value: undefined },
  2849. ignoreList: { writable: true, value: options.ignoreList },
  2850. });
  2851. this.byStart[0] = chunk;
  2852. this.byEnd[string.length] = chunk;
  2853. }
  2854. addSourcemapLocation(char) {
  2855. this.sourcemapLocations.add(char);
  2856. }
  2857. append(content) {
  2858. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  2859. this.outro += content;
  2860. return this;
  2861. }
  2862. appendLeft(index, content) {
  2863. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  2864. this._split(index);
  2865. const chunk = this.byEnd[index];
  2866. if (chunk) {
  2867. chunk.appendLeft(content);
  2868. } else {
  2869. this.intro += content;
  2870. }
  2871. return this;
  2872. }
  2873. appendRight(index, content) {
  2874. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  2875. this._split(index);
  2876. const chunk = this.byStart[index];
  2877. if (chunk) {
  2878. chunk.appendRight(content);
  2879. } else {
  2880. this.outro += content;
  2881. }
  2882. return this;
  2883. }
  2884. clone() {
  2885. const cloned = new MagicString(this.original, { filename: this.filename });
  2886. let originalChunk = this.firstChunk;
  2887. let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
  2888. while (originalChunk) {
  2889. cloned.byStart[clonedChunk.start] = clonedChunk;
  2890. cloned.byEnd[clonedChunk.end] = clonedChunk;
  2891. const nextOriginalChunk = originalChunk.next;
  2892. const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
  2893. if (nextClonedChunk) {
  2894. clonedChunk.next = nextClonedChunk;
  2895. nextClonedChunk.previous = clonedChunk;
  2896. clonedChunk = nextClonedChunk;
  2897. }
  2898. originalChunk = nextOriginalChunk;
  2899. }
  2900. cloned.lastChunk = clonedChunk;
  2901. if (this.indentExclusionRanges) {
  2902. cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
  2903. }
  2904. cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
  2905. cloned.intro = this.intro;
  2906. cloned.outro = this.outro;
  2907. return cloned;
  2908. }
  2909. generateDecodedMap(options) {
  2910. options = options || {};
  2911. const sourceIndex = 0;
  2912. const names = Object.keys(this.storedNames);
  2913. const mappings = new Mappings(options.hires);
  2914. const locate = getLocator(this.original);
  2915. if (this.intro) {
  2916. mappings.advance(this.intro);
  2917. }
  2918. this.firstChunk.eachNext((chunk) => {
  2919. const loc = locate(chunk.start);
  2920. if (chunk.intro.length) mappings.advance(chunk.intro);
  2921. if (chunk.edited) {
  2922. mappings.addEdit(
  2923. sourceIndex,
  2924. chunk.content,
  2925. loc,
  2926. chunk.storeName ? names.indexOf(chunk.original) : -1,
  2927. );
  2928. } else {
  2929. mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
  2930. }
  2931. if (chunk.outro.length) mappings.advance(chunk.outro);
  2932. });
  2933. return {
  2934. file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
  2935. sources: [
  2936. options.source ? getRelativePath(options.file || '', options.source) : options.file || '',
  2937. ],
  2938. sourcesContent: options.includeContent ? [this.original] : undefined,
  2939. names,
  2940. mappings: mappings.raw,
  2941. x_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined,
  2942. };
  2943. }
  2944. generateMap(options) {
  2945. return new SourceMap(this.generateDecodedMap(options));
  2946. }
  2947. _ensureindentStr() {
  2948. if (this.indentStr === undefined) {
  2949. this.indentStr = guessIndent(this.original);
  2950. }
  2951. }
  2952. _getRawIndentString() {
  2953. this._ensureindentStr();
  2954. return this.indentStr;
  2955. }
  2956. getIndentString() {
  2957. this._ensureindentStr();
  2958. return this.indentStr === null ? '\t' : this.indentStr;
  2959. }
  2960. indent(indentStr, options) {
  2961. const pattern = /^[^\r\n]/gm;
  2962. if (isObject$1(indentStr)) {
  2963. options = indentStr;
  2964. indentStr = undefined;
  2965. }
  2966. if (indentStr === undefined) {
  2967. this._ensureindentStr();
  2968. indentStr = this.indentStr || '\t';
  2969. }
  2970. if (indentStr === '') return this; // noop
  2971. options = options || {};
  2972. // Process exclusion ranges
  2973. const isExcluded = {};
  2974. if (options.exclude) {
  2975. const exclusions =
  2976. typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
  2977. exclusions.forEach((exclusion) => {
  2978. for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
  2979. isExcluded[i] = true;
  2980. }
  2981. });
  2982. }
  2983. let shouldIndentNextCharacter = options.indentStart !== false;
  2984. const replacer = (match) => {
  2985. if (shouldIndentNextCharacter) return `${indentStr}${match}`;
  2986. shouldIndentNextCharacter = true;
  2987. return match;
  2988. };
  2989. this.intro = this.intro.replace(pattern, replacer);
  2990. let charIndex = 0;
  2991. let chunk = this.firstChunk;
  2992. while (chunk) {
  2993. const end = chunk.end;
  2994. if (chunk.edited) {
  2995. if (!isExcluded[charIndex]) {
  2996. chunk.content = chunk.content.replace(pattern, replacer);
  2997. if (chunk.content.length) {
  2998. shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
  2999. }
  3000. }
  3001. } else {
  3002. charIndex = chunk.start;
  3003. while (charIndex < end) {
  3004. if (!isExcluded[charIndex]) {
  3005. const char = this.original[charIndex];
  3006. if (char === '\n') {
  3007. shouldIndentNextCharacter = true;
  3008. } else if (char !== '\r' && shouldIndentNextCharacter) {
  3009. shouldIndentNextCharacter = false;
  3010. if (charIndex === chunk.start) {
  3011. chunk.prependRight(indentStr);
  3012. } else {
  3013. this._splitChunk(chunk, charIndex);
  3014. chunk = chunk.next;
  3015. chunk.prependRight(indentStr);
  3016. }
  3017. }
  3018. }
  3019. charIndex += 1;
  3020. }
  3021. }
  3022. charIndex = chunk.end;
  3023. chunk = chunk.next;
  3024. }
  3025. this.outro = this.outro.replace(pattern, replacer);
  3026. return this;
  3027. }
  3028. insert() {
  3029. throw new Error(
  3030. 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)',
  3031. );
  3032. }
  3033. insertLeft(index, content) {
  3034. if (!warned.insertLeft) {
  3035. console.warn(
  3036. 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead',
  3037. ); // eslint-disable-line no-console
  3038. warned.insertLeft = true;
  3039. }
  3040. return this.appendLeft(index, content);
  3041. }
  3042. insertRight(index, content) {
  3043. if (!warned.insertRight) {
  3044. console.warn(
  3045. 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead',
  3046. ); // eslint-disable-line no-console
  3047. warned.insertRight = true;
  3048. }
  3049. return this.prependRight(index, content);
  3050. }
  3051. move(start, end, index) {
  3052. if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself');
  3053. this._split(start);
  3054. this._split(end);
  3055. this._split(index);
  3056. const first = this.byStart[start];
  3057. const last = this.byEnd[end];
  3058. const oldLeft = first.previous;
  3059. const oldRight = last.next;
  3060. const newRight = this.byStart[index];
  3061. if (!newRight && last === this.lastChunk) return this;
  3062. const newLeft = newRight ? newRight.previous : this.lastChunk;
  3063. if (oldLeft) oldLeft.next = oldRight;
  3064. if (oldRight) oldRight.previous = oldLeft;
  3065. if (newLeft) newLeft.next = first;
  3066. if (newRight) newRight.previous = last;
  3067. if (!first.previous) this.firstChunk = last.next;
  3068. if (!last.next) {
  3069. this.lastChunk = first.previous;
  3070. this.lastChunk.next = null;
  3071. }
  3072. first.previous = newLeft;
  3073. last.next = newRight || null;
  3074. if (!newLeft) this.firstChunk = first;
  3075. if (!newRight) this.lastChunk = last;
  3076. return this;
  3077. }
  3078. overwrite(start, end, content, options) {
  3079. options = options || {};
  3080. return this.update(start, end, content, { ...options, overwrite: !options.contentOnly });
  3081. }
  3082. update(start, end, content, options) {
  3083. if (typeof content !== 'string') throw new TypeError('replacement content must be a string');
  3084. while (start < 0) start += this.original.length;
  3085. while (end < 0) end += this.original.length;
  3086. if (end > this.original.length) throw new Error('end is out of bounds');
  3087. if (start === end)
  3088. throw new Error(
  3089. 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead',
  3090. );
  3091. this._split(start);
  3092. this._split(end);
  3093. if (options === true) {
  3094. if (!warned.storeName) {
  3095. console.warn(
  3096. 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string',
  3097. ); // eslint-disable-line no-console
  3098. warned.storeName = true;
  3099. }
  3100. options = { storeName: true };
  3101. }
  3102. const storeName = options !== undefined ? options.storeName : false;
  3103. const overwrite = options !== undefined ? options.overwrite : false;
  3104. if (storeName) {
  3105. const original = this.original.slice(start, end);
  3106. Object.defineProperty(this.storedNames, original, {
  3107. writable: true,
  3108. value: true,
  3109. enumerable: true,
  3110. });
  3111. }
  3112. const first = this.byStart[start];
  3113. const last = this.byEnd[end];
  3114. if (first) {
  3115. let chunk = first;
  3116. while (chunk !== last) {
  3117. if (chunk.next !== this.byStart[chunk.end]) {
  3118. throw new Error('Cannot overwrite across a split point');
  3119. }
  3120. chunk = chunk.next;
  3121. chunk.edit('', false);
  3122. }
  3123. first.edit(content, storeName, !overwrite);
  3124. } else {
  3125. // must be inserting at the end
  3126. const newChunk = new Chunk$1(start, end, '').edit(content, storeName);
  3127. // TODO last chunk in the array may not be the last chunk, if it's moved...
  3128. last.next = newChunk;
  3129. newChunk.previous = last;
  3130. }
  3131. return this;
  3132. }
  3133. prepend(content) {
  3134. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  3135. this.intro = content + this.intro;
  3136. return this;
  3137. }
  3138. prependLeft(index, content) {
  3139. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  3140. this._split(index);
  3141. const chunk = this.byEnd[index];
  3142. if (chunk) {
  3143. chunk.prependLeft(content);
  3144. } else {
  3145. this.intro = content + this.intro;
  3146. }
  3147. return this;
  3148. }
  3149. prependRight(index, content) {
  3150. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  3151. this._split(index);
  3152. const chunk = this.byStart[index];
  3153. if (chunk) {
  3154. chunk.prependRight(content);
  3155. } else {
  3156. this.outro = content + this.outro;
  3157. }
  3158. return this;
  3159. }
  3160. remove(start, end) {
  3161. while (start < 0) start += this.original.length;
  3162. while (end < 0) end += this.original.length;
  3163. if (start === end) return this;
  3164. if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
  3165. if (start > end) throw new Error('end must be greater than start');
  3166. this._split(start);
  3167. this._split(end);
  3168. let chunk = this.byStart[start];
  3169. while (chunk) {
  3170. chunk.intro = '';
  3171. chunk.outro = '';
  3172. chunk.edit('');
  3173. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  3174. }
  3175. return this;
  3176. }
  3177. lastChar() {
  3178. if (this.outro.length) return this.outro[this.outro.length - 1];
  3179. let chunk = this.lastChunk;
  3180. do {
  3181. if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
  3182. if (chunk.content.length) return chunk.content[chunk.content.length - 1];
  3183. if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
  3184. } while ((chunk = chunk.previous));
  3185. if (this.intro.length) return this.intro[this.intro.length - 1];
  3186. return '';
  3187. }
  3188. lastLine() {
  3189. let lineIndex = this.outro.lastIndexOf(n);
  3190. if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
  3191. let lineStr = this.outro;
  3192. let chunk = this.lastChunk;
  3193. do {
  3194. if (chunk.outro.length > 0) {
  3195. lineIndex = chunk.outro.lastIndexOf(n);
  3196. if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
  3197. lineStr = chunk.outro + lineStr;
  3198. }
  3199. if (chunk.content.length > 0) {
  3200. lineIndex = chunk.content.lastIndexOf(n);
  3201. if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
  3202. lineStr = chunk.content + lineStr;
  3203. }
  3204. if (chunk.intro.length > 0) {
  3205. lineIndex = chunk.intro.lastIndexOf(n);
  3206. if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
  3207. lineStr = chunk.intro + lineStr;
  3208. }
  3209. } while ((chunk = chunk.previous));
  3210. lineIndex = this.intro.lastIndexOf(n);
  3211. if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
  3212. return this.intro + lineStr;
  3213. }
  3214. slice(start = 0, end = this.original.length) {
  3215. while (start < 0) start += this.original.length;
  3216. while (end < 0) end += this.original.length;
  3217. let result = '';
  3218. // find start chunk
  3219. let chunk = this.firstChunk;
  3220. while (chunk && (chunk.start > start || chunk.end <= start)) {
  3221. // found end chunk before start
  3222. if (chunk.start < end && chunk.end >= end) {
  3223. return result;
  3224. }
  3225. chunk = chunk.next;
  3226. }
  3227. if (chunk && chunk.edited && chunk.start !== start)
  3228. throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
  3229. const startChunk = chunk;
  3230. while (chunk) {
  3231. if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
  3232. result += chunk.intro;
  3233. }
  3234. const containsEnd = chunk.start < end && chunk.end >= end;
  3235. if (containsEnd && chunk.edited && chunk.end !== end)
  3236. throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
  3237. const sliceStart = startChunk === chunk ? start - chunk.start : 0;
  3238. const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
  3239. result += chunk.content.slice(sliceStart, sliceEnd);
  3240. if (chunk.outro && (!containsEnd || chunk.end === end)) {
  3241. result += chunk.outro;
  3242. }
  3243. if (containsEnd) {
  3244. break;
  3245. }
  3246. chunk = chunk.next;
  3247. }
  3248. return result;
  3249. }
  3250. // TODO deprecate this? not really very useful
  3251. snip(start, end) {
  3252. const clone = this.clone();
  3253. clone.remove(0, start);
  3254. clone.remove(end, clone.original.length);
  3255. return clone;
  3256. }
  3257. _split(index) {
  3258. if (this.byStart[index] || this.byEnd[index]) return;
  3259. let chunk = this.lastSearchedChunk;
  3260. const searchForward = index > chunk.end;
  3261. while (chunk) {
  3262. if (chunk.contains(index)) return this._splitChunk(chunk, index);
  3263. chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
  3264. }
  3265. }
  3266. _splitChunk(chunk, index) {
  3267. if (chunk.edited && chunk.content.length) {
  3268. // zero-length edited chunks are a special case (overlapping replacements)
  3269. const loc = getLocator(this.original)(index);
  3270. throw new Error(
  3271. `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`,
  3272. );
  3273. }
  3274. const newChunk = chunk.split(index);
  3275. this.byEnd[index] = chunk;
  3276. this.byStart[index] = newChunk;
  3277. this.byEnd[newChunk.end] = newChunk;
  3278. if (chunk === this.lastChunk) this.lastChunk = newChunk;
  3279. this.lastSearchedChunk = chunk;
  3280. return true;
  3281. }
  3282. toString() {
  3283. let str = this.intro;
  3284. let chunk = this.firstChunk;
  3285. while (chunk) {
  3286. str += chunk.toString();
  3287. chunk = chunk.next;
  3288. }
  3289. return str + this.outro;
  3290. }
  3291. isEmpty() {
  3292. let chunk = this.firstChunk;
  3293. do {
  3294. if (
  3295. (chunk.intro.length && chunk.intro.trim()) ||
  3296. (chunk.content.length && chunk.content.trim()) ||
  3297. (chunk.outro.length && chunk.outro.trim())
  3298. )
  3299. return false;
  3300. } while ((chunk = chunk.next));
  3301. return true;
  3302. }
  3303. length() {
  3304. let chunk = this.firstChunk;
  3305. let length = 0;
  3306. do {
  3307. length += chunk.intro.length + chunk.content.length + chunk.outro.length;
  3308. } while ((chunk = chunk.next));
  3309. return length;
  3310. }
  3311. trimLines() {
  3312. return this.trim('[\\r\\n]');
  3313. }
  3314. trim(charType) {
  3315. return this.trimStart(charType).trimEnd(charType);
  3316. }
  3317. trimEndAborted(charType) {
  3318. const rx = new RegExp((charType || '\\s') + '+$');
  3319. this.outro = this.outro.replace(rx, '');
  3320. if (this.outro.length) return true;
  3321. let chunk = this.lastChunk;
  3322. do {
  3323. const end = chunk.end;
  3324. const aborted = chunk.trimEnd(rx);
  3325. // if chunk was trimmed, we have a new lastChunk
  3326. if (chunk.end !== end) {
  3327. if (this.lastChunk === chunk) {
  3328. this.lastChunk = chunk.next;
  3329. }
  3330. this.byEnd[chunk.end] = chunk;
  3331. this.byStart[chunk.next.start] = chunk.next;
  3332. this.byEnd[chunk.next.end] = chunk.next;
  3333. }
  3334. if (aborted) return true;
  3335. chunk = chunk.previous;
  3336. } while (chunk);
  3337. return false;
  3338. }
  3339. trimEnd(charType) {
  3340. this.trimEndAborted(charType);
  3341. return this;
  3342. }
  3343. trimStartAborted(charType) {
  3344. const rx = new RegExp('^' + (charType || '\\s') + '+');
  3345. this.intro = this.intro.replace(rx, '');
  3346. if (this.intro.length) return true;
  3347. let chunk = this.firstChunk;
  3348. do {
  3349. const end = chunk.end;
  3350. const aborted = chunk.trimStart(rx);
  3351. if (chunk.end !== end) {
  3352. // special case...
  3353. if (chunk === this.lastChunk) this.lastChunk = chunk.next;
  3354. this.byEnd[chunk.end] = chunk;
  3355. this.byStart[chunk.next.start] = chunk.next;
  3356. this.byEnd[chunk.next.end] = chunk.next;
  3357. }
  3358. if (aborted) return true;
  3359. chunk = chunk.next;
  3360. } while (chunk);
  3361. return false;
  3362. }
  3363. trimStart(charType) {
  3364. this.trimStartAborted(charType);
  3365. return this;
  3366. }
  3367. hasChanged() {
  3368. return this.original !== this.toString();
  3369. }
  3370. _replaceRegexp(searchValue, replacement) {
  3371. function getReplacement(match, str) {
  3372. if (typeof replacement === 'string') {
  3373. return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
  3374. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
  3375. if (i === '$') return '$';
  3376. if (i === '&') return match[0];
  3377. const num = +i;
  3378. if (num < match.length) return match[+i];
  3379. return `$${i}`;
  3380. });
  3381. } else {
  3382. return replacement(...match, match.index, str, match.groups);
  3383. }
  3384. }
  3385. function matchAll(re, str) {
  3386. let match;
  3387. const matches = [];
  3388. while ((match = re.exec(str))) {
  3389. matches.push(match);
  3390. }
  3391. return matches;
  3392. }
  3393. if (searchValue.global) {
  3394. const matches = matchAll(searchValue, this.original);
  3395. matches.forEach((match) => {
  3396. if (match.index != null)
  3397. this.overwrite(
  3398. match.index,
  3399. match.index + match[0].length,
  3400. getReplacement(match, this.original),
  3401. );
  3402. });
  3403. } else {
  3404. const match = this.original.match(searchValue);
  3405. if (match && match.index != null)
  3406. this.overwrite(
  3407. match.index,
  3408. match.index + match[0].length,
  3409. getReplacement(match, this.original),
  3410. );
  3411. }
  3412. return this;
  3413. }
  3414. _replaceString(string, replacement) {
  3415. const { original } = this;
  3416. const index = original.indexOf(string);
  3417. if (index !== -1) {
  3418. this.overwrite(index, index + string.length, replacement);
  3419. }
  3420. return this;
  3421. }
  3422. replace(searchValue, replacement) {
  3423. if (typeof searchValue === 'string') {
  3424. return this._replaceString(searchValue, replacement);
  3425. }
  3426. return this._replaceRegexp(searchValue, replacement);
  3427. }
  3428. _replaceAllString(string, replacement) {
  3429. const { original } = this;
  3430. const stringLength = string.length;
  3431. for (
  3432. let index = original.indexOf(string);
  3433. index !== -1;
  3434. index = original.indexOf(string, index + stringLength)
  3435. ) {
  3436. this.overwrite(index, index + stringLength, replacement);
  3437. }
  3438. return this;
  3439. }
  3440. replaceAll(searchValue, replacement) {
  3441. if (typeof searchValue === 'string') {
  3442. return this._replaceAllString(searchValue, replacement);
  3443. }
  3444. if (!searchValue.global) {
  3445. throw new TypeError(
  3446. 'MagicString.prototype.replaceAll called with a non-global RegExp argument',
  3447. );
  3448. }
  3449. return this._replaceRegexp(searchValue, replacement);
  3450. }
  3451. }
  3452. const hasOwnProp = Object.prototype.hasOwnProperty;
  3453. let Bundle$1 = class Bundle {
  3454. constructor(options = {}) {
  3455. this.intro = options.intro || '';
  3456. this.separator = options.separator !== undefined ? options.separator : '\n';
  3457. this.sources = [];
  3458. this.uniqueSources = [];
  3459. this.uniqueSourceIndexByFilename = {};
  3460. }
  3461. addSource(source) {
  3462. if (source instanceof MagicString) {
  3463. return this.addSource({
  3464. content: source,
  3465. filename: source.filename,
  3466. separator: this.separator,
  3467. });
  3468. }
  3469. if (!isObject$1(source) || !source.content) {
  3470. throw new Error(
  3471. 'bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`',
  3472. );
  3473. }
  3474. ['filename', 'ignoreList', 'indentExclusionRanges', 'separator'].forEach((option) => {
  3475. if (!hasOwnProp.call(source, option)) source[option] = source.content[option];
  3476. });
  3477. if (source.separator === undefined) {
  3478. // TODO there's a bunch of this sort of thing, needs cleaning up
  3479. source.separator = this.separator;
  3480. }
  3481. if (source.filename) {
  3482. if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {
  3483. this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;
  3484. this.uniqueSources.push({ filename: source.filename, content: source.content.original });
  3485. } else {
  3486. const uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];
  3487. if (source.content.original !== uniqueSource.content) {
  3488. throw new Error(`Illegal source: same filename (${source.filename}), different contents`);
  3489. }
  3490. }
  3491. }
  3492. this.sources.push(source);
  3493. return this;
  3494. }
  3495. append(str, options) {
  3496. this.addSource({
  3497. content: new MagicString(str),
  3498. separator: (options && options.separator) || '',
  3499. });
  3500. return this;
  3501. }
  3502. clone() {
  3503. const bundle = new Bundle({
  3504. intro: this.intro,
  3505. separator: this.separator,
  3506. });
  3507. this.sources.forEach((source) => {
  3508. bundle.addSource({
  3509. filename: source.filename,
  3510. content: source.content.clone(),
  3511. separator: source.separator,
  3512. });
  3513. });
  3514. return bundle;
  3515. }
  3516. generateDecodedMap(options = {}) {
  3517. const names = [];
  3518. let x_google_ignoreList = undefined;
  3519. this.sources.forEach((source) => {
  3520. Object.keys(source.content.storedNames).forEach((name) => {
  3521. if (!~names.indexOf(name)) names.push(name);
  3522. });
  3523. });
  3524. const mappings = new Mappings(options.hires);
  3525. if (this.intro) {
  3526. mappings.advance(this.intro);
  3527. }
  3528. this.sources.forEach((source, i) => {
  3529. if (i > 0) {
  3530. mappings.advance(this.separator);
  3531. }
  3532. const sourceIndex = source.filename ? this.uniqueSourceIndexByFilename[source.filename] : -1;
  3533. const magicString = source.content;
  3534. const locate = getLocator(magicString.original);
  3535. if (magicString.intro) {
  3536. mappings.advance(magicString.intro);
  3537. }
  3538. magicString.firstChunk.eachNext((chunk) => {
  3539. const loc = locate(chunk.start);
  3540. if (chunk.intro.length) mappings.advance(chunk.intro);
  3541. if (source.filename) {
  3542. if (chunk.edited) {
  3543. mappings.addEdit(
  3544. sourceIndex,
  3545. chunk.content,
  3546. loc,
  3547. chunk.storeName ? names.indexOf(chunk.original) : -1,
  3548. );
  3549. } else {
  3550. mappings.addUneditedChunk(
  3551. sourceIndex,
  3552. chunk,
  3553. magicString.original,
  3554. loc,
  3555. magicString.sourcemapLocations,
  3556. );
  3557. }
  3558. } else {
  3559. mappings.advance(chunk.content);
  3560. }
  3561. if (chunk.outro.length) mappings.advance(chunk.outro);
  3562. });
  3563. if (magicString.outro) {
  3564. mappings.advance(magicString.outro);
  3565. }
  3566. if (source.ignoreList && sourceIndex !== -1) {
  3567. if (x_google_ignoreList === undefined) {
  3568. x_google_ignoreList = [];
  3569. }
  3570. x_google_ignoreList.push(sourceIndex);
  3571. }
  3572. });
  3573. return {
  3574. file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
  3575. sources: this.uniqueSources.map((source) => {
  3576. return options.file ? getRelativePath(options.file, source.filename) : source.filename;
  3577. }),
  3578. sourcesContent: this.uniqueSources.map((source) => {
  3579. return options.includeContent ? source.content : null;
  3580. }),
  3581. names,
  3582. mappings: mappings.raw,
  3583. x_google_ignoreList,
  3584. };
  3585. }
  3586. generateMap(options) {
  3587. return new SourceMap(this.generateDecodedMap(options));
  3588. }
  3589. getIndentString() {
  3590. const indentStringCounts = {};
  3591. this.sources.forEach((source) => {
  3592. const indentStr = source.content._getRawIndentString();
  3593. if (indentStr === null) return;
  3594. if (!indentStringCounts[indentStr]) indentStringCounts[indentStr] = 0;
  3595. indentStringCounts[indentStr] += 1;
  3596. });
  3597. return (
  3598. Object.keys(indentStringCounts).sort((a, b) => {
  3599. return indentStringCounts[a] - indentStringCounts[b];
  3600. })[0] || '\t'
  3601. );
  3602. }
  3603. indent(indentStr) {
  3604. if (!arguments.length) {
  3605. indentStr = this.getIndentString();
  3606. }
  3607. if (indentStr === '') return this; // noop
  3608. let trailingNewline = !this.intro || this.intro.slice(-1) === '\n';
  3609. this.sources.forEach((source, i) => {
  3610. const separator = source.separator !== undefined ? source.separator : this.separator;
  3611. const indentStart = trailingNewline || (i > 0 && /\r?\n$/.test(separator));
  3612. source.content.indent(indentStr, {
  3613. exclude: source.indentExclusionRanges,
  3614. indentStart, //: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator )
  3615. });
  3616. trailingNewline = source.content.lastChar() === '\n';
  3617. });
  3618. if (this.intro) {
  3619. this.intro =
  3620. indentStr +
  3621. this.intro.replace(/^[^\n]/gm, (match, index) => {
  3622. return index > 0 ? indentStr + match : match;
  3623. });
  3624. }
  3625. return this;
  3626. }
  3627. prepend(str) {
  3628. this.intro = str + this.intro;
  3629. return this;
  3630. }
  3631. toString() {
  3632. const body = this.sources
  3633. .map((source, i) => {
  3634. const separator = source.separator !== undefined ? source.separator : this.separator;
  3635. const str = (i > 0 ? separator : '') + source.content.toString();
  3636. return str;
  3637. })
  3638. .join('');
  3639. return this.intro + body;
  3640. }
  3641. isEmpty() {
  3642. if (this.intro.length && this.intro.trim()) return false;
  3643. if (this.sources.some((source) => !source.content.isEmpty())) return false;
  3644. return true;
  3645. }
  3646. length() {
  3647. return this.sources.reduce(
  3648. (length, source) => length + source.content.length(),
  3649. this.intro.length,
  3650. );
  3651. }
  3652. trimLines() {
  3653. return this.trim('[\\r\\n]');
  3654. }
  3655. trim(charType) {
  3656. return this.trimStart(charType).trimEnd(charType);
  3657. }
  3658. trimStart(charType) {
  3659. const rx = new RegExp('^' + (charType || '\\s') + '+');
  3660. this.intro = this.intro.replace(rx, '');
  3661. if (!this.intro) {
  3662. let source;
  3663. let i = 0;
  3664. do {
  3665. source = this.sources[i++];
  3666. if (!source) {
  3667. break;
  3668. }
  3669. } while (!source.content.trimStartAborted(charType));
  3670. }
  3671. return this;
  3672. }
  3673. trimEnd(charType) {
  3674. const rx = new RegExp((charType || '\\s') + '+$');
  3675. let source;
  3676. let i = this.sources.length - 1;
  3677. do {
  3678. source = this.sources[i--];
  3679. if (!source) {
  3680. this.intro = this.intro.replace(rx, '');
  3681. break;
  3682. }
  3683. } while (!source.content.trimEndAborted(charType));
  3684. return this;
  3685. }
  3686. };
  3687. const needsEscapeRegEx = /[\n\r'\\\u2028\u2029]/;
  3688. const quoteNewlineRegEx = /([\n\r'\u2028\u2029])/g;
  3689. const backSlashRegEx = /\\/g;
  3690. function escapeId(id) {
  3691. if (!needsEscapeRegEx.test(id))
  3692. return id;
  3693. return id.replace(backSlashRegEx, '\\\\').replace(quoteNewlineRegEx, '\\$1');
  3694. }
  3695. class ExternalChunk {
  3696. constructor(module, options, inputBase) {
  3697. this.options = options;
  3698. this.inputBase = inputBase;
  3699. this.defaultVariableName = '';
  3700. this.namespaceVariableName = '';
  3701. this.variableName = '';
  3702. this.fileName = null;
  3703. this.importAssertions = null;
  3704. this.id = module.id;
  3705. this.moduleInfo = module.info;
  3706. this.renormalizeRenderPath = module.renormalizeRenderPath;
  3707. this.suggestedVariableName = module.suggestedVariableName;
  3708. }
  3709. getFileName() {
  3710. if (this.fileName) {
  3711. return this.fileName;
  3712. }
  3713. const { paths } = this.options;
  3714. return (this.fileName =
  3715. (typeof paths === 'function' ? paths(this.id) : paths[this.id]) ||
  3716. (this.renormalizeRenderPath ? normalize(node_path.relative(this.inputBase, this.id)) : this.id));
  3717. }
  3718. getImportAssertions(snippets) {
  3719. return (this.importAssertions || (this.importAssertions = formatAssertions(this.options.format === 'es' &&
  3720. this.options.externalImportAssertions &&
  3721. this.moduleInfo.assertions, snippets)));
  3722. }
  3723. getImportPath(importer) {
  3724. return escapeId(this.renormalizeRenderPath
  3725. ? getImportPath(importer, this.getFileName(), this.options.format === 'amd', false)
  3726. : this.getFileName());
  3727. }
  3728. }
  3729. function formatAssertions(assertions, { getObject }) {
  3730. if (!assertions) {
  3731. return null;
  3732. }
  3733. const assertionEntries = Object.entries(assertions).map(([key, value]) => [key, `'${value}'`]);
  3734. if (assertionEntries.length > 0) {
  3735. return getObject(assertionEntries, { lineBreakIndent: null });
  3736. }
  3737. return null;
  3738. }
  3739. const UnknownKey = Symbol('Unknown Key');
  3740. const UnknownNonAccessorKey = Symbol('Unknown Non-Accessor Key');
  3741. const UnknownInteger = Symbol('Unknown Integer');
  3742. const SymbolToStringTag = Symbol('Symbol.toStringTag');
  3743. const EMPTY_PATH = [];
  3744. const UNKNOWN_PATH = [UnknownKey];
  3745. // For deoptimizations, this means we are modifying an unknown property but did
  3746. // not lose track of the object or are creating a setter/getter;
  3747. // For assignment effects it means we do not check for setter/getter effects
  3748. // but only if something is mutated that is included, which is relevant for
  3749. // Object.defineProperty
  3750. const UNKNOWN_NON_ACCESSOR_PATH = [UnknownNonAccessorKey];
  3751. const UNKNOWN_INTEGER_PATH = [UnknownInteger];
  3752. const EntitiesKey = Symbol('Entities');
  3753. class PathTracker {
  3754. constructor() {
  3755. this.entityPaths = Object.create(null, {
  3756. [EntitiesKey]: { value: new Set() }
  3757. });
  3758. }
  3759. trackEntityAtPathAndGetIfTracked(path, entity) {
  3760. const trackedEntities = this.getEntities(path);
  3761. if (trackedEntities.has(entity))
  3762. return true;
  3763. trackedEntities.add(entity);
  3764. return false;
  3765. }
  3766. withTrackedEntityAtPath(path, entity, onUntracked, returnIfTracked) {
  3767. const trackedEntities = this.getEntities(path);
  3768. if (trackedEntities.has(entity))
  3769. return returnIfTracked;
  3770. trackedEntities.add(entity);
  3771. const result = onUntracked();
  3772. trackedEntities.delete(entity);
  3773. return result;
  3774. }
  3775. getEntities(path) {
  3776. let currentPaths = this.entityPaths;
  3777. for (const pathSegment of path) {
  3778. currentPaths = currentPaths[pathSegment] =
  3779. currentPaths[pathSegment] ||
  3780. Object.create(null, { [EntitiesKey]: { value: new Set() } });
  3781. }
  3782. return currentPaths[EntitiesKey];
  3783. }
  3784. }
  3785. const SHARED_RECURSION_TRACKER = new PathTracker();
  3786. class DiscriminatedPathTracker {
  3787. constructor() {
  3788. this.entityPaths = Object.create(null, {
  3789. [EntitiesKey]: { value: new Map() }
  3790. });
  3791. }
  3792. trackEntityAtPathAndGetIfTracked(path, discriminator, entity) {
  3793. let currentPaths = this.entityPaths;
  3794. for (const pathSegment of path) {
  3795. currentPaths = currentPaths[pathSegment] =
  3796. currentPaths[pathSegment] ||
  3797. Object.create(null, { [EntitiesKey]: { value: new Map() } });
  3798. }
  3799. const trackedEntities = getOrCreate(currentPaths[EntitiesKey], discriminator, (getNewSet));
  3800. if (trackedEntities.has(entity))
  3801. return true;
  3802. trackedEntities.add(entity);
  3803. return false;
  3804. }
  3805. }
  3806. const UnknownValue = Symbol('Unknown Value');
  3807. const UnknownTruthyValue = Symbol('Unknown Truthy Value');
  3808. class ExpressionEntity {
  3809. constructor() {
  3810. this.included = false;
  3811. }
  3812. deoptimizeArgumentsOnInteractionAtPath(interaction, _path, _recursionTracker) {
  3813. deoptimizeInteraction(interaction);
  3814. }
  3815. deoptimizePath(_path) { }
  3816. /**
  3817. * If possible it returns a stringifyable literal value for this node that
  3818. * can be used for inlining or comparing values. Otherwise, it should return
  3819. * UnknownValue.
  3820. */
  3821. getLiteralValueAtPath(_path, _recursionTracker, _origin) {
  3822. return UnknownValue;
  3823. }
  3824. getReturnExpressionWhenCalledAtPath(_path, _interaction, _recursionTracker, _origin) {
  3825. return UNKNOWN_RETURN_EXPRESSION;
  3826. }
  3827. hasEffectsOnInteractionAtPath(_path, _interaction, _context) {
  3828. return true;
  3829. }
  3830. include(_context, _includeChildrenRecursively, _options) {
  3831. this.included = true;
  3832. }
  3833. includeCallArguments(context, parameters) {
  3834. for (const argument of parameters) {
  3835. argument.include(context, false);
  3836. }
  3837. }
  3838. shouldBeIncluded(_context) {
  3839. return true;
  3840. }
  3841. }
  3842. const UNKNOWN_EXPRESSION = new (class UnknownExpression extends ExpressionEntity {
  3843. })();
  3844. const UNKNOWN_RETURN_EXPRESSION = [
  3845. UNKNOWN_EXPRESSION,
  3846. false
  3847. ];
  3848. const deoptimizeInteraction = (interaction) => {
  3849. for (const argument of interaction.args) {
  3850. argument?.deoptimizePath(UNKNOWN_PATH);
  3851. }
  3852. };
  3853. const INTERACTION_ACCESSED = 0;
  3854. const INTERACTION_ASSIGNED = 1;
  3855. const INTERACTION_CALLED = 2;
  3856. const NODE_INTERACTION_UNKNOWN_ACCESS = {
  3857. args: [null],
  3858. type: INTERACTION_ACCESSED
  3859. };
  3860. const NODE_INTERACTION_UNKNOWN_ASSIGNMENT = {
  3861. args: [null, UNKNOWN_EXPRESSION],
  3862. type: INTERACTION_ASSIGNED
  3863. };
  3864. // While this is technically a call without arguments, we can compare against
  3865. // this reference in places where precise values or this argument would make a
  3866. // difference
  3867. const NODE_INTERACTION_UNKNOWN_CALL = {
  3868. args: [null],
  3869. type: INTERACTION_CALLED,
  3870. withNew: false
  3871. };
  3872. class Variable extends ExpressionEntity {
  3873. constructor(name) {
  3874. super();
  3875. this.name = name;
  3876. this.alwaysRendered = false;
  3877. this.forbiddenNames = null;
  3878. this.initReached = false;
  3879. this.isId = false;
  3880. this.isReassigned = false;
  3881. this.kind = null;
  3882. this.renderBaseName = null;
  3883. this.renderName = null;
  3884. }
  3885. /**
  3886. * Binds identifiers that reference this variable to this variable.
  3887. * Necessary to be able to change variable names.
  3888. */
  3889. addReference(_identifier) { }
  3890. /**
  3891. * Prevent this variable from being renamed to this name to avoid name
  3892. * collisions
  3893. */
  3894. forbidName(name) {
  3895. (this.forbiddenNames || (this.forbiddenNames = new Set())).add(name);
  3896. }
  3897. getBaseVariableName() {
  3898. return this.renderBaseName || this.renderName || this.name;
  3899. }
  3900. getName(getPropertyAccess, useOriginalName) {
  3901. if (useOriginalName?.(this)) {
  3902. return this.name;
  3903. }
  3904. const name = this.renderName || this.name;
  3905. return this.renderBaseName ? `${this.renderBaseName}${getPropertyAccess(name)}` : name;
  3906. }
  3907. hasEffectsOnInteractionAtPath(path, { type }, _context) {
  3908. return type !== INTERACTION_ACCESSED || path.length > 0;
  3909. }
  3910. /**
  3911. * Marks this variable as being part of the bundle, which is usually the case when one of
  3912. * its identifiers becomes part of the bundle. Returns true if it has not been included
  3913. * previously.
  3914. * Once a variable is included, it should take care all its declarations are included.
  3915. */
  3916. include() {
  3917. this.included = true;
  3918. }
  3919. markCalledFromTryStatement() { }
  3920. setRenderNames(baseName, name) {
  3921. this.renderBaseName = baseName;
  3922. this.renderName = name;
  3923. }
  3924. }
  3925. class ExternalVariable extends Variable {
  3926. constructor(module, name) {
  3927. super(name);
  3928. this.referenced = false;
  3929. this.module = module;
  3930. this.isNamespace = name === '*';
  3931. }
  3932. addReference(identifier) {
  3933. this.referenced = true;
  3934. if (this.name === 'default' || this.name === '*') {
  3935. this.module.suggestName(identifier.name);
  3936. }
  3937. }
  3938. hasEffectsOnInteractionAtPath(path, { type }) {
  3939. return type !== INTERACTION_ACCESSED || path.length > (this.isNamespace ? 1 : 0);
  3940. }
  3941. include() {
  3942. if (!this.included) {
  3943. this.included = true;
  3944. this.module.used = true;
  3945. }
  3946. }
  3947. }
  3948. const RESERVED_NAMES = new Set([
  3949. 'await',
  3950. 'break',
  3951. 'case',
  3952. 'catch',
  3953. 'class',
  3954. 'const',
  3955. 'continue',
  3956. 'debugger',
  3957. 'default',
  3958. 'delete',
  3959. 'do',
  3960. 'else',
  3961. 'enum',
  3962. 'eval',
  3963. 'export',
  3964. 'extends',
  3965. 'false',
  3966. 'finally',
  3967. 'for',
  3968. 'function',
  3969. 'if',
  3970. 'implements',
  3971. 'import',
  3972. 'in',
  3973. 'instanceof',
  3974. 'interface',
  3975. 'let',
  3976. 'NaN',
  3977. 'new',
  3978. 'null',
  3979. 'package',
  3980. 'private',
  3981. 'protected',
  3982. 'public',
  3983. 'return',
  3984. 'static',
  3985. 'super',
  3986. 'switch',
  3987. 'this',
  3988. 'throw',
  3989. 'true',
  3990. 'try',
  3991. 'typeof',
  3992. 'undefined',
  3993. 'var',
  3994. 'void',
  3995. 'while',
  3996. 'with',
  3997. 'yield'
  3998. ]);
  3999. const RESERVED_NAMES$1 = RESERVED_NAMES;
  4000. const illegalCharacters = /[^\w$]/g;
  4001. const startsWithDigit = (value) => /\d/.test(value[0]);
  4002. const needsEscape = (value) => startsWithDigit(value) || RESERVED_NAMES$1.has(value) || value === 'arguments';
  4003. function isLegal(value) {
  4004. if (needsEscape(value)) {
  4005. return false;
  4006. }
  4007. return !illegalCharacters.test(value);
  4008. }
  4009. function makeLegal(value) {
  4010. value = value
  4011. .replace(/-(\w)/g, (_, letter) => letter.toUpperCase())
  4012. .replace(illegalCharacters, '_');
  4013. if (needsEscape(value))
  4014. value = `_${value}`;
  4015. return value || '_';
  4016. }
  4017. class ExternalModule {
  4018. constructor(options, id, moduleSideEffects, meta, renormalizeRenderPath, assertions) {
  4019. this.options = options;
  4020. this.id = id;
  4021. this.renormalizeRenderPath = renormalizeRenderPath;
  4022. this.dynamicImporters = [];
  4023. this.execIndex = Infinity;
  4024. this.exportedVariables = new Map();
  4025. this.importers = [];
  4026. this.reexported = false;
  4027. this.used = false;
  4028. this.declarations = new Map();
  4029. this.mostCommonSuggestion = 0;
  4030. this.nameSuggestions = new Map();
  4031. this.suggestedVariableName = makeLegal(id.split(/[/\\]/).pop());
  4032. const { importers, dynamicImporters } = this;
  4033. const info = (this.info = {
  4034. assertions,
  4035. ast: null,
  4036. code: null,
  4037. dynamicallyImportedIdResolutions: EMPTY_ARRAY,
  4038. dynamicallyImportedIds: EMPTY_ARRAY,
  4039. get dynamicImporters() {
  4040. return dynamicImporters.sort();
  4041. },
  4042. exportedBindings: null,
  4043. exports: null,
  4044. hasDefaultExport: null,
  4045. get hasModuleSideEffects() {
  4046. warnDeprecation('Accessing ModuleInfo.hasModuleSideEffects from plugins is deprecated. Please use ModuleInfo.moduleSideEffects instead.', URL_THIS_GETMODULEINFO, true, options);
  4047. return info.moduleSideEffects;
  4048. },
  4049. id,
  4050. implicitlyLoadedAfterOneOf: EMPTY_ARRAY,
  4051. implicitlyLoadedBefore: EMPTY_ARRAY,
  4052. importedIdResolutions: EMPTY_ARRAY,
  4053. importedIds: EMPTY_ARRAY,
  4054. get importers() {
  4055. return importers.sort();
  4056. },
  4057. isEntry: false,
  4058. isExternal: true,
  4059. isIncluded: null,
  4060. meta,
  4061. moduleSideEffects,
  4062. syntheticNamedExports: false
  4063. });
  4064. // Hide the deprecated key so that it only warns when accessed explicitly
  4065. Object.defineProperty(this.info, 'hasModuleSideEffects', {
  4066. enumerable: false
  4067. });
  4068. }
  4069. getVariableForExportName(name) {
  4070. const declaration = this.declarations.get(name);
  4071. if (declaration)
  4072. return [declaration];
  4073. const externalVariable = new ExternalVariable(this, name);
  4074. this.declarations.set(name, externalVariable);
  4075. this.exportedVariables.set(externalVariable, name);
  4076. return [externalVariable];
  4077. }
  4078. suggestName(name) {
  4079. const value = (this.nameSuggestions.get(name) ?? 0) + 1;
  4080. this.nameSuggestions.set(name, value);
  4081. if (value > this.mostCommonSuggestion) {
  4082. this.mostCommonSuggestion = value;
  4083. this.suggestedVariableName = name;
  4084. }
  4085. }
  4086. warnUnusedImports() {
  4087. const unused = [...this.declarations]
  4088. .filter(([name, declaration]) => name !== '*' && !declaration.included && !this.reexported && !declaration.referenced)
  4089. .map(([name]) => name);
  4090. if (unused.length === 0)
  4091. return;
  4092. const importersSet = new Set();
  4093. for (const name of unused) {
  4094. for (const importer of this.declarations.get(name).module.importers) {
  4095. importersSet.add(importer);
  4096. }
  4097. }
  4098. const importersArray = [...importersSet];
  4099. this.options.onLog(LOGLEVEL_WARN, logUnusedExternalImports(this.id, unused, importersArray));
  4100. }
  4101. }
  4102. function getDefaultExportFromCjs (x) {
  4103. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  4104. }
  4105. function getAugmentedNamespace(n) {
  4106. if (n.__esModule) return n;
  4107. var f = n.default;
  4108. if (typeof f == "function") {
  4109. var a = function a () {
  4110. if (this instanceof a) {
  4111. return Reflect.construct(f, arguments, this.constructor);
  4112. }
  4113. return f.apply(this, arguments);
  4114. };
  4115. a.prototype = f.prototype;
  4116. } else a = {};
  4117. Object.defineProperty(a, '__esModule', {value: true});
  4118. Object.keys(n).forEach(function (k) {
  4119. var d = Object.getOwnPropertyDescriptor(n, k);
  4120. Object.defineProperty(a, k, d.get ? d : {
  4121. enumerable: true,
  4122. get: function () {
  4123. return n[k];
  4124. }
  4125. });
  4126. });
  4127. return a;
  4128. }
  4129. var utils$3 = {};
  4130. const path$1 = require$$0$1;
  4131. const WIN_SLASH = '\\\\/';
  4132. const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
  4133. /**
  4134. * Posix glob regex
  4135. */
  4136. const DOT_LITERAL = '\\.';
  4137. const PLUS_LITERAL = '\\+';
  4138. const QMARK_LITERAL = '\\?';
  4139. const SLASH_LITERAL = '\\/';
  4140. const ONE_CHAR = '(?=.)';
  4141. const QMARK = '[^/]';
  4142. const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
  4143. const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
  4144. const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
  4145. const NO_DOT = `(?!${DOT_LITERAL})`;
  4146. const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
  4147. const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
  4148. const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
  4149. const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
  4150. const STAR = `${QMARK}*?`;
  4151. const POSIX_CHARS = {
  4152. DOT_LITERAL,
  4153. PLUS_LITERAL,
  4154. QMARK_LITERAL,
  4155. SLASH_LITERAL,
  4156. ONE_CHAR,
  4157. QMARK,
  4158. END_ANCHOR,
  4159. DOTS_SLASH,
  4160. NO_DOT,
  4161. NO_DOTS,
  4162. NO_DOT_SLASH,
  4163. NO_DOTS_SLASH,
  4164. QMARK_NO_DOT,
  4165. STAR,
  4166. START_ANCHOR
  4167. };
  4168. /**
  4169. * Windows glob regex
  4170. */
  4171. const WINDOWS_CHARS = {
  4172. ...POSIX_CHARS,
  4173. SLASH_LITERAL: `[${WIN_SLASH}]`,
  4174. QMARK: WIN_NO_SLASH,
  4175. STAR: `${WIN_NO_SLASH}*?`,
  4176. DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
  4177. NO_DOT: `(?!${DOT_LITERAL})`,
  4178. NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  4179. NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
  4180. NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  4181. QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
  4182. START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
  4183. END_ANCHOR: `(?:[${WIN_SLASH}]|$)`
  4184. };
  4185. /**
  4186. * POSIX Bracket Regex
  4187. */
  4188. const POSIX_REGEX_SOURCE$1 = {
  4189. alnum: 'a-zA-Z0-9',
  4190. alpha: 'a-zA-Z',
  4191. ascii: '\\x00-\\x7F',
  4192. blank: ' \\t',
  4193. cntrl: '\\x00-\\x1F\\x7F',
  4194. digit: '0-9',
  4195. graph: '\\x21-\\x7E',
  4196. lower: 'a-z',
  4197. print: '\\x20-\\x7E ',
  4198. punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
  4199. space: ' \\t\\r\\n\\v\\f',
  4200. upper: 'A-Z',
  4201. word: 'A-Za-z0-9_',
  4202. xdigit: 'A-Fa-f0-9'
  4203. };
  4204. var constants$2 = {
  4205. MAX_LENGTH: 1024 * 64,
  4206. POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1,
  4207. // regular expressions
  4208. REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
  4209. REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
  4210. REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
  4211. REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
  4212. REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
  4213. REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
  4214. // Replace globs with equivalent patterns to reduce parsing time.
  4215. REPLACEMENTS: {
  4216. '***': '*',
  4217. '**/**': '**',
  4218. '**/**/**': '**'
  4219. },
  4220. // Digits
  4221. CHAR_0: 48, /* 0 */
  4222. CHAR_9: 57, /* 9 */
  4223. // Alphabet chars.
  4224. CHAR_UPPERCASE_A: 65, /* A */
  4225. CHAR_LOWERCASE_A: 97, /* a */
  4226. CHAR_UPPERCASE_Z: 90, /* Z */
  4227. CHAR_LOWERCASE_Z: 122, /* z */
  4228. CHAR_LEFT_PARENTHESES: 40, /* ( */
  4229. CHAR_RIGHT_PARENTHESES: 41, /* ) */
  4230. CHAR_ASTERISK: 42, /* * */
  4231. // Non-alphabetic chars.
  4232. CHAR_AMPERSAND: 38, /* & */
  4233. CHAR_AT: 64, /* @ */
  4234. CHAR_BACKWARD_SLASH: 92, /* \ */
  4235. CHAR_CARRIAGE_RETURN: 13, /* \r */
  4236. CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */
  4237. CHAR_COLON: 58, /* : */
  4238. CHAR_COMMA: 44, /* , */
  4239. CHAR_DOT: 46, /* . */
  4240. CHAR_DOUBLE_QUOTE: 34, /* " */
  4241. CHAR_EQUAL: 61, /* = */
  4242. CHAR_EXCLAMATION_MARK: 33, /* ! */
  4243. CHAR_FORM_FEED: 12, /* \f */
  4244. CHAR_FORWARD_SLASH: 47, /* / */
  4245. CHAR_GRAVE_ACCENT: 96, /* ` */
  4246. CHAR_HASH: 35, /* # */
  4247. CHAR_HYPHEN_MINUS: 45, /* - */
  4248. CHAR_LEFT_ANGLE_BRACKET: 60, /* < */
  4249. CHAR_LEFT_CURLY_BRACE: 123, /* { */
  4250. CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */
  4251. CHAR_LINE_FEED: 10, /* \n */
  4252. CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
  4253. CHAR_PERCENT: 37, /* % */
  4254. CHAR_PLUS: 43, /* + */
  4255. CHAR_QUESTION_MARK: 63, /* ? */
  4256. CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */
  4257. CHAR_RIGHT_CURLY_BRACE: 125, /* } */
  4258. CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */
  4259. CHAR_SEMICOLON: 59, /* ; */
  4260. CHAR_SINGLE_QUOTE: 39, /* ' */
  4261. CHAR_SPACE: 32, /* */
  4262. CHAR_TAB: 9, /* \t */
  4263. CHAR_UNDERSCORE: 95, /* _ */
  4264. CHAR_VERTICAL_LINE: 124, /* | */
  4265. CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
  4266. SEP: path$1.sep,
  4267. /**
  4268. * Create EXTGLOB_CHARS
  4269. */
  4270. extglobChars(chars) {
  4271. return {
  4272. '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
  4273. '?': { type: 'qmark', open: '(?:', close: ')?' },
  4274. '+': { type: 'plus', open: '(?:', close: ')+' },
  4275. '*': { type: 'star', open: '(?:', close: ')*' },
  4276. '@': { type: 'at', open: '(?:', close: ')' }
  4277. };
  4278. },
  4279. /**
  4280. * Create GLOB_CHARS
  4281. */
  4282. globChars(win32) {
  4283. return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
  4284. }
  4285. };
  4286. (function (exports) {
  4287. const path = require$$0$1;
  4288. const win32 = process.platform === 'win32';
  4289. const {
  4290. REGEX_BACKSLASH,
  4291. REGEX_REMOVE_BACKSLASH,
  4292. REGEX_SPECIAL_CHARS,
  4293. REGEX_SPECIAL_CHARS_GLOBAL
  4294. } = constants$2;
  4295. exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  4296. exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
  4297. exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
  4298. exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
  4299. exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
  4300. exports.removeBackslashes = str => {
  4301. return str.replace(REGEX_REMOVE_BACKSLASH, match => {
  4302. return match === '\\' ? '' : match;
  4303. });
  4304. };
  4305. exports.supportsLookbehinds = () => {
  4306. const segs = process.version.slice(1).split('.').map(Number);
  4307. if (segs.length === 3 && segs[0] >= 9 || (segs[0] === 8 && segs[1] >= 10)) {
  4308. return true;
  4309. }
  4310. return false;
  4311. };
  4312. exports.isWindows = options => {
  4313. if (options && typeof options.windows === 'boolean') {
  4314. return options.windows;
  4315. }
  4316. return win32 === true || path.sep === '\\';
  4317. };
  4318. exports.escapeLast = (input, char, lastIdx) => {
  4319. const idx = input.lastIndexOf(char, lastIdx);
  4320. if (idx === -1) return input;
  4321. if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
  4322. return `${input.slice(0, idx)}\\${input.slice(idx)}`;
  4323. };
  4324. exports.removePrefix = (input, state = {}) => {
  4325. let output = input;
  4326. if (output.startsWith('./')) {
  4327. output = output.slice(2);
  4328. state.prefix = './';
  4329. }
  4330. return output;
  4331. };
  4332. exports.wrapOutput = (input, state = {}, options = {}) => {
  4333. const prepend = options.contains ? '' : '^';
  4334. const append = options.contains ? '' : '$';
  4335. let output = `${prepend}(?:${input})${append}`;
  4336. if (state.negated === true) {
  4337. output = `(?:^(?!${output}).*$)`;
  4338. }
  4339. return output;
  4340. };
  4341. } (utils$3));
  4342. const utils$2 = utils$3;
  4343. const {
  4344. CHAR_ASTERISK, /* * */
  4345. CHAR_AT, /* @ */
  4346. CHAR_BACKWARD_SLASH, /* \ */
  4347. CHAR_COMMA, /* , */
  4348. CHAR_DOT, /* . */
  4349. CHAR_EXCLAMATION_MARK, /* ! */
  4350. CHAR_FORWARD_SLASH, /* / */
  4351. CHAR_LEFT_CURLY_BRACE, /* { */
  4352. CHAR_LEFT_PARENTHESES, /* ( */
  4353. CHAR_LEFT_SQUARE_BRACKET, /* [ */
  4354. CHAR_PLUS, /* + */
  4355. CHAR_QUESTION_MARK, /* ? */
  4356. CHAR_RIGHT_CURLY_BRACE, /* } */
  4357. CHAR_RIGHT_PARENTHESES, /* ) */
  4358. CHAR_RIGHT_SQUARE_BRACKET /* ] */
  4359. } = constants$2;
  4360. const isPathSeparator = code => {
  4361. return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
  4362. };
  4363. const depth = token => {
  4364. if (token.isPrefix !== true) {
  4365. token.depth = token.isGlobstar ? Infinity : 1;
  4366. }
  4367. };
  4368. /**
  4369. * Quickly scans a glob pattern and returns an object with a handful of
  4370. * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
  4371. * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
  4372. * with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
  4373. *
  4374. * ```js
  4375. * const pm = require('picomatch');
  4376. * console.log(pm.scan('foo/bar/*.js'));
  4377. * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
  4378. * ```
  4379. * @param {String} `str`
  4380. * @param {Object} `options`
  4381. * @return {Object} Returns an object with tokens and regex source string.
  4382. * @api public
  4383. */
  4384. const scan$1 = (input, options) => {
  4385. const opts = options || {};
  4386. const length = input.length - 1;
  4387. const scanToEnd = opts.parts === true || opts.scanToEnd === true;
  4388. const slashes = [];
  4389. const tokens = [];
  4390. const parts = [];
  4391. let str = input;
  4392. let index = -1;
  4393. let start = 0;
  4394. let lastIndex = 0;
  4395. let isBrace = false;
  4396. let isBracket = false;
  4397. let isGlob = false;
  4398. let isExtglob = false;
  4399. let isGlobstar = false;
  4400. let braceEscaped = false;
  4401. let backslashes = false;
  4402. let negated = false;
  4403. let negatedExtglob = false;
  4404. let finished = false;
  4405. let braces = 0;
  4406. let prev;
  4407. let code;
  4408. let token = { value: '', depth: 0, isGlob: false };
  4409. const eos = () => index >= length;
  4410. const peek = () => str.charCodeAt(index + 1);
  4411. const advance = () => {
  4412. prev = code;
  4413. return str.charCodeAt(++index);
  4414. };
  4415. while (index < length) {
  4416. code = advance();
  4417. let next;
  4418. if (code === CHAR_BACKWARD_SLASH) {
  4419. backslashes = token.backslashes = true;
  4420. code = advance();
  4421. if (code === CHAR_LEFT_CURLY_BRACE) {
  4422. braceEscaped = true;
  4423. }
  4424. continue;
  4425. }
  4426. if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
  4427. braces++;
  4428. while (eos() !== true && (code = advance())) {
  4429. if (code === CHAR_BACKWARD_SLASH) {
  4430. backslashes = token.backslashes = true;
  4431. advance();
  4432. continue;
  4433. }
  4434. if (code === CHAR_LEFT_CURLY_BRACE) {
  4435. braces++;
  4436. continue;
  4437. }
  4438. if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
  4439. isBrace = token.isBrace = true;
  4440. isGlob = token.isGlob = true;
  4441. finished = true;
  4442. if (scanToEnd === true) {
  4443. continue;
  4444. }
  4445. break;
  4446. }
  4447. if (braceEscaped !== true && code === CHAR_COMMA) {
  4448. isBrace = token.isBrace = true;
  4449. isGlob = token.isGlob = true;
  4450. finished = true;
  4451. if (scanToEnd === true) {
  4452. continue;
  4453. }
  4454. break;
  4455. }
  4456. if (code === CHAR_RIGHT_CURLY_BRACE) {
  4457. braces--;
  4458. if (braces === 0) {
  4459. braceEscaped = false;
  4460. isBrace = token.isBrace = true;
  4461. finished = true;
  4462. break;
  4463. }
  4464. }
  4465. }
  4466. if (scanToEnd === true) {
  4467. continue;
  4468. }
  4469. break;
  4470. }
  4471. if (code === CHAR_FORWARD_SLASH) {
  4472. slashes.push(index);
  4473. tokens.push(token);
  4474. token = { value: '', depth: 0, isGlob: false };
  4475. if (finished === true) continue;
  4476. if (prev === CHAR_DOT && index === (start + 1)) {
  4477. start += 2;
  4478. continue;
  4479. }
  4480. lastIndex = index + 1;
  4481. continue;
  4482. }
  4483. if (opts.noext !== true) {
  4484. const isExtglobChar = code === CHAR_PLUS
  4485. || code === CHAR_AT
  4486. || code === CHAR_ASTERISK
  4487. || code === CHAR_QUESTION_MARK
  4488. || code === CHAR_EXCLAMATION_MARK;
  4489. if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
  4490. isGlob = token.isGlob = true;
  4491. isExtglob = token.isExtglob = true;
  4492. finished = true;
  4493. if (code === CHAR_EXCLAMATION_MARK && index === start) {
  4494. negatedExtglob = true;
  4495. }
  4496. if (scanToEnd === true) {
  4497. while (eos() !== true && (code = advance())) {
  4498. if (code === CHAR_BACKWARD_SLASH) {
  4499. backslashes = token.backslashes = true;
  4500. code = advance();
  4501. continue;
  4502. }
  4503. if (code === CHAR_RIGHT_PARENTHESES) {
  4504. isGlob = token.isGlob = true;
  4505. finished = true;
  4506. break;
  4507. }
  4508. }
  4509. continue;
  4510. }
  4511. break;
  4512. }
  4513. }
  4514. if (code === CHAR_ASTERISK) {
  4515. if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
  4516. isGlob = token.isGlob = true;
  4517. finished = true;
  4518. if (scanToEnd === true) {
  4519. continue;
  4520. }
  4521. break;
  4522. }
  4523. if (code === CHAR_QUESTION_MARK) {
  4524. isGlob = token.isGlob = true;
  4525. finished = true;
  4526. if (scanToEnd === true) {
  4527. continue;
  4528. }
  4529. break;
  4530. }
  4531. if (code === CHAR_LEFT_SQUARE_BRACKET) {
  4532. while (eos() !== true && (next = advance())) {
  4533. if (next === CHAR_BACKWARD_SLASH) {
  4534. backslashes = token.backslashes = true;
  4535. advance();
  4536. continue;
  4537. }
  4538. if (next === CHAR_RIGHT_SQUARE_BRACKET) {
  4539. isBracket = token.isBracket = true;
  4540. isGlob = token.isGlob = true;
  4541. finished = true;
  4542. break;
  4543. }
  4544. }
  4545. if (scanToEnd === true) {
  4546. continue;
  4547. }
  4548. break;
  4549. }
  4550. if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
  4551. negated = token.negated = true;
  4552. start++;
  4553. continue;
  4554. }
  4555. if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
  4556. isGlob = token.isGlob = true;
  4557. if (scanToEnd === true) {
  4558. while (eos() !== true && (code = advance())) {
  4559. if (code === CHAR_LEFT_PARENTHESES) {
  4560. backslashes = token.backslashes = true;
  4561. code = advance();
  4562. continue;
  4563. }
  4564. if (code === CHAR_RIGHT_PARENTHESES) {
  4565. finished = true;
  4566. break;
  4567. }
  4568. }
  4569. continue;
  4570. }
  4571. break;
  4572. }
  4573. if (isGlob === true) {
  4574. finished = true;
  4575. if (scanToEnd === true) {
  4576. continue;
  4577. }
  4578. break;
  4579. }
  4580. }
  4581. if (opts.noext === true) {
  4582. isExtglob = false;
  4583. isGlob = false;
  4584. }
  4585. let base = str;
  4586. let prefix = '';
  4587. let glob = '';
  4588. if (start > 0) {
  4589. prefix = str.slice(0, start);
  4590. str = str.slice(start);
  4591. lastIndex -= start;
  4592. }
  4593. if (base && isGlob === true && lastIndex > 0) {
  4594. base = str.slice(0, lastIndex);
  4595. glob = str.slice(lastIndex);
  4596. } else if (isGlob === true) {
  4597. base = '';
  4598. glob = str;
  4599. } else {
  4600. base = str;
  4601. }
  4602. if (base && base !== '' && base !== '/' && base !== str) {
  4603. if (isPathSeparator(base.charCodeAt(base.length - 1))) {
  4604. base = base.slice(0, -1);
  4605. }
  4606. }
  4607. if (opts.unescape === true) {
  4608. if (glob) glob = utils$2.removeBackslashes(glob);
  4609. if (base && backslashes === true) {
  4610. base = utils$2.removeBackslashes(base);
  4611. }
  4612. }
  4613. const state = {
  4614. prefix,
  4615. input,
  4616. start,
  4617. base,
  4618. glob,
  4619. isBrace,
  4620. isBracket,
  4621. isGlob,
  4622. isExtglob,
  4623. isGlobstar,
  4624. negated,
  4625. negatedExtglob
  4626. };
  4627. if (opts.tokens === true) {
  4628. state.maxDepth = 0;
  4629. if (!isPathSeparator(code)) {
  4630. tokens.push(token);
  4631. }
  4632. state.tokens = tokens;
  4633. }
  4634. if (opts.parts === true || opts.tokens === true) {
  4635. let prevIndex;
  4636. for (let idx = 0; idx < slashes.length; idx++) {
  4637. const n = prevIndex ? prevIndex + 1 : start;
  4638. const i = slashes[idx];
  4639. const value = input.slice(n, i);
  4640. if (opts.tokens) {
  4641. if (idx === 0 && start !== 0) {
  4642. tokens[idx].isPrefix = true;
  4643. tokens[idx].value = prefix;
  4644. } else {
  4645. tokens[idx].value = value;
  4646. }
  4647. depth(tokens[idx]);
  4648. state.maxDepth += tokens[idx].depth;
  4649. }
  4650. if (idx !== 0 || value !== '') {
  4651. parts.push(value);
  4652. }
  4653. prevIndex = i;
  4654. }
  4655. if (prevIndex && prevIndex + 1 < input.length) {
  4656. const value = input.slice(prevIndex + 1);
  4657. parts.push(value);
  4658. if (opts.tokens) {
  4659. tokens[tokens.length - 1].value = value;
  4660. depth(tokens[tokens.length - 1]);
  4661. state.maxDepth += tokens[tokens.length - 1].depth;
  4662. }
  4663. }
  4664. state.slashes = slashes;
  4665. state.parts = parts;
  4666. }
  4667. return state;
  4668. };
  4669. var scan_1 = scan$1;
  4670. const constants$1 = constants$2;
  4671. const utils$1 = utils$3;
  4672. /**
  4673. * Constants
  4674. */
  4675. const {
  4676. MAX_LENGTH,
  4677. POSIX_REGEX_SOURCE,
  4678. REGEX_NON_SPECIAL_CHARS,
  4679. REGEX_SPECIAL_CHARS_BACKREF,
  4680. REPLACEMENTS
  4681. } = constants$1;
  4682. /**
  4683. * Helpers
  4684. */
  4685. const expandRange = (args, options) => {
  4686. if (typeof options.expandRange === 'function') {
  4687. return options.expandRange(...args, options);
  4688. }
  4689. args.sort();
  4690. const value = `[${args.join('-')}]`;
  4691. return value;
  4692. };
  4693. /**
  4694. * Create the message for a syntax error
  4695. */
  4696. const syntaxError = (type, char) => {
  4697. return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
  4698. };
  4699. /**
  4700. * Parse the given input string.
  4701. * @param {String} input
  4702. * @param {Object} options
  4703. * @return {Object}
  4704. */
  4705. const parse$2 = (input, options) => {
  4706. if (typeof input !== 'string') {
  4707. throw new TypeError('Expected a string');
  4708. }
  4709. input = REPLACEMENTS[input] || input;
  4710. const opts = { ...options };
  4711. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  4712. let len = input.length;
  4713. if (len > max) {
  4714. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  4715. }
  4716. const bos = { type: 'bos', value: '', output: opts.prepend || '' };
  4717. const tokens = [bos];
  4718. const capture = opts.capture ? '' : '?:';
  4719. const win32 = utils$1.isWindows(options);
  4720. // create constants based on platform, for windows or posix
  4721. const PLATFORM_CHARS = constants$1.globChars(win32);
  4722. const EXTGLOB_CHARS = constants$1.extglobChars(PLATFORM_CHARS);
  4723. const {
  4724. DOT_LITERAL,
  4725. PLUS_LITERAL,
  4726. SLASH_LITERAL,
  4727. ONE_CHAR,
  4728. DOTS_SLASH,
  4729. NO_DOT,
  4730. NO_DOT_SLASH,
  4731. NO_DOTS_SLASH,
  4732. QMARK,
  4733. QMARK_NO_DOT,
  4734. STAR,
  4735. START_ANCHOR
  4736. } = PLATFORM_CHARS;
  4737. const globstar = opts => {
  4738. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  4739. };
  4740. const nodot = opts.dot ? '' : NO_DOT;
  4741. const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
  4742. let star = opts.bash === true ? globstar(opts) : STAR;
  4743. if (opts.capture) {
  4744. star = `(${star})`;
  4745. }
  4746. // minimatch options support
  4747. if (typeof opts.noext === 'boolean') {
  4748. opts.noextglob = opts.noext;
  4749. }
  4750. const state = {
  4751. input,
  4752. index: -1,
  4753. start: 0,
  4754. dot: opts.dot === true,
  4755. consumed: '',
  4756. output: '',
  4757. prefix: '',
  4758. backtrack: false,
  4759. negated: false,
  4760. brackets: 0,
  4761. braces: 0,
  4762. parens: 0,
  4763. quotes: 0,
  4764. globstar: false,
  4765. tokens
  4766. };
  4767. input = utils$1.removePrefix(input, state);
  4768. len = input.length;
  4769. const extglobs = [];
  4770. const braces = [];
  4771. const stack = [];
  4772. let prev = bos;
  4773. let value;
  4774. /**
  4775. * Tokenizing helpers
  4776. */
  4777. const eos = () => state.index === len - 1;
  4778. const peek = state.peek = (n = 1) => input[state.index + n];
  4779. const advance = state.advance = () => input[++state.index] || '';
  4780. const remaining = () => input.slice(state.index + 1);
  4781. const consume = (value = '', num = 0) => {
  4782. state.consumed += value;
  4783. state.index += num;
  4784. };
  4785. const append = token => {
  4786. state.output += token.output != null ? token.output : token.value;
  4787. consume(token.value);
  4788. };
  4789. const negate = () => {
  4790. let count = 1;
  4791. while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
  4792. advance();
  4793. state.start++;
  4794. count++;
  4795. }
  4796. if (count % 2 === 0) {
  4797. return false;
  4798. }
  4799. state.negated = true;
  4800. state.start++;
  4801. return true;
  4802. };
  4803. const increment = type => {
  4804. state[type]++;
  4805. stack.push(type);
  4806. };
  4807. const decrement = type => {
  4808. state[type]--;
  4809. stack.pop();
  4810. };
  4811. /**
  4812. * Push tokens onto the tokens array. This helper speeds up
  4813. * tokenizing by 1) helping us avoid backtracking as much as possible,
  4814. * and 2) helping us avoid creating extra tokens when consecutive
  4815. * characters are plain text. This improves performance and simplifies
  4816. * lookbehinds.
  4817. */
  4818. const push = tok => {
  4819. if (prev.type === 'globstar') {
  4820. const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
  4821. const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));
  4822. if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
  4823. state.output = state.output.slice(0, -prev.output.length);
  4824. prev.type = 'star';
  4825. prev.value = '*';
  4826. prev.output = star;
  4827. state.output += prev.output;
  4828. }
  4829. }
  4830. if (extglobs.length && tok.type !== 'paren') {
  4831. extglobs[extglobs.length - 1].inner += tok.value;
  4832. }
  4833. if (tok.value || tok.output) append(tok);
  4834. if (prev && prev.type === 'text' && tok.type === 'text') {
  4835. prev.value += tok.value;
  4836. prev.output = (prev.output || '') + tok.value;
  4837. return;
  4838. }
  4839. tok.prev = prev;
  4840. tokens.push(tok);
  4841. prev = tok;
  4842. };
  4843. const extglobOpen = (type, value) => {
  4844. const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };
  4845. token.prev = prev;
  4846. token.parens = state.parens;
  4847. token.output = state.output;
  4848. const output = (opts.capture ? '(' : '') + token.open;
  4849. increment('parens');
  4850. push({ type, value, output: state.output ? '' : ONE_CHAR });
  4851. push({ type: 'paren', extglob: true, value: advance(), output });
  4852. extglobs.push(token);
  4853. };
  4854. const extglobClose = token => {
  4855. let output = token.close + (opts.capture ? ')' : '');
  4856. let rest;
  4857. if (token.type === 'negate') {
  4858. let extglobStar = star;
  4859. if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
  4860. extglobStar = globstar(opts);
  4861. }
  4862. if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
  4863. output = token.close = `)$))${extglobStar}`;
  4864. }
  4865. if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
  4866. // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis.
  4867. // In this case, we need to parse the string and use it in the output of the original pattern.
  4868. // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`.
  4869. //
  4870. // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`.
  4871. const expression = parse$2(rest, { ...options, fastpaths: false }).output;
  4872. output = token.close = `)${expression})${extglobStar})`;
  4873. }
  4874. if (token.prev.type === 'bos') {
  4875. state.negatedExtglob = true;
  4876. }
  4877. }
  4878. push({ type: 'paren', extglob: true, value, output });
  4879. decrement('parens');
  4880. };
  4881. /**
  4882. * Fast paths
  4883. */
  4884. if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
  4885. let backslashes = false;
  4886. let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
  4887. if (first === '\\') {
  4888. backslashes = true;
  4889. return m;
  4890. }
  4891. if (first === '?') {
  4892. if (esc) {
  4893. return esc + first + (rest ? QMARK.repeat(rest.length) : '');
  4894. }
  4895. if (index === 0) {
  4896. return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
  4897. }
  4898. return QMARK.repeat(chars.length);
  4899. }
  4900. if (first === '.') {
  4901. return DOT_LITERAL.repeat(chars.length);
  4902. }
  4903. if (first === '*') {
  4904. if (esc) {
  4905. return esc + first + (rest ? star : '');
  4906. }
  4907. return star;
  4908. }
  4909. return esc ? m : `\\${m}`;
  4910. });
  4911. if (backslashes === true) {
  4912. if (opts.unescape === true) {
  4913. output = output.replace(/\\/g, '');
  4914. } else {
  4915. output = output.replace(/\\+/g, m => {
  4916. return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
  4917. });
  4918. }
  4919. }
  4920. if (output === input && opts.contains === true) {
  4921. state.output = input;
  4922. return state;
  4923. }
  4924. state.output = utils$1.wrapOutput(output, state, options);
  4925. return state;
  4926. }
  4927. /**
  4928. * Tokenize input until we reach end-of-string
  4929. */
  4930. while (!eos()) {
  4931. value = advance();
  4932. if (value === '\u0000') {
  4933. continue;
  4934. }
  4935. /**
  4936. * Escaped characters
  4937. */
  4938. if (value === '\\') {
  4939. const next = peek();
  4940. if (next === '/' && opts.bash !== true) {
  4941. continue;
  4942. }
  4943. if (next === '.' || next === ';') {
  4944. continue;
  4945. }
  4946. if (!next) {
  4947. value += '\\';
  4948. push({ type: 'text', value });
  4949. continue;
  4950. }
  4951. // collapse slashes to reduce potential for exploits
  4952. const match = /^\\+/.exec(remaining());
  4953. let slashes = 0;
  4954. if (match && match[0].length > 2) {
  4955. slashes = match[0].length;
  4956. state.index += slashes;
  4957. if (slashes % 2 !== 0) {
  4958. value += '\\';
  4959. }
  4960. }
  4961. if (opts.unescape === true) {
  4962. value = advance();
  4963. } else {
  4964. value += advance();
  4965. }
  4966. if (state.brackets === 0) {
  4967. push({ type: 'text', value });
  4968. continue;
  4969. }
  4970. }
  4971. /**
  4972. * If we're inside a regex character class, continue
  4973. * until we reach the closing bracket.
  4974. */
  4975. if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
  4976. if (opts.posix !== false && value === ':') {
  4977. const inner = prev.value.slice(1);
  4978. if (inner.includes('[')) {
  4979. prev.posix = true;
  4980. if (inner.includes(':')) {
  4981. const idx = prev.value.lastIndexOf('[');
  4982. const pre = prev.value.slice(0, idx);
  4983. const rest = prev.value.slice(idx + 2);
  4984. const posix = POSIX_REGEX_SOURCE[rest];
  4985. if (posix) {
  4986. prev.value = pre + posix;
  4987. state.backtrack = true;
  4988. advance();
  4989. if (!bos.output && tokens.indexOf(prev) === 1) {
  4990. bos.output = ONE_CHAR;
  4991. }
  4992. continue;
  4993. }
  4994. }
  4995. }
  4996. }
  4997. if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
  4998. value = `\\${value}`;
  4999. }
  5000. if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
  5001. value = `\\${value}`;
  5002. }
  5003. if (opts.posix === true && value === '!' && prev.value === '[') {
  5004. value = '^';
  5005. }
  5006. prev.value += value;
  5007. append({ value });
  5008. continue;
  5009. }
  5010. /**
  5011. * If we're inside a quoted string, continue
  5012. * until we reach the closing double quote.
  5013. */
  5014. if (state.quotes === 1 && value !== '"') {
  5015. value = utils$1.escapeRegex(value);
  5016. prev.value += value;
  5017. append({ value });
  5018. continue;
  5019. }
  5020. /**
  5021. * Double quotes
  5022. */
  5023. if (value === '"') {
  5024. state.quotes = state.quotes === 1 ? 0 : 1;
  5025. if (opts.keepQuotes === true) {
  5026. push({ type: 'text', value });
  5027. }
  5028. continue;
  5029. }
  5030. /**
  5031. * Parentheses
  5032. */
  5033. if (value === '(') {
  5034. increment('parens');
  5035. push({ type: 'paren', value });
  5036. continue;
  5037. }
  5038. if (value === ')') {
  5039. if (state.parens === 0 && opts.strictBrackets === true) {
  5040. throw new SyntaxError(syntaxError('opening', '('));
  5041. }
  5042. const extglob = extglobs[extglobs.length - 1];
  5043. if (extglob && state.parens === extglob.parens + 1) {
  5044. extglobClose(extglobs.pop());
  5045. continue;
  5046. }
  5047. push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
  5048. decrement('parens');
  5049. continue;
  5050. }
  5051. /**
  5052. * Square brackets
  5053. */
  5054. if (value === '[') {
  5055. if (opts.nobracket === true || !remaining().includes(']')) {
  5056. if (opts.nobracket !== true && opts.strictBrackets === true) {
  5057. throw new SyntaxError(syntaxError('closing', ']'));
  5058. }
  5059. value = `\\${value}`;
  5060. } else {
  5061. increment('brackets');
  5062. }
  5063. push({ type: 'bracket', value });
  5064. continue;
  5065. }
  5066. if (value === ']') {
  5067. if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
  5068. push({ type: 'text', value, output: `\\${value}` });
  5069. continue;
  5070. }
  5071. if (state.brackets === 0) {
  5072. if (opts.strictBrackets === true) {
  5073. throw new SyntaxError(syntaxError('opening', '['));
  5074. }
  5075. push({ type: 'text', value, output: `\\${value}` });
  5076. continue;
  5077. }
  5078. decrement('brackets');
  5079. const prevValue = prev.value.slice(1);
  5080. if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
  5081. value = `/${value}`;
  5082. }
  5083. prev.value += value;
  5084. append({ value });
  5085. // when literal brackets are explicitly disabled
  5086. // assume we should match with a regex character class
  5087. if (opts.literalBrackets === false || utils$1.hasRegexChars(prevValue)) {
  5088. continue;
  5089. }
  5090. const escaped = utils$1.escapeRegex(prev.value);
  5091. state.output = state.output.slice(0, -prev.value.length);
  5092. // when literal brackets are explicitly enabled
  5093. // assume we should escape the brackets to match literal characters
  5094. if (opts.literalBrackets === true) {
  5095. state.output += escaped;
  5096. prev.value = escaped;
  5097. continue;
  5098. }
  5099. // when the user specifies nothing, try to match both
  5100. prev.value = `(${capture}${escaped}|${prev.value})`;
  5101. state.output += prev.value;
  5102. continue;
  5103. }
  5104. /**
  5105. * Braces
  5106. */
  5107. if (value === '{' && opts.nobrace !== true) {
  5108. increment('braces');
  5109. const open = {
  5110. type: 'brace',
  5111. value,
  5112. output: '(',
  5113. outputIndex: state.output.length,
  5114. tokensIndex: state.tokens.length
  5115. };
  5116. braces.push(open);
  5117. push(open);
  5118. continue;
  5119. }
  5120. if (value === '}') {
  5121. const brace = braces[braces.length - 1];
  5122. if (opts.nobrace === true || !brace) {
  5123. push({ type: 'text', value, output: value });
  5124. continue;
  5125. }
  5126. let output = ')';
  5127. if (brace.dots === true) {
  5128. const arr = tokens.slice();
  5129. const range = [];
  5130. for (let i = arr.length - 1; i >= 0; i--) {
  5131. tokens.pop();
  5132. if (arr[i].type === 'brace') {
  5133. break;
  5134. }
  5135. if (arr[i].type !== 'dots') {
  5136. range.unshift(arr[i].value);
  5137. }
  5138. }
  5139. output = expandRange(range, opts);
  5140. state.backtrack = true;
  5141. }
  5142. if (brace.comma !== true && brace.dots !== true) {
  5143. const out = state.output.slice(0, brace.outputIndex);
  5144. const toks = state.tokens.slice(brace.tokensIndex);
  5145. brace.value = brace.output = '\\{';
  5146. value = output = '\\}';
  5147. state.output = out;
  5148. for (const t of toks) {
  5149. state.output += (t.output || t.value);
  5150. }
  5151. }
  5152. push({ type: 'brace', value, output });
  5153. decrement('braces');
  5154. braces.pop();
  5155. continue;
  5156. }
  5157. /**
  5158. * Pipes
  5159. */
  5160. if (value === '|') {
  5161. if (extglobs.length > 0) {
  5162. extglobs[extglobs.length - 1].conditions++;
  5163. }
  5164. push({ type: 'text', value });
  5165. continue;
  5166. }
  5167. /**
  5168. * Commas
  5169. */
  5170. if (value === ',') {
  5171. let output = value;
  5172. const brace = braces[braces.length - 1];
  5173. if (brace && stack[stack.length - 1] === 'braces') {
  5174. brace.comma = true;
  5175. output = '|';
  5176. }
  5177. push({ type: 'comma', value, output });
  5178. continue;
  5179. }
  5180. /**
  5181. * Slashes
  5182. */
  5183. if (value === '/') {
  5184. // if the beginning of the glob is "./", advance the start
  5185. // to the current index, and don't add the "./" characters
  5186. // to the state. This greatly simplifies lookbehinds when
  5187. // checking for BOS characters like "!" and "." (not "./")
  5188. if (prev.type === 'dot' && state.index === state.start + 1) {
  5189. state.start = state.index + 1;
  5190. state.consumed = '';
  5191. state.output = '';
  5192. tokens.pop();
  5193. prev = bos; // reset "prev" to the first token
  5194. continue;
  5195. }
  5196. push({ type: 'slash', value, output: SLASH_LITERAL });
  5197. continue;
  5198. }
  5199. /**
  5200. * Dots
  5201. */
  5202. if (value === '.') {
  5203. if (state.braces > 0 && prev.type === 'dot') {
  5204. if (prev.value === '.') prev.output = DOT_LITERAL;
  5205. const brace = braces[braces.length - 1];
  5206. prev.type = 'dots';
  5207. prev.output += value;
  5208. prev.value += value;
  5209. brace.dots = true;
  5210. continue;
  5211. }
  5212. if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
  5213. push({ type: 'text', value, output: DOT_LITERAL });
  5214. continue;
  5215. }
  5216. push({ type: 'dot', value, output: DOT_LITERAL });
  5217. continue;
  5218. }
  5219. /**
  5220. * Question marks
  5221. */
  5222. if (value === '?') {
  5223. const isGroup = prev && prev.value === '(';
  5224. if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  5225. extglobOpen('qmark', value);
  5226. continue;
  5227. }
  5228. if (prev && prev.type === 'paren') {
  5229. const next = peek();
  5230. let output = value;
  5231. if (next === '<' && !utils$1.supportsLookbehinds()) {
  5232. throw new Error('Node.js v10 or higher is required for regex lookbehinds');
  5233. }
  5234. if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {
  5235. output = `\\${value}`;
  5236. }
  5237. push({ type: 'text', value, output });
  5238. continue;
  5239. }
  5240. if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
  5241. push({ type: 'qmark', value, output: QMARK_NO_DOT });
  5242. continue;
  5243. }
  5244. push({ type: 'qmark', value, output: QMARK });
  5245. continue;
  5246. }
  5247. /**
  5248. * Exclamation
  5249. */
  5250. if (value === '!') {
  5251. if (opts.noextglob !== true && peek() === '(') {
  5252. if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
  5253. extglobOpen('negate', value);
  5254. continue;
  5255. }
  5256. }
  5257. if (opts.nonegate !== true && state.index === 0) {
  5258. negate();
  5259. continue;
  5260. }
  5261. }
  5262. /**
  5263. * Plus
  5264. */
  5265. if (value === '+') {
  5266. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  5267. extglobOpen('plus', value);
  5268. continue;
  5269. }
  5270. if ((prev && prev.value === '(') || opts.regex === false) {
  5271. push({ type: 'plus', value, output: PLUS_LITERAL });
  5272. continue;
  5273. }
  5274. if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {
  5275. push({ type: 'plus', value });
  5276. continue;
  5277. }
  5278. push({ type: 'plus', value: PLUS_LITERAL });
  5279. continue;
  5280. }
  5281. /**
  5282. * Plain text
  5283. */
  5284. if (value === '@') {
  5285. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  5286. push({ type: 'at', extglob: true, value, output: '' });
  5287. continue;
  5288. }
  5289. push({ type: 'text', value });
  5290. continue;
  5291. }
  5292. /**
  5293. * Plain text
  5294. */
  5295. if (value !== '*') {
  5296. if (value === '$' || value === '^') {
  5297. value = `\\${value}`;
  5298. }
  5299. const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
  5300. if (match) {
  5301. value += match[0];
  5302. state.index += match[0].length;
  5303. }
  5304. push({ type: 'text', value });
  5305. continue;
  5306. }
  5307. /**
  5308. * Stars
  5309. */
  5310. if (prev && (prev.type === 'globstar' || prev.star === true)) {
  5311. prev.type = 'star';
  5312. prev.star = true;
  5313. prev.value += value;
  5314. prev.output = star;
  5315. state.backtrack = true;
  5316. state.globstar = true;
  5317. consume(value);
  5318. continue;
  5319. }
  5320. let rest = remaining();
  5321. if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
  5322. extglobOpen('star', value);
  5323. continue;
  5324. }
  5325. if (prev.type === 'star') {
  5326. if (opts.noglobstar === true) {
  5327. consume(value);
  5328. continue;
  5329. }
  5330. const prior = prev.prev;
  5331. const before = prior.prev;
  5332. const isStart = prior.type === 'slash' || prior.type === 'bos';
  5333. const afterStar = before && (before.type === 'star' || before.type === 'globstar');
  5334. if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {
  5335. push({ type: 'star', value, output: '' });
  5336. continue;
  5337. }
  5338. const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
  5339. const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
  5340. if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
  5341. push({ type: 'star', value, output: '' });
  5342. continue;
  5343. }
  5344. // strip consecutive `/**/`
  5345. while (rest.slice(0, 3) === '/**') {
  5346. const after = input[state.index + 4];
  5347. if (after && after !== '/') {
  5348. break;
  5349. }
  5350. rest = rest.slice(3);
  5351. consume('/**', 3);
  5352. }
  5353. if (prior.type === 'bos' && eos()) {
  5354. prev.type = 'globstar';
  5355. prev.value += value;
  5356. prev.output = globstar(opts);
  5357. state.output = prev.output;
  5358. state.globstar = true;
  5359. consume(value);
  5360. continue;
  5361. }
  5362. if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
  5363. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  5364. prior.output = `(?:${prior.output}`;
  5365. prev.type = 'globstar';
  5366. prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
  5367. prev.value += value;
  5368. state.globstar = true;
  5369. state.output += prior.output + prev.output;
  5370. consume(value);
  5371. continue;
  5372. }
  5373. if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
  5374. const end = rest[1] !== void 0 ? '|$' : '';
  5375. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  5376. prior.output = `(?:${prior.output}`;
  5377. prev.type = 'globstar';
  5378. prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
  5379. prev.value += value;
  5380. state.output += prior.output + prev.output;
  5381. state.globstar = true;
  5382. consume(value + advance());
  5383. push({ type: 'slash', value: '/', output: '' });
  5384. continue;
  5385. }
  5386. if (prior.type === 'bos' && rest[0] === '/') {
  5387. prev.type = 'globstar';
  5388. prev.value += value;
  5389. prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
  5390. state.output = prev.output;
  5391. state.globstar = true;
  5392. consume(value + advance());
  5393. push({ type: 'slash', value: '/', output: '' });
  5394. continue;
  5395. }
  5396. // remove single star from output
  5397. state.output = state.output.slice(0, -prev.output.length);
  5398. // reset previous token to globstar
  5399. prev.type = 'globstar';
  5400. prev.output = globstar(opts);
  5401. prev.value += value;
  5402. // reset output with globstar
  5403. state.output += prev.output;
  5404. state.globstar = true;
  5405. consume(value);
  5406. continue;
  5407. }
  5408. const token = { type: 'star', value, output: star };
  5409. if (opts.bash === true) {
  5410. token.output = '.*?';
  5411. if (prev.type === 'bos' || prev.type === 'slash') {
  5412. token.output = nodot + token.output;
  5413. }
  5414. push(token);
  5415. continue;
  5416. }
  5417. if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
  5418. token.output = value;
  5419. push(token);
  5420. continue;
  5421. }
  5422. if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
  5423. if (prev.type === 'dot') {
  5424. state.output += NO_DOT_SLASH;
  5425. prev.output += NO_DOT_SLASH;
  5426. } else if (opts.dot === true) {
  5427. state.output += NO_DOTS_SLASH;
  5428. prev.output += NO_DOTS_SLASH;
  5429. } else {
  5430. state.output += nodot;
  5431. prev.output += nodot;
  5432. }
  5433. if (peek() !== '*') {
  5434. state.output += ONE_CHAR;
  5435. prev.output += ONE_CHAR;
  5436. }
  5437. }
  5438. push(token);
  5439. }
  5440. while (state.brackets > 0) {
  5441. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
  5442. state.output = utils$1.escapeLast(state.output, '[');
  5443. decrement('brackets');
  5444. }
  5445. while (state.parens > 0) {
  5446. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
  5447. state.output = utils$1.escapeLast(state.output, '(');
  5448. decrement('parens');
  5449. }
  5450. while (state.braces > 0) {
  5451. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
  5452. state.output = utils$1.escapeLast(state.output, '{');
  5453. decrement('braces');
  5454. }
  5455. if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
  5456. push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
  5457. }
  5458. // rebuild the output if we had to backtrack at any point
  5459. if (state.backtrack === true) {
  5460. state.output = '';
  5461. for (const token of state.tokens) {
  5462. state.output += token.output != null ? token.output : token.value;
  5463. if (token.suffix) {
  5464. state.output += token.suffix;
  5465. }
  5466. }
  5467. }
  5468. return state;
  5469. };
  5470. /**
  5471. * Fast paths for creating regular expressions for common glob patterns.
  5472. * This can significantly speed up processing and has very little downside
  5473. * impact when none of the fast paths match.
  5474. */
  5475. parse$2.fastpaths = (input, options) => {
  5476. const opts = { ...options };
  5477. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  5478. const len = input.length;
  5479. if (len > max) {
  5480. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  5481. }
  5482. input = REPLACEMENTS[input] || input;
  5483. const win32 = utils$1.isWindows(options);
  5484. // create constants based on platform, for windows or posix
  5485. const {
  5486. DOT_LITERAL,
  5487. SLASH_LITERAL,
  5488. ONE_CHAR,
  5489. DOTS_SLASH,
  5490. NO_DOT,
  5491. NO_DOTS,
  5492. NO_DOTS_SLASH,
  5493. STAR,
  5494. START_ANCHOR
  5495. } = constants$1.globChars(win32);
  5496. const nodot = opts.dot ? NO_DOTS : NO_DOT;
  5497. const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
  5498. const capture = opts.capture ? '' : '?:';
  5499. const state = { negated: false, prefix: '' };
  5500. let star = opts.bash === true ? '.*?' : STAR;
  5501. if (opts.capture) {
  5502. star = `(${star})`;
  5503. }
  5504. const globstar = opts => {
  5505. if (opts.noglobstar === true) return star;
  5506. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  5507. };
  5508. const create = str => {
  5509. switch (str) {
  5510. case '*':
  5511. return `${nodot}${ONE_CHAR}${star}`;
  5512. case '.*':
  5513. return `${DOT_LITERAL}${ONE_CHAR}${star}`;
  5514. case '*.*':
  5515. return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  5516. case '*/*':
  5517. return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
  5518. case '**':
  5519. return nodot + globstar(opts);
  5520. case '**/*':
  5521. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
  5522. case '**/*.*':
  5523. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  5524. case '**/.*':
  5525. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
  5526. default: {
  5527. const match = /^(.*?)\.(\w+)$/.exec(str);
  5528. if (!match) return;
  5529. const source = create(match[1]);
  5530. if (!source) return;
  5531. return source + DOT_LITERAL + match[2];
  5532. }
  5533. }
  5534. };
  5535. const output = utils$1.removePrefix(input, state);
  5536. let source = create(output);
  5537. if (source && opts.strictSlashes !== true) {
  5538. source += `${SLASH_LITERAL}?`;
  5539. }
  5540. return source;
  5541. };
  5542. var parse_1 = parse$2;
  5543. const path = require$$0$1;
  5544. const scan = scan_1;
  5545. const parse$1 = parse_1;
  5546. const utils = utils$3;
  5547. const constants = constants$2;
  5548. const isObject = val => val && typeof val === 'object' && !Array.isArray(val);
  5549. /**
  5550. * Creates a matcher function from one or more glob patterns. The
  5551. * returned function takes a string to match as its first argument,
  5552. * and returns true if the string is a match. The returned matcher
  5553. * function also takes a boolean as the second argument that, when true,
  5554. * returns an object with additional information.
  5555. *
  5556. * ```js
  5557. * const picomatch = require('picomatch');
  5558. * // picomatch(glob[, options]);
  5559. *
  5560. * const isMatch = picomatch('*.!(*a)');
  5561. * console.log(isMatch('a.a')); //=> false
  5562. * console.log(isMatch('a.b')); //=> true
  5563. * ```
  5564. * @name picomatch
  5565. * @param {String|Array} `globs` One or more glob patterns.
  5566. * @param {Object=} `options`
  5567. * @return {Function=} Returns a matcher function.
  5568. * @api public
  5569. */
  5570. const picomatch$1 = (glob, options, returnState = false) => {
  5571. if (Array.isArray(glob)) {
  5572. const fns = glob.map(input => picomatch$1(input, options, returnState));
  5573. const arrayMatcher = str => {
  5574. for (const isMatch of fns) {
  5575. const state = isMatch(str);
  5576. if (state) return state;
  5577. }
  5578. return false;
  5579. };
  5580. return arrayMatcher;
  5581. }
  5582. const isState = isObject(glob) && glob.tokens && glob.input;
  5583. if (glob === '' || (typeof glob !== 'string' && !isState)) {
  5584. throw new TypeError('Expected pattern to be a non-empty string');
  5585. }
  5586. const opts = options || {};
  5587. const posix = utils.isWindows(options);
  5588. const regex = isState
  5589. ? picomatch$1.compileRe(glob, options)
  5590. : picomatch$1.makeRe(glob, options, false, true);
  5591. const state = regex.state;
  5592. delete regex.state;
  5593. let isIgnored = () => false;
  5594. if (opts.ignore) {
  5595. const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
  5596. isIgnored = picomatch$1(opts.ignore, ignoreOpts, returnState);
  5597. }
  5598. const matcher = (input, returnObject = false) => {
  5599. const { isMatch, match, output } = picomatch$1.test(input, regex, options, { glob, posix });
  5600. const result = { glob, state, regex, posix, input, output, match, isMatch };
  5601. if (typeof opts.onResult === 'function') {
  5602. opts.onResult(result);
  5603. }
  5604. if (isMatch === false) {
  5605. result.isMatch = false;
  5606. return returnObject ? result : false;
  5607. }
  5608. if (isIgnored(input)) {
  5609. if (typeof opts.onIgnore === 'function') {
  5610. opts.onIgnore(result);
  5611. }
  5612. result.isMatch = false;
  5613. return returnObject ? result : false;
  5614. }
  5615. if (typeof opts.onMatch === 'function') {
  5616. opts.onMatch(result);
  5617. }
  5618. return returnObject ? result : true;
  5619. };
  5620. if (returnState) {
  5621. matcher.state = state;
  5622. }
  5623. return matcher;
  5624. };
  5625. /**
  5626. * Test `input` with the given `regex`. This is used by the main
  5627. * `picomatch()` function to test the input string.
  5628. *
  5629. * ```js
  5630. * const picomatch = require('picomatch');
  5631. * // picomatch.test(input, regex[, options]);
  5632. *
  5633. * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
  5634. * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
  5635. * ```
  5636. * @param {String} `input` String to test.
  5637. * @param {RegExp} `regex`
  5638. * @return {Object} Returns an object with matching info.
  5639. * @api public
  5640. */
  5641. picomatch$1.test = (input, regex, options, { glob, posix } = {}) => {
  5642. if (typeof input !== 'string') {
  5643. throw new TypeError('Expected input to be a string');
  5644. }
  5645. if (input === '') {
  5646. return { isMatch: false, output: '' };
  5647. }
  5648. const opts = options || {};
  5649. const format = opts.format || (posix ? utils.toPosixSlashes : null);
  5650. let match = input === glob;
  5651. let output = (match && format) ? format(input) : input;
  5652. if (match === false) {
  5653. output = format ? format(input) : input;
  5654. match = output === glob;
  5655. }
  5656. if (match === false || opts.capture === true) {
  5657. if (opts.matchBase === true || opts.basename === true) {
  5658. match = picomatch$1.matchBase(input, regex, options, posix);
  5659. } else {
  5660. match = regex.exec(output);
  5661. }
  5662. }
  5663. return { isMatch: Boolean(match), match, output };
  5664. };
  5665. /**
  5666. * Match the basename of a filepath.
  5667. *
  5668. * ```js
  5669. * const picomatch = require('picomatch');
  5670. * // picomatch.matchBase(input, glob[, options]);
  5671. * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
  5672. * ```
  5673. * @param {String} `input` String to test.
  5674. * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
  5675. * @return {Boolean}
  5676. * @api public
  5677. */
  5678. picomatch$1.matchBase = (input, glob, options, posix = utils.isWindows(options)) => {
  5679. const regex = glob instanceof RegExp ? glob : picomatch$1.makeRe(glob, options);
  5680. return regex.test(path.basename(input));
  5681. };
  5682. /**
  5683. * Returns true if **any** of the given glob `patterns` match the specified `string`.
  5684. *
  5685. * ```js
  5686. * const picomatch = require('picomatch');
  5687. * // picomatch.isMatch(string, patterns[, options]);
  5688. *
  5689. * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
  5690. * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
  5691. * ```
  5692. * @param {String|Array} str The string to test.
  5693. * @param {String|Array} patterns One or more glob patterns to use for matching.
  5694. * @param {Object} [options] See available [options](#options).
  5695. * @return {Boolean} Returns true if any patterns match `str`
  5696. * @api public
  5697. */
  5698. picomatch$1.isMatch = (str, patterns, options) => picomatch$1(patterns, options)(str);
  5699. /**
  5700. * Parse a glob pattern to create the source string for a regular
  5701. * expression.
  5702. *
  5703. * ```js
  5704. * const picomatch = require('picomatch');
  5705. * const result = picomatch.parse(pattern[, options]);
  5706. * ```
  5707. * @param {String} `pattern`
  5708. * @param {Object} `options`
  5709. * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
  5710. * @api public
  5711. */
  5712. picomatch$1.parse = (pattern, options) => {
  5713. if (Array.isArray(pattern)) return pattern.map(p => picomatch$1.parse(p, options));
  5714. return parse$1(pattern, { ...options, fastpaths: false });
  5715. };
  5716. /**
  5717. * Scan a glob pattern to separate the pattern into segments.
  5718. *
  5719. * ```js
  5720. * const picomatch = require('picomatch');
  5721. * // picomatch.scan(input[, options]);
  5722. *
  5723. * const result = picomatch.scan('!./foo/*.js');
  5724. * console.log(result);
  5725. * { prefix: '!./',
  5726. * input: '!./foo/*.js',
  5727. * start: 3,
  5728. * base: 'foo',
  5729. * glob: '*.js',
  5730. * isBrace: false,
  5731. * isBracket: false,
  5732. * isGlob: true,
  5733. * isExtglob: false,
  5734. * isGlobstar: false,
  5735. * negated: true }
  5736. * ```
  5737. * @param {String} `input` Glob pattern to scan.
  5738. * @param {Object} `options`
  5739. * @return {Object} Returns an object with
  5740. * @api public
  5741. */
  5742. picomatch$1.scan = (input, options) => scan(input, options);
  5743. /**
  5744. * Compile a regular expression from the `state` object returned by the
  5745. * [parse()](#parse) method.
  5746. *
  5747. * @param {Object} `state`
  5748. * @param {Object} `options`
  5749. * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
  5750. * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
  5751. * @return {RegExp}
  5752. * @api public
  5753. */
  5754. picomatch$1.compileRe = (state, options, returnOutput = false, returnState = false) => {
  5755. if (returnOutput === true) {
  5756. return state.output;
  5757. }
  5758. const opts = options || {};
  5759. const prepend = opts.contains ? '' : '^';
  5760. const append = opts.contains ? '' : '$';
  5761. let source = `${prepend}(?:${state.output})${append}`;
  5762. if (state && state.negated === true) {
  5763. source = `^(?!${source}).*$`;
  5764. }
  5765. const regex = picomatch$1.toRegex(source, options);
  5766. if (returnState === true) {
  5767. regex.state = state;
  5768. }
  5769. return regex;
  5770. };
  5771. /**
  5772. * Create a regular expression from a parsed glob pattern.
  5773. *
  5774. * ```js
  5775. * const picomatch = require('picomatch');
  5776. * const state = picomatch.parse('*.js');
  5777. * // picomatch.compileRe(state[, options]);
  5778. *
  5779. * console.log(picomatch.compileRe(state));
  5780. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  5781. * ```
  5782. * @param {String} `state` The object returned from the `.parse` method.
  5783. * @param {Object} `options`
  5784. * @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.
  5785. * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
  5786. * @return {RegExp} Returns a regex created from the given pattern.
  5787. * @api public
  5788. */
  5789. picomatch$1.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
  5790. if (!input || typeof input !== 'string') {
  5791. throw new TypeError('Expected a non-empty string');
  5792. }
  5793. let parsed = { negated: false, fastpaths: true };
  5794. if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
  5795. parsed.output = parse$1.fastpaths(input, options);
  5796. }
  5797. if (!parsed.output) {
  5798. parsed = parse$1(input, options);
  5799. }
  5800. return picomatch$1.compileRe(parsed, options, returnOutput, returnState);
  5801. };
  5802. /**
  5803. * Create a regular expression from the given regex source string.
  5804. *
  5805. * ```js
  5806. * const picomatch = require('picomatch');
  5807. * // picomatch.toRegex(source[, options]);
  5808. *
  5809. * const { output } = picomatch.parse('*.js');
  5810. * console.log(picomatch.toRegex(output));
  5811. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  5812. * ```
  5813. * @param {String} `source` Regular expression source string.
  5814. * @param {Object} `options`
  5815. * @return {RegExp}
  5816. * @api public
  5817. */
  5818. picomatch$1.toRegex = (source, options) => {
  5819. try {
  5820. const opts = options || {};
  5821. return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
  5822. } catch (err) {
  5823. if (options && options.debug === true) throw err;
  5824. return /$^/;
  5825. }
  5826. };
  5827. /**
  5828. * Picomatch constants.
  5829. * @return {Object}
  5830. */
  5831. picomatch$1.constants = constants;
  5832. /**
  5833. * Expose "picomatch"
  5834. */
  5835. var picomatch_1 = picomatch$1;
  5836. var picomatch = picomatch_1;
  5837. const pm = /*@__PURE__*/getDefaultExportFromCjs(picomatch);
  5838. const extractors = {
  5839. ArrayPattern(names, param) {
  5840. for (const element of param.elements) {
  5841. if (element)
  5842. extractors[element.type](names, element);
  5843. }
  5844. },
  5845. AssignmentPattern(names, param) {
  5846. extractors[param.left.type](names, param.left);
  5847. },
  5848. Identifier(names, param) {
  5849. names.push(param.name);
  5850. },
  5851. MemberExpression() { },
  5852. ObjectPattern(names, param) {
  5853. for (const prop of param.properties) {
  5854. // @ts-ignore Typescript reports that this is not a valid type
  5855. if (prop.type === 'RestElement') {
  5856. extractors.RestElement(names, prop);
  5857. }
  5858. else {
  5859. extractors[prop.value.type](names, prop.value);
  5860. }
  5861. }
  5862. },
  5863. RestElement(names, param) {
  5864. extractors[param.argument.type](names, param.argument);
  5865. }
  5866. };
  5867. const extractAssignedNames = function extractAssignedNames(param) {
  5868. const names = [];
  5869. extractors[param.type](names, param);
  5870. return names;
  5871. };
  5872. // Helper since Typescript can't detect readonly arrays with Array.isArray
  5873. function isArray$1(arg) {
  5874. return Array.isArray(arg);
  5875. }
  5876. function ensureArray(thing) {
  5877. if (isArray$1(thing))
  5878. return thing;
  5879. if (thing == null)
  5880. return [];
  5881. return [thing];
  5882. }
  5883. const normalizePath = function normalizePath(filename) {
  5884. return filename.split(require$$0$1.win32.sep).join(require$$0$1.posix.sep);
  5885. };
  5886. function getMatcherString(id, resolutionBase) {
  5887. if (resolutionBase === false || require$$0$1.isAbsolute(id) || id.startsWith('**')) {
  5888. return normalizePath(id);
  5889. }
  5890. // resolve('') is valid and will default to process.cwd()
  5891. const basePath = normalizePath(require$$0$1.resolve(resolutionBase || ''))
  5892. // escape all possible (posix + win) path characters that might interfere with regex
  5893. .replace(/[-^$*+?.()|[\]{}]/g, '\\$&');
  5894. // Note that we use posix.join because:
  5895. // 1. the basePath has been normalized to use /
  5896. // 2. the incoming glob (id) matcher, also uses /
  5897. // otherwise Node will force backslash (\) on windows
  5898. return require$$0$1.posix.join(basePath, normalizePath(id));
  5899. }
  5900. const createFilter = function createFilter(include, exclude, options) {
  5901. const resolutionBase = options && options.resolve;
  5902. const getMatcher = (id) => id instanceof RegExp
  5903. ? id
  5904. : {
  5905. test: (what) => {
  5906. // this refactor is a tad overly verbose but makes for easy debugging
  5907. const pattern = getMatcherString(id, resolutionBase);
  5908. const fn = pm(pattern, { dot: true });
  5909. const result = fn(what);
  5910. return result;
  5911. }
  5912. };
  5913. const includeMatchers = ensureArray(include).map(getMatcher);
  5914. const excludeMatchers = ensureArray(exclude).map(getMatcher);
  5915. return function result(id) {
  5916. if (typeof id !== 'string')
  5917. return false;
  5918. if (/\0/.test(id))
  5919. return false;
  5920. const pathId = normalizePath(id);
  5921. for (let i = 0; i < excludeMatchers.length; ++i) {
  5922. const matcher = excludeMatchers[i];
  5923. if (matcher.test(pathId))
  5924. return false;
  5925. }
  5926. for (let i = 0; i < includeMatchers.length; ++i) {
  5927. const matcher = includeMatchers[i];
  5928. if (matcher.test(pathId))
  5929. return true;
  5930. }
  5931. return !includeMatchers.length;
  5932. };
  5933. };
  5934. 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';
  5935. 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';
  5936. const forbiddenIdentifiers = new Set(`${reservedWords$1} ${builtins}`.split(' '));
  5937. forbiddenIdentifiers.add('');
  5938. function createInclusionContext() {
  5939. return {
  5940. brokenFlow: false,
  5941. hasBreak: false,
  5942. hasContinue: false,
  5943. includedCallArguments: new Set(),
  5944. includedLabels: new Set()
  5945. };
  5946. }
  5947. function createHasEffectsContext() {
  5948. return {
  5949. accessed: new PathTracker(),
  5950. assigned: new PathTracker(),
  5951. brokenFlow: false,
  5952. called: new DiscriminatedPathTracker(),
  5953. hasBreak: false,
  5954. hasContinue: false,
  5955. ignore: {
  5956. breaks: false,
  5957. continues: false,
  5958. labels: new Set(),
  5959. returnYield: false,
  5960. this: false
  5961. },
  5962. includedLabels: new Set(),
  5963. instantiated: new DiscriminatedPathTracker(),
  5964. replacedVariableInits: new Map()
  5965. };
  5966. }
  5967. function assembleMemberDescriptions(memberDescriptions, inheritedDescriptions = null) {
  5968. return Object.create(inheritedDescriptions, memberDescriptions);
  5969. }
  5970. const UNDEFINED_EXPRESSION = new (class UndefinedExpression extends ExpressionEntity {
  5971. getLiteralValueAtPath() {
  5972. return undefined;
  5973. }
  5974. })();
  5975. const returnsUnknown = {
  5976. value: {
  5977. hasEffectsWhenCalled: null,
  5978. returns: UNKNOWN_EXPRESSION
  5979. }
  5980. };
  5981. const UNKNOWN_LITERAL_BOOLEAN = new (class UnknownBoolean extends ExpressionEntity {
  5982. getReturnExpressionWhenCalledAtPath(path) {
  5983. if (path.length === 1) {
  5984. return getMemberReturnExpressionWhenCalled(literalBooleanMembers, path[0]);
  5985. }
  5986. return UNKNOWN_RETURN_EXPRESSION;
  5987. }
  5988. hasEffectsOnInteractionAtPath(path, interaction, context) {
  5989. if (interaction.type === INTERACTION_ACCESSED) {
  5990. return path.length > 1;
  5991. }
  5992. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  5993. return hasMemberEffectWhenCalled(literalBooleanMembers, path[0], interaction, context);
  5994. }
  5995. return true;
  5996. }
  5997. })();
  5998. const returnsBoolean = {
  5999. value: {
  6000. hasEffectsWhenCalled: null,
  6001. returns: UNKNOWN_LITERAL_BOOLEAN
  6002. }
  6003. };
  6004. const UNKNOWN_LITERAL_NUMBER = new (class UnknownNumber extends ExpressionEntity {
  6005. getReturnExpressionWhenCalledAtPath(path) {
  6006. if (path.length === 1) {
  6007. return getMemberReturnExpressionWhenCalled(literalNumberMembers, path[0]);
  6008. }
  6009. return UNKNOWN_RETURN_EXPRESSION;
  6010. }
  6011. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6012. if (interaction.type === INTERACTION_ACCESSED) {
  6013. return path.length > 1;
  6014. }
  6015. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  6016. return hasMemberEffectWhenCalled(literalNumberMembers, path[0], interaction, context);
  6017. }
  6018. return true;
  6019. }
  6020. })();
  6021. const returnsNumber = {
  6022. value: {
  6023. hasEffectsWhenCalled: null,
  6024. returns: UNKNOWN_LITERAL_NUMBER
  6025. }
  6026. };
  6027. const UNKNOWN_LITERAL_STRING = new (class UnknownString extends ExpressionEntity {
  6028. getReturnExpressionWhenCalledAtPath(path) {
  6029. if (path.length === 1) {
  6030. return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
  6031. }
  6032. return UNKNOWN_RETURN_EXPRESSION;
  6033. }
  6034. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6035. if (interaction.type === INTERACTION_ACCESSED) {
  6036. return path.length > 1;
  6037. }
  6038. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  6039. return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
  6040. }
  6041. return true;
  6042. }
  6043. })();
  6044. const returnsString = {
  6045. value: {
  6046. hasEffectsWhenCalled: null,
  6047. returns: UNKNOWN_LITERAL_STRING
  6048. }
  6049. };
  6050. const stringReplace = {
  6051. value: {
  6052. hasEffectsWhenCalled({ args }, context) {
  6053. const argument1 = args[2];
  6054. return (args.length < 3 ||
  6055. (typeof argument1.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, {
  6056. deoptimizeCache() { }
  6057. }) === 'symbol' &&
  6058. argument1.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)));
  6059. },
  6060. returns: UNKNOWN_LITERAL_STRING
  6061. }
  6062. };
  6063. const objectMembers = assembleMemberDescriptions({
  6064. hasOwnProperty: returnsBoolean,
  6065. isPrototypeOf: returnsBoolean,
  6066. propertyIsEnumerable: returnsBoolean,
  6067. toLocaleString: returnsString,
  6068. toString: returnsString,
  6069. valueOf: returnsUnknown
  6070. });
  6071. const literalBooleanMembers = assembleMemberDescriptions({
  6072. valueOf: returnsBoolean
  6073. }, objectMembers);
  6074. const literalNumberMembers = assembleMemberDescriptions({
  6075. toExponential: returnsString,
  6076. toFixed: returnsString,
  6077. toLocaleString: returnsString,
  6078. toPrecision: returnsString,
  6079. valueOf: returnsNumber
  6080. }, objectMembers);
  6081. /**
  6082. * RegExp are stateful when they have the global or sticky flags set.
  6083. * But if we actually don't use them, the side effect does not matter.
  6084. * the check logic in `hasEffectsOnInteractionAtPath`.
  6085. */
  6086. const literalRegExpMembers = assembleMemberDescriptions({
  6087. exec: returnsUnknown,
  6088. test: returnsBoolean
  6089. }, objectMembers);
  6090. const literalStringMembers = assembleMemberDescriptions({
  6091. anchor: returnsString,
  6092. at: returnsUnknown,
  6093. big: returnsString,
  6094. blink: returnsString,
  6095. bold: returnsString,
  6096. charAt: returnsString,
  6097. charCodeAt: returnsNumber,
  6098. codePointAt: returnsUnknown,
  6099. concat: returnsString,
  6100. endsWith: returnsBoolean,
  6101. fixed: returnsString,
  6102. fontcolor: returnsString,
  6103. fontsize: returnsString,
  6104. includes: returnsBoolean,
  6105. indexOf: returnsNumber,
  6106. italics: returnsString,
  6107. lastIndexOf: returnsNumber,
  6108. link: returnsString,
  6109. localeCompare: returnsNumber,
  6110. match: returnsUnknown,
  6111. matchAll: returnsUnknown,
  6112. normalize: returnsString,
  6113. padEnd: returnsString,
  6114. padStart: returnsString,
  6115. repeat: returnsString,
  6116. replace: stringReplace,
  6117. replaceAll: stringReplace,
  6118. search: returnsNumber,
  6119. slice: returnsString,
  6120. small: returnsString,
  6121. split: returnsUnknown,
  6122. startsWith: returnsBoolean,
  6123. strike: returnsString,
  6124. sub: returnsString,
  6125. substr: returnsString,
  6126. substring: returnsString,
  6127. sup: returnsString,
  6128. toLocaleLowerCase: returnsString,
  6129. toLocaleUpperCase: returnsString,
  6130. toLowerCase: returnsString,
  6131. toString: returnsString,
  6132. toUpperCase: returnsString,
  6133. trim: returnsString,
  6134. trimEnd: returnsString,
  6135. trimLeft: returnsString,
  6136. trimRight: returnsString,
  6137. trimStart: returnsString,
  6138. valueOf: returnsString
  6139. }, objectMembers);
  6140. function getLiteralMembersForValue(value) {
  6141. if (value instanceof RegExp) {
  6142. return literalRegExpMembers;
  6143. }
  6144. switch (typeof value) {
  6145. case 'boolean': {
  6146. return literalBooleanMembers;
  6147. }
  6148. case 'number': {
  6149. return literalNumberMembers;
  6150. }
  6151. case 'string': {
  6152. return literalStringMembers;
  6153. }
  6154. }
  6155. return Object.create(null);
  6156. }
  6157. function hasMemberEffectWhenCalled(members, memberName, interaction, context) {
  6158. if (typeof memberName !== 'string' || !members[memberName]) {
  6159. return true;
  6160. }
  6161. return members[memberName].hasEffectsWhenCalled?.(interaction, context) || false;
  6162. }
  6163. function getMemberReturnExpressionWhenCalled(members, memberName) {
  6164. if (typeof memberName !== 'string' || !members[memberName])
  6165. return UNKNOWN_RETURN_EXPRESSION;
  6166. return [members[memberName].returns, false];
  6167. }
  6168. // AST walker module for Mozilla Parser API compatible trees
  6169. function skipThrough(node, st, c) { c(node, st); }
  6170. function ignore(_node, _st, _c) {}
  6171. // Node walkers.
  6172. var base = {};
  6173. base.Program = base.BlockStatement = base.StaticBlock = function (node, st, c) {
  6174. for (var i = 0, list = node.body; i < list.length; i += 1)
  6175. {
  6176. var stmt = list[i];
  6177. c(stmt, st, "Statement");
  6178. }
  6179. };
  6180. base.Statement = skipThrough;
  6181. base.EmptyStatement = ignore;
  6182. base.ExpressionStatement = base.ParenthesizedExpression = base.ChainExpression =
  6183. function (node, st, c) { return c(node.expression, st, "Expression"); };
  6184. base.IfStatement = function (node, st, c) {
  6185. c(node.test, st, "Expression");
  6186. c(node.consequent, st, "Statement");
  6187. if (node.alternate) { c(node.alternate, st, "Statement"); }
  6188. };
  6189. base.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); };
  6190. base.BreakStatement = base.ContinueStatement = ignore;
  6191. base.WithStatement = function (node, st, c) {
  6192. c(node.object, st, "Expression");
  6193. c(node.body, st, "Statement");
  6194. };
  6195. base.SwitchStatement = function (node, st, c) {
  6196. c(node.discriminant, st, "Expression");
  6197. for (var i$1 = 0, list$1 = node.cases; i$1 < list$1.length; i$1 += 1) {
  6198. var cs = list$1[i$1];
  6199. if (cs.test) { c(cs.test, st, "Expression"); }
  6200. for (var i = 0, list = cs.consequent; i < list.length; i += 1)
  6201. {
  6202. var cons = list[i];
  6203. c(cons, st, "Statement");
  6204. }
  6205. }
  6206. };
  6207. base.SwitchCase = function (node, st, c) {
  6208. if (node.test) { c(node.test, st, "Expression"); }
  6209. for (var i = 0, list = node.consequent; i < list.length; i += 1)
  6210. {
  6211. var cons = list[i];
  6212. c(cons, st, "Statement");
  6213. }
  6214. };
  6215. base.ReturnStatement = base.YieldExpression = base.AwaitExpression = function (node, st, c) {
  6216. if (node.argument) { c(node.argument, st, "Expression"); }
  6217. };
  6218. base.ThrowStatement = base.SpreadElement =
  6219. function (node, st, c) { return c(node.argument, st, "Expression"); };
  6220. base.TryStatement = function (node, st, c) {
  6221. c(node.block, st, "Statement");
  6222. if (node.handler) { c(node.handler, st); }
  6223. if (node.finalizer) { c(node.finalizer, st, "Statement"); }
  6224. };
  6225. base.CatchClause = function (node, st, c) {
  6226. if (node.param) { c(node.param, st, "Pattern"); }
  6227. c(node.body, st, "Statement");
  6228. };
  6229. base.WhileStatement = base.DoWhileStatement = function (node, st, c) {
  6230. c(node.test, st, "Expression");
  6231. c(node.body, st, "Statement");
  6232. };
  6233. base.ForStatement = function (node, st, c) {
  6234. if (node.init) { c(node.init, st, "ForInit"); }
  6235. if (node.test) { c(node.test, st, "Expression"); }
  6236. if (node.update) { c(node.update, st, "Expression"); }
  6237. c(node.body, st, "Statement");
  6238. };
  6239. base.ForInStatement = base.ForOfStatement = function (node, st, c) {
  6240. c(node.left, st, "ForInit");
  6241. c(node.right, st, "Expression");
  6242. c(node.body, st, "Statement");
  6243. };
  6244. base.ForInit = function (node, st, c) {
  6245. if (node.type === "VariableDeclaration") { c(node, st); }
  6246. else { c(node, st, "Expression"); }
  6247. };
  6248. base.DebuggerStatement = ignore;
  6249. base.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); };
  6250. base.VariableDeclaration = function (node, st, c) {
  6251. for (var i = 0, list = node.declarations; i < list.length; i += 1)
  6252. {
  6253. var decl = list[i];
  6254. c(decl, st);
  6255. }
  6256. };
  6257. base.VariableDeclarator = function (node, st, c) {
  6258. c(node.id, st, "Pattern");
  6259. if (node.init) { c(node.init, st, "Expression"); }
  6260. };
  6261. base.Function = function (node, st, c) {
  6262. if (node.id) { c(node.id, st, "Pattern"); }
  6263. for (var i = 0, list = node.params; i < list.length; i += 1)
  6264. {
  6265. var param = list[i];
  6266. c(param, st, "Pattern");
  6267. }
  6268. c(node.body, st, node.expression ? "Expression" : "Statement");
  6269. };
  6270. base.Pattern = function (node, st, c) {
  6271. if (node.type === "Identifier")
  6272. { c(node, st, "VariablePattern"); }
  6273. else if (node.type === "MemberExpression")
  6274. { c(node, st, "MemberPattern"); }
  6275. else
  6276. { c(node, st); }
  6277. };
  6278. base.VariablePattern = ignore;
  6279. base.MemberPattern = skipThrough;
  6280. base.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); };
  6281. base.ArrayPattern = function (node, st, c) {
  6282. for (var i = 0, list = node.elements; i < list.length; i += 1) {
  6283. var elt = list[i];
  6284. if (elt) { c(elt, st, "Pattern"); }
  6285. }
  6286. };
  6287. base.ObjectPattern = function (node, st, c) {
  6288. for (var i = 0, list = node.properties; i < list.length; i += 1) {
  6289. var prop = list[i];
  6290. if (prop.type === "Property") {
  6291. if (prop.computed) { c(prop.key, st, "Expression"); }
  6292. c(prop.value, st, "Pattern");
  6293. } else if (prop.type === "RestElement") {
  6294. c(prop.argument, st, "Pattern");
  6295. }
  6296. }
  6297. };
  6298. base.Expression = skipThrough;
  6299. base.ThisExpression = base.Super = base.MetaProperty = ignore;
  6300. base.ArrayExpression = function (node, st, c) {
  6301. for (var i = 0, list = node.elements; i < list.length; i += 1) {
  6302. var elt = list[i];
  6303. if (elt) { c(elt, st, "Expression"); }
  6304. }
  6305. };
  6306. base.ObjectExpression = function (node, st, c) {
  6307. for (var i = 0, list = node.properties; i < list.length; i += 1)
  6308. {
  6309. var prop = list[i];
  6310. c(prop, st);
  6311. }
  6312. };
  6313. base.FunctionExpression = base.ArrowFunctionExpression = base.FunctionDeclaration;
  6314. base.SequenceExpression = function (node, st, c) {
  6315. for (var i = 0, list = node.expressions; i < list.length; i += 1)
  6316. {
  6317. var expr = list[i];
  6318. c(expr, st, "Expression");
  6319. }
  6320. };
  6321. base.TemplateLiteral = function (node, st, c) {
  6322. for (var i = 0, list = node.quasis; i < list.length; i += 1)
  6323. {
  6324. var quasi = list[i];
  6325. c(quasi, st);
  6326. }
  6327. for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1)
  6328. {
  6329. var expr = list$1[i$1];
  6330. c(expr, st, "Expression");
  6331. }
  6332. };
  6333. base.TemplateElement = ignore;
  6334. base.UnaryExpression = base.UpdateExpression = function (node, st, c) {
  6335. c(node.argument, st, "Expression");
  6336. };
  6337. base.BinaryExpression = base.LogicalExpression = function (node, st, c) {
  6338. c(node.left, st, "Expression");
  6339. c(node.right, st, "Expression");
  6340. };
  6341. base.AssignmentExpression = base.AssignmentPattern = function (node, st, c) {
  6342. c(node.left, st, "Pattern");
  6343. c(node.right, st, "Expression");
  6344. };
  6345. base.ConditionalExpression = function (node, st, c) {
  6346. c(node.test, st, "Expression");
  6347. c(node.consequent, st, "Expression");
  6348. c(node.alternate, st, "Expression");
  6349. };
  6350. base.NewExpression = base.CallExpression = function (node, st, c) {
  6351. c(node.callee, st, "Expression");
  6352. if (node.arguments)
  6353. { for (var i = 0, list = node.arguments; i < list.length; i += 1)
  6354. {
  6355. var arg = list[i];
  6356. c(arg, st, "Expression");
  6357. } }
  6358. };
  6359. base.MemberExpression = function (node, st, c) {
  6360. c(node.object, st, "Expression");
  6361. if (node.computed) { c(node.property, st, "Expression"); }
  6362. };
  6363. base.ExportNamedDeclaration = base.ExportDefaultDeclaration = function (node, st, c) {
  6364. if (node.declaration)
  6365. { c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); }
  6366. if (node.source) { c(node.source, st, "Expression"); }
  6367. };
  6368. base.ExportAllDeclaration = function (node, st, c) {
  6369. if (node.exported)
  6370. { c(node.exported, st); }
  6371. c(node.source, st, "Expression");
  6372. };
  6373. base.ImportDeclaration = function (node, st, c) {
  6374. for (var i = 0, list = node.specifiers; i < list.length; i += 1)
  6375. {
  6376. var spec = list[i];
  6377. c(spec, st);
  6378. }
  6379. c(node.source, st, "Expression");
  6380. };
  6381. base.ImportExpression = function (node, st, c) {
  6382. c(node.source, st, "Expression");
  6383. };
  6384. base.ImportSpecifier = base.ImportDefaultSpecifier = base.ImportNamespaceSpecifier = base.Identifier = base.PrivateIdentifier = base.Literal = ignore;
  6385. base.TaggedTemplateExpression = function (node, st, c) {
  6386. c(node.tag, st, "Expression");
  6387. c(node.quasi, st, "Expression");
  6388. };
  6389. base.ClassDeclaration = base.ClassExpression = function (node, st, c) { return c(node, st, "Class"); };
  6390. base.Class = function (node, st, c) {
  6391. if (node.id) { c(node.id, st, "Pattern"); }
  6392. if (node.superClass) { c(node.superClass, st, "Expression"); }
  6393. c(node.body, st);
  6394. };
  6395. base.ClassBody = function (node, st, c) {
  6396. for (var i = 0, list = node.body; i < list.length; i += 1)
  6397. {
  6398. var elt = list[i];
  6399. c(elt, st);
  6400. }
  6401. };
  6402. base.MethodDefinition = base.PropertyDefinition = base.Property = function (node, st, c) {
  6403. if (node.computed) { c(node.key, st, "Expression"); }
  6404. if (node.value) { c(node.value, st, "Expression"); }
  6405. };
  6406. const ArrowFunctionExpression$1 = 'ArrowFunctionExpression';
  6407. const BinaryExpression$1 = 'BinaryExpression';
  6408. const BlockStatement$1 = 'BlockStatement';
  6409. const CallExpression$1 = 'CallExpression';
  6410. const ChainExpression$1 = 'ChainExpression';
  6411. const ConditionalExpression$1 = 'ConditionalExpression';
  6412. const ExportDefaultDeclaration$1 = 'ExportDefaultDeclaration';
  6413. const ExportNamedDeclaration$1 = 'ExportNamedDeclaration';
  6414. const ExpressionStatement$1 = 'ExpressionStatement';
  6415. const FunctionDeclaration$1 = 'FunctionDeclaration';
  6416. const Identifier$1 = 'Identifier';
  6417. const LogicalExpression$1 = 'LogicalExpression';
  6418. const NewExpression$1 = 'NewExpression';
  6419. const Program$1 = 'Program';
  6420. const Property$1 = 'Property';
  6421. const ReturnStatement$1 = 'ReturnStatement';
  6422. const SequenceExpression$1 = 'SequenceExpression';
  6423. const VariableDeclarator$1 = 'VariableDeclarator';
  6424. const VariableDeclaration$1 = 'VariableDeclaration';
  6425. // this looks ridiculous, but it prevents sourcemap tooling from mistaking
  6426. // this for an actual sourceMappingURL
  6427. let SOURCEMAPPING_URL = 'sourceMa';
  6428. SOURCEMAPPING_URL += 'ppingURL';
  6429. const whiteSpaceNoNewline = '[ \\f\\r\\t\\v\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]';
  6430. const SOURCEMAPPING_URL_RE = new RegExp(`^#${whiteSpaceNoNewline}+${SOURCEMAPPING_URL}=.+`);
  6431. const ANNOTATION_KEY = '_rollupAnnotations';
  6432. const INVALID_COMMENT_KEY = '_rollupRemoved';
  6433. function handlePureAnnotationsOfNode(node, state, type = node.type) {
  6434. const { annotations, code } = state;
  6435. // eslint-disable-next-line unicorn/consistent-destructuring
  6436. let comment = annotations[state.annotationIndex];
  6437. while (comment && node.start >= comment.end) {
  6438. markPureNode(node, comment, code);
  6439. comment = annotations[++state.annotationIndex];
  6440. }
  6441. if (comment && comment.end <= node.end) {
  6442. base[type](node, state, handlePureAnnotationsOfNode);
  6443. // eslint-disable-next-line unicorn/consistent-destructuring
  6444. while ((comment = annotations[state.annotationIndex]) && comment.end <= node.end) {
  6445. ++state.annotationIndex;
  6446. annotateNode(node, comment, false);
  6447. }
  6448. }
  6449. }
  6450. const neitherWithespaceNorBrackets = /[^\s(]/g;
  6451. const noWhitespace = /\S/g;
  6452. function markPureNode(node, comment, code) {
  6453. const annotatedNodes = [];
  6454. let invalidAnnotation;
  6455. const codeInBetween = code.slice(comment.end, node.start);
  6456. if (doesNotMatchOutsideComment(codeInBetween, neitherWithespaceNorBrackets)) {
  6457. const parentStart = node.start;
  6458. while (true) {
  6459. annotatedNodes.push(node);
  6460. switch (node.type) {
  6461. case ExpressionStatement$1:
  6462. case ChainExpression$1: {
  6463. node = node.expression;
  6464. continue;
  6465. }
  6466. case SequenceExpression$1: {
  6467. // if there are parentheses, the annotation would apply to the entire expression
  6468. if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) {
  6469. node = node.expressions[0];
  6470. continue;
  6471. }
  6472. invalidAnnotation = true;
  6473. break;
  6474. }
  6475. case ConditionalExpression$1: {
  6476. // if there are parentheses, the annotation would apply to the entire expression
  6477. if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) {
  6478. node = node.test;
  6479. continue;
  6480. }
  6481. invalidAnnotation = true;
  6482. break;
  6483. }
  6484. case LogicalExpression$1:
  6485. case BinaryExpression$1: {
  6486. // if there are parentheses, the annotation would apply to the entire expression
  6487. if (doesNotMatchOutsideComment(code.slice(parentStart, node.start), noWhitespace)) {
  6488. node = node.left;
  6489. continue;
  6490. }
  6491. invalidAnnotation = true;
  6492. break;
  6493. }
  6494. case ExportNamedDeclaration$1:
  6495. case ExportDefaultDeclaration$1: {
  6496. node = node.declaration;
  6497. continue;
  6498. }
  6499. case VariableDeclaration$1: {
  6500. const declaration = node;
  6501. if (declaration.kind === 'const') {
  6502. // jsdoc only applies to the first declaration
  6503. node = declaration.declarations[0].init;
  6504. continue;
  6505. }
  6506. invalidAnnotation = true;
  6507. break;
  6508. }
  6509. case VariableDeclarator$1: {
  6510. node = node.init;
  6511. continue;
  6512. }
  6513. case FunctionDeclaration$1:
  6514. case ArrowFunctionExpression$1:
  6515. case CallExpression$1:
  6516. case NewExpression$1: {
  6517. break;
  6518. }
  6519. default: {
  6520. invalidAnnotation = true;
  6521. }
  6522. }
  6523. break;
  6524. }
  6525. }
  6526. else {
  6527. invalidAnnotation = true;
  6528. }
  6529. if (invalidAnnotation) {
  6530. annotateNode(node, comment, false);
  6531. }
  6532. else {
  6533. for (const node of annotatedNodes) {
  6534. annotateNode(node, comment, true);
  6535. }
  6536. }
  6537. }
  6538. function doesNotMatchOutsideComment(code, forbiddenChars) {
  6539. let nextMatch;
  6540. while ((nextMatch = forbiddenChars.exec(code)) !== null) {
  6541. if (nextMatch[0] === '/') {
  6542. const charCodeAfterSlash = code.charCodeAt(forbiddenChars.lastIndex);
  6543. if (charCodeAfterSlash === 42 /*"*"*/) {
  6544. forbiddenChars.lastIndex = code.indexOf('*/', forbiddenChars.lastIndex + 1) + 2;
  6545. continue;
  6546. }
  6547. else if (charCodeAfterSlash === 47 /*"/"*/) {
  6548. forbiddenChars.lastIndex = code.indexOf('\n', forbiddenChars.lastIndex + 1) + 1;
  6549. continue;
  6550. }
  6551. }
  6552. forbiddenChars.lastIndex = 0;
  6553. return false;
  6554. }
  6555. return true;
  6556. }
  6557. const annotationsRegexes = [
  6558. ['pure', /[#@]__PURE__/],
  6559. ['noSideEffects', /[#@]__NO_SIDE_EFFECTS__/]
  6560. ];
  6561. function addAnnotations(comments, esTreeAst, code) {
  6562. const annotations = [];
  6563. const sourceMappingComments = [];
  6564. for (const comment of comments) {
  6565. for (const [annotationType, regex] of annotationsRegexes) {
  6566. if (regex.test(comment.value)) {
  6567. annotations.push({ ...comment, annotationType });
  6568. }
  6569. }
  6570. if (SOURCEMAPPING_URL_RE.test(comment.value)) {
  6571. sourceMappingComments.push(comment);
  6572. }
  6573. }
  6574. for (const comment of sourceMappingComments) {
  6575. annotateNode(esTreeAst, comment, false);
  6576. }
  6577. handlePureAnnotationsOfNode(esTreeAst, {
  6578. annotationIndex: 0,
  6579. annotations,
  6580. code
  6581. });
  6582. }
  6583. function annotateNode(node, comment, valid) {
  6584. const key = valid ? ANNOTATION_KEY : INVALID_COMMENT_KEY;
  6585. const property = node[key];
  6586. if (property) {
  6587. property.push(comment);
  6588. }
  6589. else {
  6590. node[key] = [comment];
  6591. }
  6592. }
  6593. const keys = {
  6594. // TODO this should be removed once ImportExpression follows official ESTree
  6595. // specs with "null" as default
  6596. ImportExpression: ['arguments'],
  6597. Literal: [],
  6598. Program: ['body']
  6599. };
  6600. function getAndCreateKeys(esTreeNode) {
  6601. keys[esTreeNode.type] = Object.keys(esTreeNode).filter(key => typeof esTreeNode[key] === 'object' && key.charCodeAt(0) !== 95 /* _ */);
  6602. return keys[esTreeNode.type];
  6603. }
  6604. const INCLUDE_PARAMETERS = 'variables';
  6605. class NodeBase extends ExpressionEntity {
  6606. constructor(esTreeNode, parent, parentScope, keepEsTreeNode = false) {
  6607. super();
  6608. /**
  6609. * Nodes can apply custom deoptimizations once they become part of the
  6610. * executed code. To do this, they must initialize this as false, implement
  6611. * applyDeoptimizations and call this from include and hasEffects if they have
  6612. * custom handlers
  6613. */
  6614. this.deoptimized = false;
  6615. // Nodes can opt-in to keep the AST if needed during the build pipeline.
  6616. // Avoid true when possible as large AST takes up memory.
  6617. this.esTreeNode = keepEsTreeNode ? esTreeNode : null;
  6618. this.keys = keys[esTreeNode.type] || getAndCreateKeys(esTreeNode);
  6619. this.parent = parent;
  6620. this.context = parent.context;
  6621. this.createScope(parentScope);
  6622. this.parseNode(esTreeNode);
  6623. this.initialise();
  6624. this.context.magicString.addSourcemapLocation(this.start);
  6625. this.context.magicString.addSourcemapLocation(this.end);
  6626. }
  6627. addExportedVariables(_variables, _exportNamesByVariable) { }
  6628. /**
  6629. * Override this to bind assignments to variables and do any initialisations
  6630. * that require the scopes to be populated with variables.
  6631. */
  6632. bind() {
  6633. for (const key of this.keys) {
  6634. const value = this[key];
  6635. if (Array.isArray(value)) {
  6636. for (const child of value) {
  6637. child?.bind();
  6638. }
  6639. }
  6640. else if (value) {
  6641. value.bind();
  6642. }
  6643. }
  6644. }
  6645. /**
  6646. * Override if this node should receive a different scope than the parent
  6647. * scope.
  6648. */
  6649. createScope(parentScope) {
  6650. this.scope = parentScope;
  6651. }
  6652. hasEffects(context) {
  6653. if (!this.deoptimized)
  6654. this.applyDeoptimizations();
  6655. for (const key of this.keys) {
  6656. const value = this[key];
  6657. if (value === null)
  6658. continue;
  6659. if (Array.isArray(value)) {
  6660. for (const child of value) {
  6661. if (child?.hasEffects(context))
  6662. return true;
  6663. }
  6664. }
  6665. else if (value.hasEffects(context))
  6666. return true;
  6667. }
  6668. return false;
  6669. }
  6670. hasEffectsAsAssignmentTarget(context, _checkAccess) {
  6671. return (this.hasEffects(context) ||
  6672. this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
  6673. }
  6674. include(context, includeChildrenRecursively, _options) {
  6675. if (!this.deoptimized)
  6676. this.applyDeoptimizations();
  6677. this.included = true;
  6678. for (const key of this.keys) {
  6679. const value = this[key];
  6680. if (value === null)
  6681. continue;
  6682. if (Array.isArray(value)) {
  6683. for (const child of value) {
  6684. child?.include(context, includeChildrenRecursively);
  6685. }
  6686. }
  6687. else {
  6688. value.include(context, includeChildrenRecursively);
  6689. }
  6690. }
  6691. }
  6692. includeAsAssignmentTarget(context, includeChildrenRecursively, _deoptimizeAccess) {
  6693. this.include(context, includeChildrenRecursively);
  6694. }
  6695. /**
  6696. * Override to perform special initialisation steps after the scope is
  6697. * initialised
  6698. */
  6699. initialise() { }
  6700. insertSemicolon(code) {
  6701. if (code.original[this.end - 1] !== ';') {
  6702. code.appendLeft(this.end, ';');
  6703. }
  6704. }
  6705. parseNode(esTreeNode, keepEsTreeNodeKeys) {
  6706. for (const [key, value] of Object.entries(esTreeNode)) {
  6707. // That way, we can override this function to add custom initialisation and then call super.parseNode
  6708. if (this.hasOwnProperty(key))
  6709. continue;
  6710. if (key.charCodeAt(0) === 95 /* _ */) {
  6711. if (key === ANNOTATION_KEY) {
  6712. const annotations = value;
  6713. this.annotations = annotations;
  6714. if (this.context.options.treeshake.annotations) {
  6715. this.annotationNoSideEffects = annotations.some(comment => comment.annotationType === 'noSideEffects');
  6716. this.annotationPure = annotations.some(comment => comment.annotationType === 'pure');
  6717. }
  6718. }
  6719. else if (key === INVALID_COMMENT_KEY) {
  6720. for (const { start, end } of value)
  6721. this.context.magicString.remove(start, end);
  6722. }
  6723. }
  6724. else if (typeof value !== 'object' || value === null) {
  6725. this[key] = value;
  6726. }
  6727. else if (Array.isArray(value)) {
  6728. this[key] = [];
  6729. for (const child of value) {
  6730. this[key].push(child === null
  6731. ? null
  6732. : new (this.context.getNodeConstructor(child.type))(child, this, this.scope, keepEsTreeNodeKeys?.includes(key)));
  6733. }
  6734. }
  6735. else {
  6736. this[key] = new (this.context.getNodeConstructor(value.type))(value, this, this.scope, keepEsTreeNodeKeys?.includes(key));
  6737. }
  6738. }
  6739. }
  6740. render(code, options) {
  6741. for (const key of this.keys) {
  6742. const value = this[key];
  6743. if (value === null)
  6744. continue;
  6745. if (Array.isArray(value)) {
  6746. for (const child of value) {
  6747. child?.render(code, options);
  6748. }
  6749. }
  6750. else {
  6751. value.render(code, options);
  6752. }
  6753. }
  6754. }
  6755. setAssignedValue(value) {
  6756. this.assignmentInteraction = { args: [null, value], type: INTERACTION_ASSIGNED };
  6757. }
  6758. shouldBeIncluded(context) {
  6759. return this.included || (!context.brokenFlow && this.hasEffects(createHasEffectsContext()));
  6760. }
  6761. /**
  6762. * Just deoptimize everything by default so that when e.g. we do not track
  6763. * something properly, it is deoptimized.
  6764. * @protected
  6765. */
  6766. applyDeoptimizations() {
  6767. this.deoptimized = true;
  6768. for (const key of this.keys) {
  6769. const value = this[key];
  6770. if (value === null)
  6771. continue;
  6772. if (Array.isArray(value)) {
  6773. for (const child of value) {
  6774. child?.deoptimizePath(UNKNOWN_PATH);
  6775. }
  6776. }
  6777. else {
  6778. value.deoptimizePath(UNKNOWN_PATH);
  6779. }
  6780. }
  6781. this.context.requestTreeshakingPass();
  6782. }
  6783. }
  6784. class SpreadElement extends NodeBase {
  6785. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  6786. if (path.length > 0) {
  6787. this.argument.deoptimizeArgumentsOnInteractionAtPath(interaction, [UnknownKey, ...path], recursionTracker);
  6788. }
  6789. }
  6790. hasEffects(context) {
  6791. if (!this.deoptimized)
  6792. this.applyDeoptimizations();
  6793. const { propertyReadSideEffects } = this.context.options
  6794. .treeshake;
  6795. return (this.argument.hasEffects(context) ||
  6796. (propertyReadSideEffects &&
  6797. (propertyReadSideEffects === 'always' ||
  6798. this.argument.hasEffectsOnInteractionAtPath(UNKNOWN_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context))));
  6799. }
  6800. applyDeoptimizations() {
  6801. this.deoptimized = true;
  6802. // Only properties of properties of the argument could become subject to reassignment
  6803. // This will also reassign the return values of iterators
  6804. this.argument.deoptimizePath([UnknownKey, UnknownKey]);
  6805. this.context.requestTreeshakingPass();
  6806. }
  6807. }
  6808. class Method extends ExpressionEntity {
  6809. constructor(description) {
  6810. super();
  6811. this.description = description;
  6812. }
  6813. deoptimizeArgumentsOnInteractionAtPath({ args, type }, path) {
  6814. if (type === INTERACTION_CALLED && path.length === 0 && this.description.mutatesSelfAsArray) {
  6815. args[0]?.deoptimizePath(UNKNOWN_INTEGER_PATH);
  6816. }
  6817. }
  6818. getReturnExpressionWhenCalledAtPath(path, { args }) {
  6819. if (path.length > 0) {
  6820. return UNKNOWN_RETURN_EXPRESSION;
  6821. }
  6822. return [
  6823. this.description.returnsPrimitive ||
  6824. (this.description.returns === 'self'
  6825. ? args[0] || UNKNOWN_EXPRESSION
  6826. : this.description.returns()),
  6827. false
  6828. ];
  6829. }
  6830. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6831. const { type } = interaction;
  6832. if (path.length > (type === INTERACTION_ACCESSED ? 1 : 0)) {
  6833. return true;
  6834. }
  6835. if (type === INTERACTION_CALLED) {
  6836. const { args } = interaction;
  6837. if (this.description.mutatesSelfAsArray === true &&
  6838. args[0]?.hasEffectsOnInteractionAtPath(UNKNOWN_INTEGER_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context)) {
  6839. return true;
  6840. }
  6841. if (this.description.callsArgs) {
  6842. for (const argumentIndex of this.description.callsArgs) {
  6843. if (args[argumentIndex + 1]?.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)) {
  6844. return true;
  6845. }
  6846. }
  6847. }
  6848. }
  6849. return false;
  6850. }
  6851. }
  6852. const METHOD_RETURNS_BOOLEAN = [
  6853. new Method({
  6854. callsArgs: null,
  6855. mutatesSelfAsArray: false,
  6856. returns: null,
  6857. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  6858. })
  6859. ];
  6860. const METHOD_RETURNS_STRING = [
  6861. new Method({
  6862. callsArgs: null,
  6863. mutatesSelfAsArray: false,
  6864. returns: null,
  6865. returnsPrimitive: UNKNOWN_LITERAL_STRING
  6866. })
  6867. ];
  6868. const METHOD_RETURNS_NUMBER = [
  6869. new Method({
  6870. callsArgs: null,
  6871. mutatesSelfAsArray: false,
  6872. returns: null,
  6873. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  6874. })
  6875. ];
  6876. const METHOD_RETURNS_UNKNOWN = [
  6877. new Method({
  6878. callsArgs: null,
  6879. mutatesSelfAsArray: false,
  6880. returns: null,
  6881. returnsPrimitive: UNKNOWN_EXPRESSION
  6882. })
  6883. ];
  6884. const INTEGER_REG_EXP = /^\d+$/;
  6885. class ObjectEntity extends ExpressionEntity {
  6886. // If a PropertyMap is used, this will be taken as propertiesAndGettersByKey
  6887. // and we assume there are no setters or getters
  6888. constructor(properties, prototypeExpression, immutable = false) {
  6889. super();
  6890. this.prototypeExpression = prototypeExpression;
  6891. this.immutable = immutable;
  6892. this.additionalExpressionsToBeDeoptimized = new Set();
  6893. this.allProperties = [];
  6894. this.deoptimizedPaths = Object.create(null);
  6895. this.expressionsToBeDeoptimizedByKey = Object.create(null);
  6896. this.gettersByKey = Object.create(null);
  6897. this.hasLostTrack = false;
  6898. this.hasUnknownDeoptimizedInteger = false;
  6899. this.hasUnknownDeoptimizedProperty = false;
  6900. this.propertiesAndGettersByKey = Object.create(null);
  6901. this.propertiesAndSettersByKey = Object.create(null);
  6902. this.settersByKey = Object.create(null);
  6903. this.unknownIntegerProps = [];
  6904. this.unmatchableGetters = [];
  6905. this.unmatchablePropertiesAndGetters = [];
  6906. this.unmatchableSetters = [];
  6907. if (Array.isArray(properties)) {
  6908. this.buildPropertyMaps(properties);
  6909. }
  6910. else {
  6911. this.propertiesAndGettersByKey = this.propertiesAndSettersByKey = properties;
  6912. for (const propertiesForKey of Object.values(properties)) {
  6913. this.allProperties.push(...propertiesForKey);
  6914. }
  6915. }
  6916. }
  6917. deoptimizeAllProperties(noAccessors) {
  6918. const isDeoptimized = this.hasLostTrack || this.hasUnknownDeoptimizedProperty;
  6919. if (noAccessors) {
  6920. this.hasUnknownDeoptimizedProperty = true;
  6921. }
  6922. else {
  6923. this.hasLostTrack = true;
  6924. }
  6925. if (isDeoptimized) {
  6926. return;
  6927. }
  6928. for (const properties of [
  6929. ...Object.values(this.propertiesAndGettersByKey),
  6930. ...Object.values(this.settersByKey)
  6931. ]) {
  6932. for (const property of properties) {
  6933. property.deoptimizePath(UNKNOWN_PATH);
  6934. }
  6935. }
  6936. // While the prototype itself cannot be mutated, each property can
  6937. this.prototypeExpression?.deoptimizePath([UnknownKey, UnknownKey]);
  6938. this.deoptimizeCachedEntities();
  6939. }
  6940. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  6941. const [key, ...subPath] = path;
  6942. const { args, type } = interaction;
  6943. if (this.hasLostTrack ||
  6944. // single paths that are deoptimized will not become getters or setters
  6945. ((type === INTERACTION_CALLED || path.length > 1) &&
  6946. (this.hasUnknownDeoptimizedProperty ||
  6947. (typeof key === 'string' && this.deoptimizedPaths[key])))) {
  6948. deoptimizeInteraction(interaction);
  6949. return;
  6950. }
  6951. const [propertiesForExactMatchByKey, relevantPropertiesByKey, relevantUnmatchableProperties] = type === INTERACTION_CALLED || path.length > 1
  6952. ? [
  6953. this.propertiesAndGettersByKey,
  6954. this.propertiesAndGettersByKey,
  6955. this.unmatchablePropertiesAndGetters
  6956. ]
  6957. : type === INTERACTION_ACCESSED
  6958. ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters]
  6959. : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters];
  6960. if (typeof key === 'string') {
  6961. if (propertiesForExactMatchByKey[key]) {
  6962. const properties = relevantPropertiesByKey[key];
  6963. if (properties) {
  6964. for (const property of properties) {
  6965. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  6966. }
  6967. }
  6968. if (!this.immutable) {
  6969. for (const argument of args) {
  6970. if (argument) {
  6971. this.additionalExpressionsToBeDeoptimized.add(argument);
  6972. }
  6973. }
  6974. }
  6975. return;
  6976. }
  6977. for (const property of relevantUnmatchableProperties) {
  6978. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  6979. }
  6980. if (INTEGER_REG_EXP.test(key)) {
  6981. for (const property of this.unknownIntegerProps) {
  6982. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  6983. }
  6984. }
  6985. }
  6986. else {
  6987. for (const properties of [
  6988. ...Object.values(relevantPropertiesByKey),
  6989. relevantUnmatchableProperties
  6990. ]) {
  6991. for (const property of properties) {
  6992. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  6993. }
  6994. }
  6995. for (const property of this.unknownIntegerProps) {
  6996. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  6997. }
  6998. }
  6999. if (!this.immutable) {
  7000. for (const argument of args) {
  7001. if (argument) {
  7002. this.additionalExpressionsToBeDeoptimized.add(argument);
  7003. }
  7004. }
  7005. }
  7006. this.prototypeExpression?.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  7007. }
  7008. deoptimizeIntegerProperties() {
  7009. if (this.hasLostTrack ||
  7010. this.hasUnknownDeoptimizedProperty ||
  7011. this.hasUnknownDeoptimizedInteger) {
  7012. return;
  7013. }
  7014. this.hasUnknownDeoptimizedInteger = true;
  7015. for (const [key, propertiesAndGetters] of Object.entries(this.propertiesAndGettersByKey)) {
  7016. if (INTEGER_REG_EXP.test(key)) {
  7017. for (const property of propertiesAndGetters) {
  7018. property.deoptimizePath(UNKNOWN_PATH);
  7019. }
  7020. }
  7021. }
  7022. this.deoptimizeCachedIntegerEntities();
  7023. }
  7024. // Assumption: If only a specific path is deoptimized, no accessors are created
  7025. deoptimizePath(path) {
  7026. if (this.hasLostTrack || this.immutable) {
  7027. return;
  7028. }
  7029. const key = path[0];
  7030. if (path.length === 1) {
  7031. if (typeof key !== 'string') {
  7032. if (key === UnknownInteger) {
  7033. return this.deoptimizeIntegerProperties();
  7034. }
  7035. return this.deoptimizeAllProperties(key === UnknownNonAccessorKey);
  7036. }
  7037. if (!this.deoptimizedPaths[key]) {
  7038. this.deoptimizedPaths[key] = true;
  7039. // we only deoptimizeCache exact matches as in all other cases,
  7040. // we do not return a literal value or return expression
  7041. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimizedByKey[key];
  7042. if (expressionsToBeDeoptimized) {
  7043. for (const expression of expressionsToBeDeoptimized) {
  7044. expression.deoptimizeCache();
  7045. }
  7046. }
  7047. }
  7048. }
  7049. const subPath = path.length === 1 ? UNKNOWN_PATH : path.slice(1);
  7050. for (const property of typeof key === 'string'
  7051. ? [
  7052. ...(this.propertiesAndGettersByKey[key] || this.unmatchablePropertiesAndGetters),
  7053. ...(this.settersByKey[key] || this.unmatchableSetters)
  7054. ]
  7055. : this.allProperties) {
  7056. property.deoptimizePath(subPath);
  7057. }
  7058. this.prototypeExpression?.deoptimizePath(path.length === 1 ? [...path, UnknownKey] : path);
  7059. }
  7060. getLiteralValueAtPath(path, recursionTracker, origin) {
  7061. if (path.length === 0) {
  7062. return UnknownTruthyValue;
  7063. }
  7064. const key = path[0];
  7065. const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
  7066. if (expressionAtPath) {
  7067. return expressionAtPath.getLiteralValueAtPath(path.slice(1), recursionTracker, origin);
  7068. }
  7069. if (this.prototypeExpression) {
  7070. return this.prototypeExpression.getLiteralValueAtPath(path, recursionTracker, origin);
  7071. }
  7072. if (path.length === 1) {
  7073. return undefined;
  7074. }
  7075. return UnknownValue;
  7076. }
  7077. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  7078. if (path.length === 0) {
  7079. return UNKNOWN_RETURN_EXPRESSION;
  7080. }
  7081. const [key, ...subPath] = path;
  7082. const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
  7083. if (expressionAtPath) {
  7084. return expressionAtPath.getReturnExpressionWhenCalledAtPath(subPath, interaction, recursionTracker, origin);
  7085. }
  7086. if (this.prototypeExpression) {
  7087. return this.prototypeExpression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  7088. }
  7089. return UNKNOWN_RETURN_EXPRESSION;
  7090. }
  7091. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7092. const [key, ...subPath] = path;
  7093. if (subPath.length > 0 || interaction.type === INTERACTION_CALLED) {
  7094. const expressionAtPath = this.getMemberExpression(key);
  7095. if (expressionAtPath) {
  7096. return expressionAtPath.hasEffectsOnInteractionAtPath(subPath, interaction, context);
  7097. }
  7098. if (this.prototypeExpression) {
  7099. return this.prototypeExpression.hasEffectsOnInteractionAtPath(path, interaction, context);
  7100. }
  7101. return true;
  7102. }
  7103. if (key === UnknownNonAccessorKey)
  7104. return false;
  7105. if (this.hasLostTrack)
  7106. return true;
  7107. const [propertiesAndAccessorsByKey, accessorsByKey, unmatchableAccessors] = interaction.type === INTERACTION_ACCESSED
  7108. ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters]
  7109. : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters];
  7110. if (typeof key === 'string') {
  7111. if (propertiesAndAccessorsByKey[key]) {
  7112. const accessors = accessorsByKey[key];
  7113. if (accessors) {
  7114. for (const accessor of accessors) {
  7115. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context))
  7116. return true;
  7117. }
  7118. }
  7119. return false;
  7120. }
  7121. for (const accessor of unmatchableAccessors) {
  7122. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context)) {
  7123. return true;
  7124. }
  7125. }
  7126. }
  7127. else {
  7128. for (const accessors of [...Object.values(accessorsByKey), unmatchableAccessors]) {
  7129. for (const accessor of accessors) {
  7130. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context))
  7131. return true;
  7132. }
  7133. }
  7134. }
  7135. if (this.prototypeExpression) {
  7136. return this.prototypeExpression.hasEffectsOnInteractionAtPath(path, interaction, context);
  7137. }
  7138. return false;
  7139. }
  7140. buildPropertyMaps(properties) {
  7141. const { allProperties, propertiesAndGettersByKey, propertiesAndSettersByKey, settersByKey, gettersByKey, unknownIntegerProps, unmatchablePropertiesAndGetters, unmatchableGetters, unmatchableSetters } = this;
  7142. const unmatchablePropertiesAndSetters = [];
  7143. for (let index = properties.length - 1; index >= 0; index--) {
  7144. const { key, kind, property } = properties[index];
  7145. allProperties.push(property);
  7146. if (typeof key === 'string') {
  7147. if (kind === 'set') {
  7148. if (!propertiesAndSettersByKey[key]) {
  7149. propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters];
  7150. settersByKey[key] = [property, ...unmatchableSetters];
  7151. }
  7152. }
  7153. else if (kind === 'get') {
  7154. if (!propertiesAndGettersByKey[key]) {
  7155. propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters];
  7156. gettersByKey[key] = [property, ...unmatchableGetters];
  7157. }
  7158. }
  7159. else {
  7160. if (!propertiesAndSettersByKey[key]) {
  7161. propertiesAndSettersByKey[key] = [property, ...unmatchablePropertiesAndSetters];
  7162. }
  7163. if (!propertiesAndGettersByKey[key]) {
  7164. propertiesAndGettersByKey[key] = [property, ...unmatchablePropertiesAndGetters];
  7165. }
  7166. }
  7167. }
  7168. else {
  7169. if (key === UnknownInteger) {
  7170. unknownIntegerProps.push(property);
  7171. continue;
  7172. }
  7173. if (kind === 'set')
  7174. unmatchableSetters.push(property);
  7175. if (kind === 'get')
  7176. unmatchableGetters.push(property);
  7177. if (kind !== 'get')
  7178. unmatchablePropertiesAndSetters.push(property);
  7179. if (kind !== 'set')
  7180. unmatchablePropertiesAndGetters.push(property);
  7181. }
  7182. }
  7183. }
  7184. deoptimizeCachedEntities() {
  7185. for (const expressionsToBeDeoptimized of Object.values(this.expressionsToBeDeoptimizedByKey)) {
  7186. for (const expression of expressionsToBeDeoptimized) {
  7187. expression.deoptimizeCache();
  7188. }
  7189. }
  7190. for (const expression of this.additionalExpressionsToBeDeoptimized) {
  7191. expression.deoptimizePath(UNKNOWN_PATH);
  7192. }
  7193. }
  7194. deoptimizeCachedIntegerEntities() {
  7195. for (const [key, expressionsToBeDeoptimized] of Object.entries(this.expressionsToBeDeoptimizedByKey)) {
  7196. if (INTEGER_REG_EXP.test(key)) {
  7197. for (const expression of expressionsToBeDeoptimized) {
  7198. expression.deoptimizeCache();
  7199. }
  7200. }
  7201. }
  7202. for (const expression of this.additionalExpressionsToBeDeoptimized) {
  7203. expression.deoptimizePath(UNKNOWN_INTEGER_PATH);
  7204. }
  7205. }
  7206. getMemberExpression(key) {
  7207. if (this.hasLostTrack ||
  7208. this.hasUnknownDeoptimizedProperty ||
  7209. typeof key !== 'string' ||
  7210. (this.hasUnknownDeoptimizedInteger && INTEGER_REG_EXP.test(key)) ||
  7211. this.deoptimizedPaths[key]) {
  7212. return UNKNOWN_EXPRESSION;
  7213. }
  7214. const properties = this.propertiesAndGettersByKey[key];
  7215. if (properties?.length === 1) {
  7216. return properties[0];
  7217. }
  7218. if (properties ||
  7219. this.unmatchablePropertiesAndGetters.length > 0 ||
  7220. (this.unknownIntegerProps.length > 0 && INTEGER_REG_EXP.test(key))) {
  7221. return UNKNOWN_EXPRESSION;
  7222. }
  7223. return null;
  7224. }
  7225. getMemberExpressionAndTrackDeopt(key, origin) {
  7226. if (typeof key !== 'string') {
  7227. return UNKNOWN_EXPRESSION;
  7228. }
  7229. const expression = this.getMemberExpression(key);
  7230. if (!(expression === UNKNOWN_EXPRESSION || this.immutable)) {
  7231. const expressionsToBeDeoptimized = (this.expressionsToBeDeoptimizedByKey[key] =
  7232. this.expressionsToBeDeoptimizedByKey[key] || []);
  7233. expressionsToBeDeoptimized.push(origin);
  7234. }
  7235. return expression;
  7236. }
  7237. }
  7238. const isInteger = (property) => typeof property === 'string' && /^\d+$/.test(property);
  7239. // This makes sure unknown properties are not handled as "undefined" but as
  7240. // "unknown" but without access side effects. An exception is done for numeric
  7241. // properties as we do not expect new builtin properties to be numbers, this
  7242. // will improve tree-shaking for out-of-bounds array properties
  7243. const OBJECT_PROTOTYPE_FALLBACK = new (class ObjectPrototypeFallbackExpression extends ExpressionEntity {
  7244. deoptimizeArgumentsOnInteractionAtPath(interaction, path) {
  7245. if (interaction.type === INTERACTION_CALLED && path.length === 1 && !isInteger(path[0])) {
  7246. deoptimizeInteraction(interaction);
  7247. }
  7248. }
  7249. getLiteralValueAtPath(path) {
  7250. // We ignore number properties as we do not expect new properties to be
  7251. // numbers and also want to keep handling out-of-bound array elements as
  7252. // "undefined"
  7253. return path.length === 1 && isInteger(path[0]) ? undefined : UnknownValue;
  7254. }
  7255. hasEffectsOnInteractionAtPath(path, { type }) {
  7256. return path.length > 1 || type === INTERACTION_CALLED;
  7257. }
  7258. })();
  7259. const OBJECT_PROTOTYPE = new ObjectEntity({
  7260. __proto__: null,
  7261. hasOwnProperty: METHOD_RETURNS_BOOLEAN,
  7262. isPrototypeOf: METHOD_RETURNS_BOOLEAN,
  7263. propertyIsEnumerable: METHOD_RETURNS_BOOLEAN,
  7264. toLocaleString: METHOD_RETURNS_STRING,
  7265. toString: METHOD_RETURNS_STRING,
  7266. valueOf: METHOD_RETURNS_UNKNOWN
  7267. }, OBJECT_PROTOTYPE_FALLBACK, true);
  7268. const NEW_ARRAY_PROPERTIES = [
  7269. { key: UnknownInteger, kind: 'init', property: UNKNOWN_EXPRESSION },
  7270. { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
  7271. ];
  7272. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN = [
  7273. new Method({
  7274. callsArgs: [0],
  7275. mutatesSelfAsArray: 'deopt-only',
  7276. returns: null,
  7277. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  7278. })
  7279. ];
  7280. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER = [
  7281. new Method({
  7282. callsArgs: [0],
  7283. mutatesSelfAsArray: 'deopt-only',
  7284. returns: null,
  7285. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  7286. })
  7287. ];
  7288. const METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY = [
  7289. new Method({
  7290. callsArgs: null,
  7291. mutatesSelfAsArray: true,
  7292. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  7293. returnsPrimitive: null
  7294. })
  7295. ];
  7296. const METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
  7297. new Method({
  7298. callsArgs: null,
  7299. mutatesSelfAsArray: 'deopt-only',
  7300. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  7301. returnsPrimitive: null
  7302. })
  7303. ];
  7304. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
  7305. new Method({
  7306. callsArgs: [0],
  7307. mutatesSelfAsArray: 'deopt-only',
  7308. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  7309. returnsPrimitive: null
  7310. })
  7311. ];
  7312. const METHOD_MUTATES_SELF_RETURNS_NUMBER = [
  7313. new Method({
  7314. callsArgs: null,
  7315. mutatesSelfAsArray: true,
  7316. returns: null,
  7317. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  7318. })
  7319. ];
  7320. const METHOD_MUTATES_SELF_RETURNS_UNKNOWN = [
  7321. new Method({
  7322. callsArgs: null,
  7323. mutatesSelfAsArray: true,
  7324. returns: null,
  7325. returnsPrimitive: UNKNOWN_EXPRESSION
  7326. })
  7327. ];
  7328. const METHOD_DEOPTS_SELF_RETURNS_UNKNOWN = [
  7329. new Method({
  7330. callsArgs: null,
  7331. mutatesSelfAsArray: 'deopt-only',
  7332. returns: null,
  7333. returnsPrimitive: UNKNOWN_EXPRESSION
  7334. })
  7335. ];
  7336. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN = [
  7337. new Method({
  7338. callsArgs: [0],
  7339. mutatesSelfAsArray: 'deopt-only',
  7340. returns: null,
  7341. returnsPrimitive: UNKNOWN_EXPRESSION
  7342. })
  7343. ];
  7344. const METHOD_MUTATES_SELF_RETURNS_SELF = [
  7345. new Method({
  7346. callsArgs: null,
  7347. mutatesSelfAsArray: true,
  7348. returns: 'self',
  7349. returnsPrimitive: null
  7350. })
  7351. ];
  7352. const METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF = [
  7353. new Method({
  7354. callsArgs: [0],
  7355. mutatesSelfAsArray: true,
  7356. returns: 'self',
  7357. returnsPrimitive: null
  7358. })
  7359. ];
  7360. const ARRAY_PROTOTYPE = new ObjectEntity({
  7361. __proto__: null,
  7362. // We assume that accessors have effects as we do not track the accessed value afterwards
  7363. at: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN,
  7364. concat: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  7365. copyWithin: METHOD_MUTATES_SELF_RETURNS_SELF,
  7366. entries: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  7367. every: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN,
  7368. fill: METHOD_MUTATES_SELF_RETURNS_SELF,
  7369. filter: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  7370. find: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  7371. findIndex: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER,
  7372. findLast: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  7373. findLastIndex: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER,
  7374. flat: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  7375. flatMap: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  7376. forEach: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  7377. includes: METHOD_RETURNS_BOOLEAN,
  7378. indexOf: METHOD_RETURNS_NUMBER,
  7379. join: METHOD_RETURNS_STRING,
  7380. keys: METHOD_RETURNS_UNKNOWN,
  7381. lastIndexOf: METHOD_RETURNS_NUMBER,
  7382. map: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  7383. pop: METHOD_MUTATES_SELF_RETURNS_UNKNOWN,
  7384. push: METHOD_MUTATES_SELF_RETURNS_NUMBER,
  7385. reduce: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  7386. reduceRight: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN,
  7387. reverse: METHOD_MUTATES_SELF_RETURNS_SELF,
  7388. shift: METHOD_MUTATES_SELF_RETURNS_UNKNOWN,
  7389. slice: METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY,
  7390. some: METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN,
  7391. sort: METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF,
  7392. splice: METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY,
  7393. toLocaleString: METHOD_RETURNS_STRING,
  7394. toString: METHOD_RETURNS_STRING,
  7395. unshift: METHOD_MUTATES_SELF_RETURNS_NUMBER,
  7396. values: METHOD_DEOPTS_SELF_RETURNS_UNKNOWN
  7397. }, OBJECT_PROTOTYPE, true);
  7398. class ArrayExpression extends NodeBase {
  7399. constructor() {
  7400. super(...arguments);
  7401. this.objectEntity = null;
  7402. }
  7403. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  7404. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  7405. }
  7406. deoptimizePath(path) {
  7407. this.getObjectEntity().deoptimizePath(path);
  7408. }
  7409. getLiteralValueAtPath(path, recursionTracker, origin) {
  7410. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  7411. }
  7412. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  7413. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  7414. }
  7415. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7416. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  7417. }
  7418. applyDeoptimizations() {
  7419. this.deoptimized = true;
  7420. let hasSpread = false;
  7421. for (let index = 0; index < this.elements.length; index++) {
  7422. const element = this.elements[index];
  7423. if (element && (hasSpread || element instanceof SpreadElement)) {
  7424. hasSpread = true;
  7425. element.deoptimizePath(UNKNOWN_PATH);
  7426. }
  7427. }
  7428. this.context.requestTreeshakingPass();
  7429. }
  7430. getObjectEntity() {
  7431. if (this.objectEntity !== null) {
  7432. return this.objectEntity;
  7433. }
  7434. const properties = [
  7435. { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
  7436. ];
  7437. let hasSpread = false;
  7438. for (let index = 0; index < this.elements.length; index++) {
  7439. const element = this.elements[index];
  7440. if (hasSpread || element instanceof SpreadElement) {
  7441. if (element) {
  7442. hasSpread = true;
  7443. properties.unshift({ key: UnknownInteger, kind: 'init', property: element });
  7444. }
  7445. }
  7446. else if (element) {
  7447. properties.push({ key: String(index), kind: 'init', property: element });
  7448. }
  7449. else {
  7450. properties.push({ key: String(index), kind: 'init', property: UNDEFINED_EXPRESSION });
  7451. }
  7452. }
  7453. return (this.objectEntity = new ObjectEntity(properties, ARRAY_PROTOTYPE));
  7454. }
  7455. }
  7456. class ArrayPattern extends NodeBase {
  7457. addExportedVariables(variables, exportNamesByVariable) {
  7458. for (const element of this.elements) {
  7459. element?.addExportedVariables(variables, exportNamesByVariable);
  7460. }
  7461. }
  7462. declare(kind) {
  7463. const variables = [];
  7464. for (const element of this.elements) {
  7465. if (element !== null) {
  7466. variables.push(...element.declare(kind, UNKNOWN_EXPRESSION));
  7467. }
  7468. }
  7469. return variables;
  7470. }
  7471. // Patterns can only be deoptimized at the empty path at the moment
  7472. deoptimizePath() {
  7473. for (const element of this.elements) {
  7474. element?.deoptimizePath(EMPTY_PATH);
  7475. }
  7476. }
  7477. // Patterns are only checked at the emtpy path at the moment
  7478. hasEffectsOnInteractionAtPath(_path, interaction, context) {
  7479. for (const element of this.elements) {
  7480. if (element?.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context))
  7481. return true;
  7482. }
  7483. return false;
  7484. }
  7485. markDeclarationReached() {
  7486. for (const element of this.elements) {
  7487. element?.markDeclarationReached();
  7488. }
  7489. }
  7490. }
  7491. class LocalVariable extends Variable {
  7492. constructor(name, declarator, init, context) {
  7493. super(name);
  7494. this.init = init;
  7495. this.calledFromTryStatement = false;
  7496. this.additionalInitializers = null;
  7497. this.expressionsToBeDeoptimized = [];
  7498. this.declarations = declarator ? [declarator] : [];
  7499. this.deoptimizationTracker = context.deoptimizationTracker;
  7500. this.module = context.module;
  7501. }
  7502. addDeclaration(identifier, init) {
  7503. this.declarations.push(identifier);
  7504. this.markInitializersForDeoptimization().push(init);
  7505. }
  7506. consolidateInitializers() {
  7507. if (this.additionalInitializers) {
  7508. for (const initializer of this.additionalInitializers) {
  7509. initializer.deoptimizePath(UNKNOWN_PATH);
  7510. }
  7511. this.additionalInitializers = null;
  7512. }
  7513. }
  7514. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  7515. if (this.isReassigned) {
  7516. deoptimizeInteraction(interaction);
  7517. return;
  7518. }
  7519. recursionTracker.withTrackedEntityAtPath(path, this.init, () => this.init.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker), undefined);
  7520. }
  7521. deoptimizePath(path) {
  7522. if (this.isReassigned ||
  7523. this.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  7524. return;
  7525. }
  7526. if (path.length === 0) {
  7527. if (!this.isReassigned) {
  7528. this.isReassigned = true;
  7529. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
  7530. this.expressionsToBeDeoptimized = EMPTY_ARRAY;
  7531. for (const expression of expressionsToBeDeoptimized) {
  7532. expression.deoptimizeCache();
  7533. }
  7534. this.init.deoptimizePath(UNKNOWN_PATH);
  7535. }
  7536. }
  7537. else {
  7538. this.init.deoptimizePath(path);
  7539. }
  7540. }
  7541. getLiteralValueAtPath(path, recursionTracker, origin) {
  7542. if (this.isReassigned) {
  7543. return UnknownValue;
  7544. }
  7545. return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  7546. this.expressionsToBeDeoptimized.push(origin);
  7547. return this.init.getLiteralValueAtPath(path, recursionTracker, origin);
  7548. }, UnknownValue);
  7549. }
  7550. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  7551. if (this.isReassigned) {
  7552. return UNKNOWN_RETURN_EXPRESSION;
  7553. }
  7554. return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  7555. this.expressionsToBeDeoptimized.push(origin);
  7556. return this.init.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  7557. }, UNKNOWN_RETURN_EXPRESSION);
  7558. }
  7559. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7560. switch (interaction.type) {
  7561. case INTERACTION_ACCESSED: {
  7562. if (this.isReassigned)
  7563. return true;
  7564. return (!context.accessed.trackEntityAtPathAndGetIfTracked(path, this) &&
  7565. this.init.hasEffectsOnInteractionAtPath(path, interaction, context));
  7566. }
  7567. case INTERACTION_ASSIGNED: {
  7568. if (this.included)
  7569. return true;
  7570. if (path.length === 0)
  7571. return false;
  7572. if (this.isReassigned)
  7573. return true;
  7574. return (!context.assigned.trackEntityAtPathAndGetIfTracked(path, this) &&
  7575. this.init.hasEffectsOnInteractionAtPath(path, interaction, context));
  7576. }
  7577. case INTERACTION_CALLED: {
  7578. if (this.isReassigned)
  7579. return true;
  7580. return (!(interaction.withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, interaction.args, this) &&
  7581. this.init.hasEffectsOnInteractionAtPath(path, interaction, context));
  7582. }
  7583. }
  7584. }
  7585. include() {
  7586. if (!this.included) {
  7587. this.included = true;
  7588. for (const declaration of this.declarations) {
  7589. // If node is a default export, it can save a tree-shaking run to include the full declaration now
  7590. if (!declaration.included)
  7591. declaration.include(createInclusionContext(), false);
  7592. let node = declaration.parent;
  7593. while (!node.included) {
  7594. // We do not want to properly include parents in case they are part of a dead branch
  7595. // in which case .include() might pull in more dead code
  7596. node.included = true;
  7597. if (node.type === Program$1)
  7598. break;
  7599. node = node.parent;
  7600. }
  7601. }
  7602. }
  7603. }
  7604. includeCallArguments(context, parameters) {
  7605. if (this.isReassigned || context.includedCallArguments.has(this.init)) {
  7606. for (const argument of parameters) {
  7607. argument.include(context, false);
  7608. }
  7609. }
  7610. else {
  7611. context.includedCallArguments.add(this.init);
  7612. this.init.includeCallArguments(context, parameters);
  7613. context.includedCallArguments.delete(this.init);
  7614. }
  7615. }
  7616. markCalledFromTryStatement() {
  7617. this.calledFromTryStatement = true;
  7618. }
  7619. markInitializersForDeoptimization() {
  7620. if (this.additionalInitializers === null) {
  7621. this.additionalInitializers = [this.init];
  7622. this.init = UNKNOWN_EXPRESSION;
  7623. this.isReassigned = true;
  7624. }
  7625. return this.additionalInitializers;
  7626. }
  7627. mergeDeclarations(variable) {
  7628. const { declarations } = this;
  7629. for (const declaration of variable.declarations) {
  7630. declarations.push(declaration);
  7631. }
  7632. const additionalInitializers = this.markInitializersForDeoptimization();
  7633. additionalInitializers.push(variable.init);
  7634. if (variable.additionalInitializers) {
  7635. for (const initializer of variable.additionalInitializers) {
  7636. additionalInitializers.push(initializer);
  7637. }
  7638. }
  7639. }
  7640. }
  7641. const MAX_TRACKED_INTERACTIONS = 20;
  7642. const NO_INTERACTIONS = EMPTY_ARRAY;
  7643. const UNKNOWN_DEOPTIMIZED_FIELD = new Set([UnknownKey]);
  7644. const EMPTY_PATH_TRACKER = new PathTracker();
  7645. const UNKNOWN_DEOPTIMIZED_ENTITY = new Set([UNKNOWN_EXPRESSION]);
  7646. class ParameterVariable extends LocalVariable {
  7647. constructor(name, declarator, context) {
  7648. super(name, declarator, UNKNOWN_EXPRESSION, context);
  7649. this.deoptimizationInteractions = [];
  7650. this.deoptimizations = new PathTracker();
  7651. this.deoptimizedFields = new Set();
  7652. this.entitiesToBeDeoptimized = new Set();
  7653. }
  7654. addEntityToBeDeoptimized(entity) {
  7655. if (entity === UNKNOWN_EXPRESSION) {
  7656. // As unknown expressions fully deoptimize all interactions, we can clear
  7657. // the interaction cache at this point provided we keep this optimization
  7658. // in mind when adding new interactions
  7659. if (!this.entitiesToBeDeoptimized.has(UNKNOWN_EXPRESSION)) {
  7660. this.entitiesToBeDeoptimized.add(UNKNOWN_EXPRESSION);
  7661. for (const { interaction } of this.deoptimizationInteractions) {
  7662. deoptimizeInteraction(interaction);
  7663. }
  7664. this.deoptimizationInteractions = NO_INTERACTIONS;
  7665. }
  7666. }
  7667. else if (this.deoptimizedFields.has(UnknownKey)) {
  7668. // This means that we already deoptimized all interactions and no longer
  7669. // track them
  7670. entity.deoptimizePath(UNKNOWN_PATH);
  7671. }
  7672. else if (!this.entitiesToBeDeoptimized.has(entity)) {
  7673. this.entitiesToBeDeoptimized.add(entity);
  7674. for (const field of this.deoptimizedFields) {
  7675. entity.deoptimizePath([field]);
  7676. }
  7677. for (const { interaction, path } of this.deoptimizationInteractions) {
  7678. entity.deoptimizeArgumentsOnInteractionAtPath(interaction, path, SHARED_RECURSION_TRACKER);
  7679. }
  7680. }
  7681. }
  7682. deoptimizeArgumentsOnInteractionAtPath(interaction, path) {
  7683. // For performance reasons, we fully deoptimize all deeper interactions
  7684. if (path.length >= 2 ||
  7685. this.entitiesToBeDeoptimized.has(UNKNOWN_EXPRESSION) ||
  7686. this.deoptimizationInteractions.length >= MAX_TRACKED_INTERACTIONS ||
  7687. (path.length === 1 &&
  7688. (this.deoptimizedFields.has(UnknownKey) ||
  7689. (interaction.type === INTERACTION_CALLED && this.deoptimizedFields.has(path[0]))))) {
  7690. deoptimizeInteraction(interaction);
  7691. return;
  7692. }
  7693. if (!this.deoptimizations.trackEntityAtPathAndGetIfTracked(path, interaction.args)) {
  7694. for (const entity of this.entitiesToBeDeoptimized) {
  7695. entity.deoptimizeArgumentsOnInteractionAtPath(interaction, path, SHARED_RECURSION_TRACKER);
  7696. }
  7697. if (!this.entitiesToBeDeoptimized.has(UNKNOWN_EXPRESSION)) {
  7698. this.deoptimizationInteractions.push({
  7699. interaction,
  7700. path
  7701. });
  7702. }
  7703. }
  7704. }
  7705. deoptimizePath(path) {
  7706. if (path.length === 0 || this.deoptimizedFields.has(UnknownKey)) {
  7707. return;
  7708. }
  7709. const key = path[0];
  7710. if (this.deoptimizedFields.has(key)) {
  7711. return;
  7712. }
  7713. this.deoptimizedFields.add(key);
  7714. for (const entity of this.entitiesToBeDeoptimized) {
  7715. // We do not need a recursion tracker here as we already track whether
  7716. // this field is deoptimized
  7717. entity.deoptimizePath([key]);
  7718. }
  7719. if (key === UnknownKey) {
  7720. // save some memory
  7721. this.deoptimizationInteractions = NO_INTERACTIONS;
  7722. this.deoptimizations = EMPTY_PATH_TRACKER;
  7723. this.deoptimizedFields = UNKNOWN_DEOPTIMIZED_FIELD;
  7724. this.entitiesToBeDeoptimized = UNKNOWN_DEOPTIMIZED_ENTITY;
  7725. }
  7726. }
  7727. getReturnExpressionWhenCalledAtPath(path) {
  7728. // We deoptimize everything that is called as that will trivially deoptimize
  7729. // the corresponding return expressions as well and avoid badly performing
  7730. // and complicated alternatives
  7731. if (path.length === 0) {
  7732. this.deoptimizePath(UNKNOWN_PATH);
  7733. }
  7734. else if (!this.deoptimizedFields.has(path[0])) {
  7735. this.deoptimizePath([path[0]]);
  7736. }
  7737. return UNKNOWN_RETURN_EXPRESSION;
  7738. }
  7739. }
  7740. function getSafeName(baseName, usedNames, forbiddenNames) {
  7741. let safeName = baseName;
  7742. let count = 1;
  7743. while (usedNames.has(safeName) || RESERVED_NAMES$1.has(safeName) || forbiddenNames?.has(safeName)) {
  7744. safeName = `${baseName}$${toBase64(count++)}`;
  7745. }
  7746. usedNames.add(safeName);
  7747. return safeName;
  7748. }
  7749. let Scope$1 = class Scope {
  7750. constructor() {
  7751. this.children = [];
  7752. this.variables = new Map();
  7753. }
  7754. addDeclaration(identifier, context, init, _isHoisted) {
  7755. const name = identifier.name;
  7756. let variable = this.variables.get(name);
  7757. if (variable) {
  7758. variable.addDeclaration(identifier, init);
  7759. }
  7760. else {
  7761. variable = new LocalVariable(identifier.name, identifier, init || UNDEFINED_EXPRESSION, context);
  7762. this.variables.set(name, variable);
  7763. }
  7764. return variable;
  7765. }
  7766. contains(name) {
  7767. return this.variables.has(name);
  7768. }
  7769. findVariable(_name) {
  7770. throw new Error('Internal Error: findVariable needs to be implemented by a subclass');
  7771. }
  7772. };
  7773. class ChildScope extends Scope$1 {
  7774. constructor(parent) {
  7775. super();
  7776. this.accessedOutsideVariables = new Map();
  7777. this.parent = parent;
  7778. parent.children.push(this);
  7779. }
  7780. addAccessedDynamicImport(importExpression) {
  7781. (this.accessedDynamicImports || (this.accessedDynamicImports = new Set())).add(importExpression);
  7782. if (this.parent instanceof ChildScope) {
  7783. this.parent.addAccessedDynamicImport(importExpression);
  7784. }
  7785. }
  7786. addAccessedGlobals(globals, accessedGlobalsByScope) {
  7787. const accessedGlobals = accessedGlobalsByScope.get(this) || new Set();
  7788. for (const name of globals) {
  7789. accessedGlobals.add(name);
  7790. }
  7791. accessedGlobalsByScope.set(this, accessedGlobals);
  7792. if (this.parent instanceof ChildScope) {
  7793. this.parent.addAccessedGlobals(globals, accessedGlobalsByScope);
  7794. }
  7795. }
  7796. addNamespaceMemberAccess(name, variable) {
  7797. this.accessedOutsideVariables.set(name, variable);
  7798. this.parent.addNamespaceMemberAccess(name, variable);
  7799. }
  7800. addReturnExpression(expression) {
  7801. this.parent instanceof ChildScope && this.parent.addReturnExpression(expression);
  7802. }
  7803. addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope) {
  7804. for (const variable of this.accessedOutsideVariables.values()) {
  7805. if (variable.included) {
  7806. usedNames.add(variable.getBaseVariableName());
  7807. if (format === 'system' && exportNamesByVariable.has(variable)) {
  7808. usedNames.add('exports');
  7809. }
  7810. }
  7811. }
  7812. const accessedGlobals = accessedGlobalsByScope.get(this);
  7813. if (accessedGlobals) {
  7814. for (const name of accessedGlobals) {
  7815. usedNames.add(name);
  7816. }
  7817. }
  7818. }
  7819. contains(name) {
  7820. return this.variables.has(name) || this.parent.contains(name);
  7821. }
  7822. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  7823. const usedNames = new Set();
  7824. this.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
  7825. if (this.accessedDynamicImports) {
  7826. for (const importExpression of this.accessedDynamicImports) {
  7827. if (importExpression.inlineNamespace) {
  7828. usedNames.add(importExpression.inlineNamespace.getBaseVariableName());
  7829. }
  7830. }
  7831. }
  7832. for (const [name, variable] of this.variables) {
  7833. if (variable.included || variable.alwaysRendered) {
  7834. variable.setRenderNames(null, getSafeName(name, usedNames, variable.forbiddenNames));
  7835. }
  7836. }
  7837. for (const scope of this.children) {
  7838. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  7839. }
  7840. }
  7841. findLexicalBoundary() {
  7842. return this.parent.findLexicalBoundary();
  7843. }
  7844. findVariable(name) {
  7845. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  7846. if (knownVariable) {
  7847. return knownVariable;
  7848. }
  7849. const variable = this.parent.findVariable(name);
  7850. this.accessedOutsideVariables.set(name, variable);
  7851. return variable;
  7852. }
  7853. }
  7854. class ParameterScope extends ChildScope {
  7855. constructor(parent, context) {
  7856. super(parent);
  7857. this.parameters = [];
  7858. this.hasRest = false;
  7859. this.context = context;
  7860. this.hoistedBodyVarScope = new ChildScope(this);
  7861. }
  7862. /**
  7863. * Adds a parameter to this scope. Parameters must be added in the correct
  7864. * order, i.e. from left to right.
  7865. */
  7866. addParameterDeclaration(identifier) {
  7867. const { name } = identifier;
  7868. const variable = new ParameterVariable(name, identifier, this.context);
  7869. const localVariable = this.hoistedBodyVarScope.variables.get(name);
  7870. if (localVariable) {
  7871. this.hoistedBodyVarScope.variables.set(name, variable);
  7872. variable.mergeDeclarations(localVariable);
  7873. }
  7874. this.variables.set(name, variable);
  7875. return variable;
  7876. }
  7877. addParameterVariables(parameters, hasRest) {
  7878. this.parameters = parameters;
  7879. for (const parameterList of parameters) {
  7880. for (const parameter of parameterList) {
  7881. parameter.alwaysRendered = true;
  7882. }
  7883. }
  7884. this.hasRest = hasRest;
  7885. }
  7886. includeCallArguments(context, parameters) {
  7887. let calledFromTryStatement = false;
  7888. let argumentIncluded = false;
  7889. const restParameter = this.hasRest && this.parameters[this.parameters.length - 1];
  7890. for (const checkedArgument of parameters) {
  7891. if (checkedArgument instanceof SpreadElement) {
  7892. for (const argument of parameters) {
  7893. argument.include(context, false);
  7894. }
  7895. break;
  7896. }
  7897. }
  7898. for (let index = parameters.length - 1; index >= 0; index--) {
  7899. const parameterVariables = this.parameters[index] || restParameter;
  7900. const argument = parameters[index];
  7901. if (parameterVariables) {
  7902. calledFromTryStatement = false;
  7903. if (parameterVariables.length === 0) {
  7904. // handle empty destructuring
  7905. argumentIncluded = true;
  7906. }
  7907. else {
  7908. for (const variable of parameterVariables) {
  7909. if (variable.included) {
  7910. argumentIncluded = true;
  7911. }
  7912. if (variable.calledFromTryStatement) {
  7913. calledFromTryStatement = true;
  7914. }
  7915. }
  7916. }
  7917. }
  7918. if (!argumentIncluded && argument.shouldBeIncluded(context)) {
  7919. argumentIncluded = true;
  7920. }
  7921. if (argumentIncluded) {
  7922. argument.include(context, calledFromTryStatement);
  7923. }
  7924. }
  7925. }
  7926. }
  7927. class ReturnValueScope extends ParameterScope {
  7928. constructor() {
  7929. super(...arguments);
  7930. this.returnExpression = null;
  7931. this.returnExpressions = [];
  7932. }
  7933. addReturnExpression(expression) {
  7934. this.returnExpressions.push(expression);
  7935. }
  7936. getReturnExpression() {
  7937. if (this.returnExpression === null)
  7938. this.updateReturnExpression();
  7939. return this.returnExpression;
  7940. }
  7941. updateReturnExpression() {
  7942. if (this.returnExpressions.length === 1) {
  7943. this.returnExpression = this.returnExpressions[0];
  7944. }
  7945. else {
  7946. this.returnExpression = UNKNOWN_EXPRESSION;
  7947. for (const expression of this.returnExpressions) {
  7948. expression.deoptimizePath(UNKNOWN_PATH);
  7949. }
  7950. }
  7951. }
  7952. }
  7953. /** @typedef { import('estree').Node} Node */
  7954. /** @typedef {Node | {
  7955. * type: 'PropertyDefinition';
  7956. * computed: boolean;
  7957. * value: Node
  7958. * }} NodeWithPropertyDefinition */
  7959. /**
  7960. *
  7961. * @param {NodeWithPropertyDefinition} node
  7962. * @param {NodeWithPropertyDefinition} parent
  7963. * @returns {boolean}
  7964. */
  7965. function is_reference (node, parent) {
  7966. if (node.type === 'MemberExpression') {
  7967. return !node.computed && is_reference(node.object, node);
  7968. }
  7969. if (node.type === 'Identifier') {
  7970. if (!parent) return true;
  7971. switch (parent.type) {
  7972. // disregard `bar` in `foo.bar`
  7973. case 'MemberExpression': return parent.computed || node === parent.object;
  7974. // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}`
  7975. case 'MethodDefinition': return parent.computed;
  7976. // disregard the `foo` in `class {foo=bar}` but keep it in `class {[foo]=bar}` and `class {bar=foo}`
  7977. case 'PropertyDefinition': return parent.computed || node === parent.value;
  7978. // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
  7979. case 'Property': return parent.computed || node === parent.value;
  7980. // disregard the `bar` in `export { foo as bar }` or
  7981. // the foo in `import { foo as bar }`
  7982. case 'ExportSpecifier':
  7983. case 'ImportSpecifier': return node === parent.local;
  7984. // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}`
  7985. case 'LabeledStatement':
  7986. case 'BreakStatement':
  7987. case 'ContinueStatement': return false;
  7988. default: return true;
  7989. }
  7990. }
  7991. return false;
  7992. }
  7993. const PureFunctionKey = Symbol('PureFunction');
  7994. const getPureFunctions = ({ treeshake }) => {
  7995. const pureFunctions = Object.create(null);
  7996. for (const functionName of treeshake ? treeshake.manualPureFunctions : []) {
  7997. let currentFunctions = pureFunctions;
  7998. for (const pathSegment of functionName.split('.')) {
  7999. currentFunctions = currentFunctions[pathSegment] || (currentFunctions[pathSegment] = Object.create(null));
  8000. }
  8001. currentFunctions[PureFunctionKey] = true;
  8002. }
  8003. return pureFunctions;
  8004. };
  8005. /* eslint sort-keys: "off" */
  8006. const ValueProperties = Symbol('Value Properties');
  8007. const getTruthyLiteralValue = () => UnknownTruthyValue;
  8008. const returnFalse = () => false;
  8009. const returnTrue = () => true;
  8010. const PURE = {
  8011. deoptimizeArgumentsOnCall: doNothing,
  8012. getLiteralValue: getTruthyLiteralValue,
  8013. hasEffectsWhenCalled: returnFalse
  8014. };
  8015. const IMPURE = {
  8016. deoptimizeArgumentsOnCall: doNothing,
  8017. getLiteralValue: getTruthyLiteralValue,
  8018. hasEffectsWhenCalled: returnTrue
  8019. };
  8020. const PURE_WITH_ARRAY = {
  8021. deoptimizeArgumentsOnCall: doNothing,
  8022. getLiteralValue: getTruthyLiteralValue,
  8023. hasEffectsWhenCalled({ args }) {
  8024. return args.length > 1 && !(args[1] instanceof ArrayExpression);
  8025. }
  8026. };
  8027. const GETTER_ACCESS = {
  8028. deoptimizeArgumentsOnCall: doNothing,
  8029. getLiteralValue: getTruthyLiteralValue,
  8030. hasEffectsWhenCalled({ args }, context) {
  8031. const [_thisArgument, firstArgument] = args;
  8032. return (!(firstArgument instanceof ExpressionEntity) ||
  8033. firstArgument.hasEffectsOnInteractionAtPath(UNKNOWN_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context));
  8034. }
  8035. };
  8036. // We use shortened variables to reduce file size here
  8037. /* OBJECT */
  8038. const O = {
  8039. __proto__: null,
  8040. [ValueProperties]: IMPURE
  8041. };
  8042. /* PURE FUNCTION */
  8043. const PF = {
  8044. __proto__: null,
  8045. [ValueProperties]: PURE
  8046. };
  8047. /* PURE FUNCTION IF FIRST ARG DOES NOT CONTAIN A GETTER */
  8048. const PF_NO_GETTER = {
  8049. __proto__: null,
  8050. [ValueProperties]: GETTER_ACCESS
  8051. };
  8052. /* FUNCTION THAT MUTATES FIRST ARG WITHOUT TRIGGERING ACCESSORS */
  8053. const MUTATES_ARG_WITHOUT_ACCESSOR = {
  8054. __proto__: null,
  8055. [ValueProperties]: {
  8056. deoptimizeArgumentsOnCall({ args: [, firstArgument] }) {
  8057. firstArgument?.deoptimizePath(UNKNOWN_PATH);
  8058. },
  8059. getLiteralValue: getTruthyLiteralValue,
  8060. hasEffectsWhenCalled({ args }, context) {
  8061. return (args.length <= 1 ||
  8062. args[1].hasEffectsOnInteractionAtPath(UNKNOWN_NON_ACCESSOR_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context));
  8063. }
  8064. }
  8065. };
  8066. /* CONSTRUCTOR */
  8067. const C = {
  8068. __proto__: null,
  8069. [ValueProperties]: IMPURE,
  8070. prototype: O
  8071. };
  8072. /* PURE CONSTRUCTOR */
  8073. const PC = {
  8074. __proto__: null,
  8075. [ValueProperties]: PURE,
  8076. prototype: O
  8077. };
  8078. const PC_WITH_ARRAY = {
  8079. __proto__: null,
  8080. [ValueProperties]: PURE_WITH_ARRAY,
  8081. prototype: O
  8082. };
  8083. const ARRAY_TYPE = {
  8084. __proto__: null,
  8085. [ValueProperties]: PURE,
  8086. from: O,
  8087. of: PF,
  8088. prototype: O
  8089. };
  8090. const INTL_MEMBER = {
  8091. __proto__: null,
  8092. [ValueProperties]: PURE,
  8093. supportedLocalesOf: PC
  8094. };
  8095. const knownGlobals = {
  8096. // Placeholders for global objects to avoid shape mutations
  8097. global: O,
  8098. globalThis: O,
  8099. self: O,
  8100. window: O,
  8101. // Common globals
  8102. __proto__: null,
  8103. [ValueProperties]: IMPURE,
  8104. Array: {
  8105. __proto__: null,
  8106. [ValueProperties]: IMPURE,
  8107. from: O,
  8108. isArray: PF,
  8109. of: PF,
  8110. prototype: O
  8111. },
  8112. ArrayBuffer: {
  8113. __proto__: null,
  8114. [ValueProperties]: PURE,
  8115. isView: PF,
  8116. prototype: O
  8117. },
  8118. Atomics: O,
  8119. BigInt: C,
  8120. BigInt64Array: C,
  8121. BigUint64Array: C,
  8122. Boolean: PC,
  8123. constructor: C,
  8124. DataView: PC,
  8125. Date: {
  8126. __proto__: null,
  8127. [ValueProperties]: PURE,
  8128. now: PF,
  8129. parse: PF,
  8130. prototype: O,
  8131. UTC: PF
  8132. },
  8133. decodeURI: PF,
  8134. decodeURIComponent: PF,
  8135. encodeURI: PF,
  8136. encodeURIComponent: PF,
  8137. Error: PC,
  8138. escape: PF,
  8139. eval: O,
  8140. EvalError: PC,
  8141. Float32Array: ARRAY_TYPE,
  8142. Float64Array: ARRAY_TYPE,
  8143. Function: C,
  8144. hasOwnProperty: O,
  8145. Infinity: O,
  8146. Int16Array: ARRAY_TYPE,
  8147. Int32Array: ARRAY_TYPE,
  8148. Int8Array: ARRAY_TYPE,
  8149. isFinite: PF,
  8150. isNaN: PF,
  8151. isPrototypeOf: O,
  8152. JSON: O,
  8153. Map: PC_WITH_ARRAY,
  8154. Math: {
  8155. __proto__: null,
  8156. [ValueProperties]: IMPURE,
  8157. abs: PF,
  8158. acos: PF,
  8159. acosh: PF,
  8160. asin: PF,
  8161. asinh: PF,
  8162. atan: PF,
  8163. atan2: PF,
  8164. atanh: PF,
  8165. cbrt: PF,
  8166. ceil: PF,
  8167. clz32: PF,
  8168. cos: PF,
  8169. cosh: PF,
  8170. exp: PF,
  8171. expm1: PF,
  8172. floor: PF,
  8173. fround: PF,
  8174. hypot: PF,
  8175. imul: PF,
  8176. log: PF,
  8177. log10: PF,
  8178. log1p: PF,
  8179. log2: PF,
  8180. max: PF,
  8181. min: PF,
  8182. pow: PF,
  8183. random: PF,
  8184. round: PF,
  8185. sign: PF,
  8186. sin: PF,
  8187. sinh: PF,
  8188. sqrt: PF,
  8189. tan: PF,
  8190. tanh: PF,
  8191. trunc: PF
  8192. },
  8193. NaN: O,
  8194. Number: {
  8195. __proto__: null,
  8196. [ValueProperties]: PURE,
  8197. isFinite: PF,
  8198. isInteger: PF,
  8199. isNaN: PF,
  8200. isSafeInteger: PF,
  8201. parseFloat: PF,
  8202. parseInt: PF,
  8203. prototype: O
  8204. },
  8205. Object: {
  8206. __proto__: null,
  8207. [ValueProperties]: PURE,
  8208. create: PF,
  8209. // Technically those can throw in certain situations, but we ignore this as
  8210. // code that relies on this will hopefully wrap this in a try-catch, which
  8211. // deoptimizes everything anyway
  8212. defineProperty: MUTATES_ARG_WITHOUT_ACCESSOR,
  8213. defineProperties: MUTATES_ARG_WITHOUT_ACCESSOR,
  8214. freeze: MUTATES_ARG_WITHOUT_ACCESSOR,
  8215. getOwnPropertyDescriptor: PF,
  8216. getOwnPropertyDescriptors: PF,
  8217. getOwnPropertyNames: PF,
  8218. getOwnPropertySymbols: PF,
  8219. getPrototypeOf: PF,
  8220. hasOwn: PF,
  8221. is: PF,
  8222. isExtensible: PF,
  8223. isFrozen: PF,
  8224. isSealed: PF,
  8225. keys: PF,
  8226. fromEntries: O,
  8227. entries: PF_NO_GETTER,
  8228. values: PF_NO_GETTER,
  8229. prototype: O
  8230. },
  8231. parseFloat: PF,
  8232. parseInt: PF,
  8233. Promise: {
  8234. __proto__: null,
  8235. [ValueProperties]: IMPURE,
  8236. all: O,
  8237. allSettled: O,
  8238. any: O,
  8239. prototype: O,
  8240. race: O,
  8241. reject: O,
  8242. resolve: O
  8243. },
  8244. propertyIsEnumerable: O,
  8245. Proxy: O,
  8246. RangeError: PC,
  8247. ReferenceError: PC,
  8248. Reflect: O,
  8249. RegExp: PC,
  8250. Set: PC_WITH_ARRAY,
  8251. SharedArrayBuffer: C,
  8252. String: {
  8253. __proto__: null,
  8254. [ValueProperties]: PURE,
  8255. fromCharCode: PF,
  8256. fromCodePoint: PF,
  8257. prototype: O,
  8258. raw: PF
  8259. },
  8260. Symbol: {
  8261. __proto__: null,
  8262. [ValueProperties]: PURE,
  8263. for: PF,
  8264. keyFor: PF,
  8265. prototype: O,
  8266. toStringTag: {
  8267. __proto__: null,
  8268. [ValueProperties]: {
  8269. deoptimizeArgumentsOnCall: doNothing,
  8270. getLiteralValue() {
  8271. return SymbolToStringTag;
  8272. },
  8273. hasEffectsWhenCalled: returnTrue
  8274. }
  8275. }
  8276. },
  8277. SyntaxError: PC,
  8278. toLocaleString: O,
  8279. toString: O,
  8280. TypeError: PC,
  8281. Uint16Array: ARRAY_TYPE,
  8282. Uint32Array: ARRAY_TYPE,
  8283. Uint8Array: ARRAY_TYPE,
  8284. Uint8ClampedArray: ARRAY_TYPE,
  8285. // Technically, this is a global, but it needs special handling
  8286. // undefined: ?,
  8287. unescape: PF,
  8288. URIError: PC,
  8289. valueOf: O,
  8290. WeakMap: PC_WITH_ARRAY,
  8291. WeakSet: PC_WITH_ARRAY,
  8292. // Additional globals shared by Node and Browser that are not strictly part of the language
  8293. clearInterval: C,
  8294. clearTimeout: C,
  8295. console: {
  8296. __proto__: null,
  8297. [ValueProperties]: IMPURE,
  8298. assert: C,
  8299. clear: C,
  8300. count: C,
  8301. countReset: C,
  8302. debug: C,
  8303. dir: C,
  8304. dirxml: C,
  8305. error: C,
  8306. exception: C,
  8307. group: C,
  8308. groupCollapsed: C,
  8309. groupEnd: C,
  8310. info: C,
  8311. log: C,
  8312. table: C,
  8313. time: C,
  8314. timeEnd: C,
  8315. timeLog: C,
  8316. trace: C,
  8317. warn: C
  8318. },
  8319. Intl: {
  8320. __proto__: null,
  8321. [ValueProperties]: IMPURE,
  8322. Collator: INTL_MEMBER,
  8323. DateTimeFormat: INTL_MEMBER,
  8324. DisplayNames: INTL_MEMBER,
  8325. ListFormat: INTL_MEMBER,
  8326. Locale: INTL_MEMBER,
  8327. NumberFormat: INTL_MEMBER,
  8328. PluralRules: INTL_MEMBER,
  8329. RelativeTimeFormat: INTL_MEMBER,
  8330. Segmenter: INTL_MEMBER
  8331. },
  8332. setInterval: C,
  8333. setTimeout: C,
  8334. TextDecoder: C,
  8335. TextEncoder: C,
  8336. URL: {
  8337. __proto__: null,
  8338. [ValueProperties]: IMPURE,
  8339. prototype: O,
  8340. canParse: PF
  8341. },
  8342. URLSearchParams: C,
  8343. // Browser specific globals
  8344. AbortController: C,
  8345. AbortSignal: C,
  8346. addEventListener: O,
  8347. alert: O,
  8348. AnalyserNode: C,
  8349. Animation: C,
  8350. AnimationEvent: C,
  8351. applicationCache: O,
  8352. ApplicationCache: C,
  8353. ApplicationCacheErrorEvent: C,
  8354. atob: O,
  8355. Attr: C,
  8356. Audio: C,
  8357. AudioBuffer: C,
  8358. AudioBufferSourceNode: C,
  8359. AudioContext: C,
  8360. AudioDestinationNode: C,
  8361. AudioListener: C,
  8362. AudioNode: C,
  8363. AudioParam: C,
  8364. AudioProcessingEvent: C,
  8365. AudioScheduledSourceNode: C,
  8366. AudioWorkletNode: C,
  8367. BarProp: C,
  8368. BaseAudioContext: C,
  8369. BatteryManager: C,
  8370. BeforeUnloadEvent: C,
  8371. BiquadFilterNode: C,
  8372. Blob: C,
  8373. BlobEvent: C,
  8374. blur: O,
  8375. BroadcastChannel: C,
  8376. btoa: O,
  8377. ByteLengthQueuingStrategy: C,
  8378. Cache: C,
  8379. caches: O,
  8380. CacheStorage: C,
  8381. cancelAnimationFrame: O,
  8382. cancelIdleCallback: O,
  8383. CanvasCaptureMediaStreamTrack: C,
  8384. CanvasGradient: C,
  8385. CanvasPattern: C,
  8386. CanvasRenderingContext2D: C,
  8387. ChannelMergerNode: C,
  8388. ChannelSplitterNode: C,
  8389. CharacterData: C,
  8390. clientInformation: O,
  8391. ClipboardEvent: C,
  8392. close: O,
  8393. closed: O,
  8394. CloseEvent: C,
  8395. Comment: C,
  8396. CompositionEvent: C,
  8397. confirm: O,
  8398. ConstantSourceNode: C,
  8399. ConvolverNode: C,
  8400. CountQueuingStrategy: C,
  8401. createImageBitmap: O,
  8402. Credential: C,
  8403. CredentialsContainer: C,
  8404. crypto: O,
  8405. Crypto: C,
  8406. CryptoKey: C,
  8407. CSS: C,
  8408. CSSConditionRule: C,
  8409. CSSFontFaceRule: C,
  8410. CSSGroupingRule: C,
  8411. CSSImportRule: C,
  8412. CSSKeyframeRule: C,
  8413. CSSKeyframesRule: C,
  8414. CSSMediaRule: C,
  8415. CSSNamespaceRule: C,
  8416. CSSPageRule: C,
  8417. CSSRule: C,
  8418. CSSRuleList: C,
  8419. CSSStyleDeclaration: C,
  8420. CSSStyleRule: C,
  8421. CSSStyleSheet: C,
  8422. CSSSupportsRule: C,
  8423. CustomElementRegistry: C,
  8424. customElements: O,
  8425. CustomEvent: {
  8426. __proto__: null,
  8427. [ValueProperties]: {
  8428. deoptimizeArgumentsOnCall({ args }) {
  8429. args[2]?.deoptimizePath(['detail']);
  8430. },
  8431. getLiteralValue: getTruthyLiteralValue,
  8432. hasEffectsWhenCalled: returnFalse
  8433. },
  8434. prototype: O
  8435. },
  8436. DataTransfer: C,
  8437. DataTransferItem: C,
  8438. DataTransferItemList: C,
  8439. defaultstatus: O,
  8440. defaultStatus: O,
  8441. DelayNode: C,
  8442. DeviceMotionEvent: C,
  8443. DeviceOrientationEvent: C,
  8444. devicePixelRatio: O,
  8445. dispatchEvent: O,
  8446. document: O,
  8447. Document: C,
  8448. DocumentFragment: C,
  8449. DocumentType: C,
  8450. DOMError: C,
  8451. DOMException: C,
  8452. DOMImplementation: C,
  8453. DOMMatrix: C,
  8454. DOMMatrixReadOnly: C,
  8455. DOMParser: C,
  8456. DOMPoint: C,
  8457. DOMPointReadOnly: C,
  8458. DOMQuad: C,
  8459. DOMRect: C,
  8460. DOMRectReadOnly: C,
  8461. DOMStringList: C,
  8462. DOMStringMap: C,
  8463. DOMTokenList: C,
  8464. DragEvent: C,
  8465. DynamicsCompressorNode: C,
  8466. Element: C,
  8467. ErrorEvent: C,
  8468. Event: C,
  8469. EventSource: C,
  8470. EventTarget: C,
  8471. external: O,
  8472. fetch: O,
  8473. File: C,
  8474. FileList: C,
  8475. FileReader: C,
  8476. find: O,
  8477. focus: O,
  8478. FocusEvent: C,
  8479. FontFace: C,
  8480. FontFaceSetLoadEvent: C,
  8481. FormData: C,
  8482. frames: O,
  8483. GainNode: C,
  8484. Gamepad: C,
  8485. GamepadButton: C,
  8486. GamepadEvent: C,
  8487. getComputedStyle: O,
  8488. getSelection: O,
  8489. HashChangeEvent: C,
  8490. Headers: C,
  8491. history: O,
  8492. History: C,
  8493. HTMLAllCollection: C,
  8494. HTMLAnchorElement: C,
  8495. HTMLAreaElement: C,
  8496. HTMLAudioElement: C,
  8497. HTMLBaseElement: C,
  8498. HTMLBodyElement: C,
  8499. HTMLBRElement: C,
  8500. HTMLButtonElement: C,
  8501. HTMLCanvasElement: C,
  8502. HTMLCollection: C,
  8503. HTMLContentElement: C,
  8504. HTMLDataElement: C,
  8505. HTMLDataListElement: C,
  8506. HTMLDetailsElement: C,
  8507. HTMLDialogElement: C,
  8508. HTMLDirectoryElement: C,
  8509. HTMLDivElement: C,
  8510. HTMLDListElement: C,
  8511. HTMLDocument: C,
  8512. HTMLElement: C,
  8513. HTMLEmbedElement: C,
  8514. HTMLFieldSetElement: C,
  8515. HTMLFontElement: C,
  8516. HTMLFormControlsCollection: C,
  8517. HTMLFormElement: C,
  8518. HTMLFrameElement: C,
  8519. HTMLFrameSetElement: C,
  8520. HTMLHeadElement: C,
  8521. HTMLHeadingElement: C,
  8522. HTMLHRElement: C,
  8523. HTMLHtmlElement: C,
  8524. HTMLIFrameElement: C,
  8525. HTMLImageElement: C,
  8526. HTMLInputElement: C,
  8527. HTMLLabelElement: C,
  8528. HTMLLegendElement: C,
  8529. HTMLLIElement: C,
  8530. HTMLLinkElement: C,
  8531. HTMLMapElement: C,
  8532. HTMLMarqueeElement: C,
  8533. HTMLMediaElement: C,
  8534. HTMLMenuElement: C,
  8535. HTMLMetaElement: C,
  8536. HTMLMeterElement: C,
  8537. HTMLModElement: C,
  8538. HTMLObjectElement: C,
  8539. HTMLOListElement: C,
  8540. HTMLOptGroupElement: C,
  8541. HTMLOptionElement: C,
  8542. HTMLOptionsCollection: C,
  8543. HTMLOutputElement: C,
  8544. HTMLParagraphElement: C,
  8545. HTMLParamElement: C,
  8546. HTMLPictureElement: C,
  8547. HTMLPreElement: C,
  8548. HTMLProgressElement: C,
  8549. HTMLQuoteElement: C,
  8550. HTMLScriptElement: C,
  8551. HTMLSelectElement: C,
  8552. HTMLShadowElement: C,
  8553. HTMLSlotElement: C,
  8554. HTMLSourceElement: C,
  8555. HTMLSpanElement: C,
  8556. HTMLStyleElement: C,
  8557. HTMLTableCaptionElement: C,
  8558. HTMLTableCellElement: C,
  8559. HTMLTableColElement: C,
  8560. HTMLTableElement: C,
  8561. HTMLTableRowElement: C,
  8562. HTMLTableSectionElement: C,
  8563. HTMLTemplateElement: C,
  8564. HTMLTextAreaElement: C,
  8565. HTMLTimeElement: C,
  8566. HTMLTitleElement: C,
  8567. HTMLTrackElement: C,
  8568. HTMLUListElement: C,
  8569. HTMLUnknownElement: C,
  8570. HTMLVideoElement: C,
  8571. IDBCursor: C,
  8572. IDBCursorWithValue: C,
  8573. IDBDatabase: C,
  8574. IDBFactory: C,
  8575. IDBIndex: C,
  8576. IDBKeyRange: C,
  8577. IDBObjectStore: C,
  8578. IDBOpenDBRequest: C,
  8579. IDBRequest: C,
  8580. IDBTransaction: C,
  8581. IDBVersionChangeEvent: C,
  8582. IdleDeadline: C,
  8583. IIRFilterNode: C,
  8584. Image: C,
  8585. ImageBitmap: C,
  8586. ImageBitmapRenderingContext: C,
  8587. ImageCapture: C,
  8588. ImageData: C,
  8589. indexedDB: O,
  8590. innerHeight: O,
  8591. innerWidth: O,
  8592. InputEvent: C,
  8593. IntersectionObserver: C,
  8594. IntersectionObserverEntry: C,
  8595. isSecureContext: O,
  8596. KeyboardEvent: C,
  8597. KeyframeEffect: C,
  8598. length: O,
  8599. localStorage: O,
  8600. location: O,
  8601. Location: C,
  8602. locationbar: O,
  8603. matchMedia: O,
  8604. MediaDeviceInfo: C,
  8605. MediaDevices: C,
  8606. MediaElementAudioSourceNode: C,
  8607. MediaEncryptedEvent: C,
  8608. MediaError: C,
  8609. MediaKeyMessageEvent: C,
  8610. MediaKeySession: C,
  8611. MediaKeyStatusMap: C,
  8612. MediaKeySystemAccess: C,
  8613. MediaList: C,
  8614. MediaQueryList: C,
  8615. MediaQueryListEvent: C,
  8616. MediaRecorder: C,
  8617. MediaSettingsRange: C,
  8618. MediaSource: C,
  8619. MediaStream: C,
  8620. MediaStreamAudioDestinationNode: C,
  8621. MediaStreamAudioSourceNode: C,
  8622. MediaStreamEvent: C,
  8623. MediaStreamTrack: C,
  8624. MediaStreamTrackEvent: C,
  8625. menubar: O,
  8626. MessageChannel: C,
  8627. MessageEvent: C,
  8628. MessagePort: C,
  8629. MIDIAccess: C,
  8630. MIDIConnectionEvent: C,
  8631. MIDIInput: C,
  8632. MIDIInputMap: C,
  8633. MIDIMessageEvent: C,
  8634. MIDIOutput: C,
  8635. MIDIOutputMap: C,
  8636. MIDIPort: C,
  8637. MimeType: C,
  8638. MimeTypeArray: C,
  8639. MouseEvent: C,
  8640. moveBy: O,
  8641. moveTo: O,
  8642. MutationEvent: C,
  8643. MutationObserver: C,
  8644. MutationRecord: C,
  8645. name: O,
  8646. NamedNodeMap: C,
  8647. NavigationPreloadManager: C,
  8648. navigator: O,
  8649. Navigator: C,
  8650. NetworkInformation: C,
  8651. Node: C,
  8652. NodeFilter: O,
  8653. NodeIterator: C,
  8654. NodeList: C,
  8655. Notification: C,
  8656. OfflineAudioCompletionEvent: C,
  8657. OfflineAudioContext: C,
  8658. offscreenBuffering: O,
  8659. OffscreenCanvas: C,
  8660. open: O,
  8661. openDatabase: O,
  8662. Option: C,
  8663. origin: O,
  8664. OscillatorNode: C,
  8665. outerHeight: O,
  8666. outerWidth: O,
  8667. PageTransitionEvent: C,
  8668. pageXOffset: O,
  8669. pageYOffset: O,
  8670. PannerNode: C,
  8671. parent: O,
  8672. Path2D: C,
  8673. PaymentAddress: C,
  8674. PaymentRequest: C,
  8675. PaymentRequestUpdateEvent: C,
  8676. PaymentResponse: C,
  8677. performance: O,
  8678. Performance: C,
  8679. PerformanceEntry: C,
  8680. PerformanceLongTaskTiming: C,
  8681. PerformanceMark: C,
  8682. PerformanceMeasure: C,
  8683. PerformanceNavigation: C,
  8684. PerformanceNavigationTiming: C,
  8685. PerformanceObserver: C,
  8686. PerformanceObserverEntryList: C,
  8687. PerformancePaintTiming: C,
  8688. PerformanceResourceTiming: C,
  8689. PerformanceTiming: C,
  8690. PeriodicWave: C,
  8691. Permissions: C,
  8692. PermissionStatus: C,
  8693. personalbar: O,
  8694. PhotoCapabilities: C,
  8695. Plugin: C,
  8696. PluginArray: C,
  8697. PointerEvent: C,
  8698. PopStateEvent: C,
  8699. postMessage: O,
  8700. Presentation: C,
  8701. PresentationAvailability: C,
  8702. PresentationConnection: C,
  8703. PresentationConnectionAvailableEvent: C,
  8704. PresentationConnectionCloseEvent: C,
  8705. PresentationConnectionList: C,
  8706. PresentationReceiver: C,
  8707. PresentationRequest: C,
  8708. print: O,
  8709. ProcessingInstruction: C,
  8710. ProgressEvent: C,
  8711. PromiseRejectionEvent: C,
  8712. prompt: O,
  8713. PushManager: C,
  8714. PushSubscription: C,
  8715. PushSubscriptionOptions: C,
  8716. queueMicrotask: O,
  8717. RadioNodeList: C,
  8718. Range: C,
  8719. ReadableStream: C,
  8720. RemotePlayback: C,
  8721. removeEventListener: O,
  8722. Request: C,
  8723. requestAnimationFrame: O,
  8724. requestIdleCallback: O,
  8725. resizeBy: O,
  8726. ResizeObserver: C,
  8727. ResizeObserverEntry: C,
  8728. resizeTo: O,
  8729. Response: C,
  8730. RTCCertificate: C,
  8731. RTCDataChannel: C,
  8732. RTCDataChannelEvent: C,
  8733. RTCDtlsTransport: C,
  8734. RTCIceCandidate: C,
  8735. RTCIceTransport: C,
  8736. RTCPeerConnection: C,
  8737. RTCPeerConnectionIceEvent: C,
  8738. RTCRtpReceiver: C,
  8739. RTCRtpSender: C,
  8740. RTCSctpTransport: C,
  8741. RTCSessionDescription: C,
  8742. RTCStatsReport: C,
  8743. RTCTrackEvent: C,
  8744. screen: O,
  8745. Screen: C,
  8746. screenLeft: O,
  8747. ScreenOrientation: C,
  8748. screenTop: O,
  8749. screenX: O,
  8750. screenY: O,
  8751. ScriptProcessorNode: C,
  8752. scroll: O,
  8753. scrollbars: O,
  8754. scrollBy: O,
  8755. scrollTo: O,
  8756. scrollX: O,
  8757. scrollY: O,
  8758. SecurityPolicyViolationEvent: C,
  8759. Selection: C,
  8760. ServiceWorker: C,
  8761. ServiceWorkerContainer: C,
  8762. ServiceWorkerRegistration: C,
  8763. sessionStorage: O,
  8764. ShadowRoot: C,
  8765. SharedWorker: C,
  8766. SourceBuffer: C,
  8767. SourceBufferList: C,
  8768. speechSynthesis: O,
  8769. SpeechSynthesisEvent: C,
  8770. SpeechSynthesisUtterance: C,
  8771. StaticRange: C,
  8772. status: O,
  8773. statusbar: O,
  8774. StereoPannerNode: C,
  8775. stop: O,
  8776. Storage: C,
  8777. StorageEvent: C,
  8778. StorageManager: C,
  8779. styleMedia: O,
  8780. StyleSheet: C,
  8781. StyleSheetList: C,
  8782. SubtleCrypto: C,
  8783. SVGAElement: C,
  8784. SVGAngle: C,
  8785. SVGAnimatedAngle: C,
  8786. SVGAnimatedBoolean: C,
  8787. SVGAnimatedEnumeration: C,
  8788. SVGAnimatedInteger: C,
  8789. SVGAnimatedLength: C,
  8790. SVGAnimatedLengthList: C,
  8791. SVGAnimatedNumber: C,
  8792. SVGAnimatedNumberList: C,
  8793. SVGAnimatedPreserveAspectRatio: C,
  8794. SVGAnimatedRect: C,
  8795. SVGAnimatedString: C,
  8796. SVGAnimatedTransformList: C,
  8797. SVGAnimateElement: C,
  8798. SVGAnimateMotionElement: C,
  8799. SVGAnimateTransformElement: C,
  8800. SVGAnimationElement: C,
  8801. SVGCircleElement: C,
  8802. SVGClipPathElement: C,
  8803. SVGComponentTransferFunctionElement: C,
  8804. SVGDefsElement: C,
  8805. SVGDescElement: C,
  8806. SVGDiscardElement: C,
  8807. SVGElement: C,
  8808. SVGEllipseElement: C,
  8809. SVGFEBlendElement: C,
  8810. SVGFEColorMatrixElement: C,
  8811. SVGFEComponentTransferElement: C,
  8812. SVGFECompositeElement: C,
  8813. SVGFEConvolveMatrixElement: C,
  8814. SVGFEDiffuseLightingElement: C,
  8815. SVGFEDisplacementMapElement: C,
  8816. SVGFEDistantLightElement: C,
  8817. SVGFEDropShadowElement: C,
  8818. SVGFEFloodElement: C,
  8819. SVGFEFuncAElement: C,
  8820. SVGFEFuncBElement: C,
  8821. SVGFEFuncGElement: C,
  8822. SVGFEFuncRElement: C,
  8823. SVGFEGaussianBlurElement: C,
  8824. SVGFEImageElement: C,
  8825. SVGFEMergeElement: C,
  8826. SVGFEMergeNodeElement: C,
  8827. SVGFEMorphologyElement: C,
  8828. SVGFEOffsetElement: C,
  8829. SVGFEPointLightElement: C,
  8830. SVGFESpecularLightingElement: C,
  8831. SVGFESpotLightElement: C,
  8832. SVGFETileElement: C,
  8833. SVGFETurbulenceElement: C,
  8834. SVGFilterElement: C,
  8835. SVGForeignObjectElement: C,
  8836. SVGGElement: C,
  8837. SVGGeometryElement: C,
  8838. SVGGradientElement: C,
  8839. SVGGraphicsElement: C,
  8840. SVGImageElement: C,
  8841. SVGLength: C,
  8842. SVGLengthList: C,
  8843. SVGLinearGradientElement: C,
  8844. SVGLineElement: C,
  8845. SVGMarkerElement: C,
  8846. SVGMaskElement: C,
  8847. SVGMatrix: C,
  8848. SVGMetadataElement: C,
  8849. SVGMPathElement: C,
  8850. SVGNumber: C,
  8851. SVGNumberList: C,
  8852. SVGPathElement: C,
  8853. SVGPatternElement: C,
  8854. SVGPoint: C,
  8855. SVGPointList: C,
  8856. SVGPolygonElement: C,
  8857. SVGPolylineElement: C,
  8858. SVGPreserveAspectRatio: C,
  8859. SVGRadialGradientElement: C,
  8860. SVGRect: C,
  8861. SVGRectElement: C,
  8862. SVGScriptElement: C,
  8863. SVGSetElement: C,
  8864. SVGStopElement: C,
  8865. SVGStringList: C,
  8866. SVGStyleElement: C,
  8867. SVGSVGElement: C,
  8868. SVGSwitchElement: C,
  8869. SVGSymbolElement: C,
  8870. SVGTextContentElement: C,
  8871. SVGTextElement: C,
  8872. SVGTextPathElement: C,
  8873. SVGTextPositioningElement: C,
  8874. SVGTitleElement: C,
  8875. SVGTransform: C,
  8876. SVGTransformList: C,
  8877. SVGTSpanElement: C,
  8878. SVGUnitTypes: C,
  8879. SVGUseElement: C,
  8880. SVGViewElement: C,
  8881. TaskAttributionTiming: C,
  8882. Text: C,
  8883. TextEvent: C,
  8884. TextMetrics: C,
  8885. TextTrack: C,
  8886. TextTrackCue: C,
  8887. TextTrackCueList: C,
  8888. TextTrackList: C,
  8889. TimeRanges: C,
  8890. toolbar: O,
  8891. top: O,
  8892. Touch: C,
  8893. TouchEvent: C,
  8894. TouchList: C,
  8895. TrackEvent: C,
  8896. TransitionEvent: C,
  8897. TreeWalker: C,
  8898. UIEvent: C,
  8899. ValidityState: C,
  8900. visualViewport: O,
  8901. VisualViewport: C,
  8902. VTTCue: C,
  8903. WaveShaperNode: C,
  8904. WebAssembly: O,
  8905. WebGL2RenderingContext: C,
  8906. WebGLActiveInfo: C,
  8907. WebGLBuffer: C,
  8908. WebGLContextEvent: C,
  8909. WebGLFramebuffer: C,
  8910. WebGLProgram: C,
  8911. WebGLQuery: C,
  8912. WebGLRenderbuffer: C,
  8913. WebGLRenderingContext: C,
  8914. WebGLSampler: C,
  8915. WebGLShader: C,
  8916. WebGLShaderPrecisionFormat: C,
  8917. WebGLSync: C,
  8918. WebGLTexture: C,
  8919. WebGLTransformFeedback: C,
  8920. WebGLUniformLocation: C,
  8921. WebGLVertexArrayObject: C,
  8922. WebSocket: C,
  8923. WheelEvent: C,
  8924. Window: C,
  8925. Worker: C,
  8926. WritableStream: C,
  8927. XMLDocument: C,
  8928. XMLHttpRequest: C,
  8929. XMLHttpRequestEventTarget: C,
  8930. XMLHttpRequestUpload: C,
  8931. XMLSerializer: C,
  8932. XPathEvaluator: C,
  8933. XPathExpression: C,
  8934. XPathResult: C,
  8935. XSLTProcessor: C
  8936. };
  8937. for (const global of ['window', 'global', 'self', 'globalThis']) {
  8938. knownGlobals[global] = knownGlobals;
  8939. }
  8940. function getGlobalAtPath(path) {
  8941. let currentGlobal = knownGlobals;
  8942. for (const pathSegment of path) {
  8943. if (typeof pathSegment !== 'string') {
  8944. return null;
  8945. }
  8946. currentGlobal = currentGlobal[pathSegment];
  8947. if (!currentGlobal) {
  8948. return null;
  8949. }
  8950. }
  8951. return currentGlobal[ValueProperties];
  8952. }
  8953. class GlobalVariable extends Variable {
  8954. constructor() {
  8955. super(...arguments);
  8956. // Ensure we use live-bindings for globals as we do not know if they have
  8957. // been reassigned
  8958. this.isReassigned = true;
  8959. }
  8960. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  8961. switch (interaction.type) {
  8962. // While there is no point in testing these cases as at the moment, they
  8963. // are also covered via other means, we keep them for completeness
  8964. case INTERACTION_ACCESSED:
  8965. case INTERACTION_ASSIGNED: {
  8966. if (!getGlobalAtPath([this.name, ...path].slice(0, -1))) {
  8967. super.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  8968. }
  8969. return;
  8970. }
  8971. case INTERACTION_CALLED: {
  8972. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  8973. if (globalAtPath) {
  8974. globalAtPath.deoptimizeArgumentsOnCall(interaction);
  8975. }
  8976. else {
  8977. super.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  8978. }
  8979. return;
  8980. }
  8981. }
  8982. }
  8983. getLiteralValueAtPath(path, _recursionTracker, _origin) {
  8984. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  8985. return globalAtPath ? globalAtPath.getLiteralValue() : UnknownValue;
  8986. }
  8987. hasEffectsOnInteractionAtPath(path, interaction, context) {
  8988. switch (interaction.type) {
  8989. case INTERACTION_ACCESSED: {
  8990. if (path.length === 0) {
  8991. // Technically, "undefined" is a global variable of sorts
  8992. return this.name !== 'undefined' && !getGlobalAtPath([this.name]);
  8993. }
  8994. return !getGlobalAtPath([this.name, ...path].slice(0, -1));
  8995. }
  8996. case INTERACTION_ASSIGNED: {
  8997. return true;
  8998. }
  8999. case INTERACTION_CALLED: {
  9000. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  9001. return !globalAtPath || globalAtPath.hasEffectsWhenCalled(interaction, context);
  9002. }
  9003. }
  9004. }
  9005. }
  9006. const tdzVariableKinds = {
  9007. __proto__: null,
  9008. class: true,
  9009. const: true,
  9010. let: true,
  9011. var: true
  9012. };
  9013. class Identifier extends NodeBase {
  9014. constructor() {
  9015. super(...arguments);
  9016. this.variable = null;
  9017. this.isTDZAccess = null;
  9018. }
  9019. addExportedVariables(variables, exportNamesByVariable) {
  9020. if (exportNamesByVariable.has(this.variable)) {
  9021. variables.push(this.variable);
  9022. }
  9023. }
  9024. bind() {
  9025. if (!this.variable && is_reference(this, this.parent)) {
  9026. this.variable = this.scope.findVariable(this.name);
  9027. this.variable.addReference(this);
  9028. }
  9029. }
  9030. declare(kind, init) {
  9031. let variable;
  9032. const { treeshake } = this.context.options;
  9033. switch (kind) {
  9034. case 'var': {
  9035. variable = this.scope.addDeclaration(this, this.context, init, true);
  9036. if (treeshake && treeshake.correctVarValueBeforeDeclaration) {
  9037. // Necessary to make sure the init is deoptimized. We cannot call deoptimizePath here.
  9038. variable.markInitializersForDeoptimization();
  9039. }
  9040. break;
  9041. }
  9042. case 'function': {
  9043. // in strict mode, functions are only hoisted within a scope but not across block scopes
  9044. variable = this.scope.addDeclaration(this, this.context, init, false);
  9045. break;
  9046. }
  9047. case 'let':
  9048. case 'const':
  9049. case 'class': {
  9050. variable = this.scope.addDeclaration(this, this.context, init, false);
  9051. break;
  9052. }
  9053. case 'parameter': {
  9054. variable = this.scope.addParameterDeclaration(this);
  9055. break;
  9056. }
  9057. /* istanbul ignore next */
  9058. default: {
  9059. /* istanbul ignore next */
  9060. throw new Error(`Internal Error: Unexpected identifier kind ${kind}.`);
  9061. }
  9062. }
  9063. variable.kind = kind;
  9064. return [(this.variable = variable)];
  9065. }
  9066. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  9067. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  9068. }
  9069. deoptimizePath(path) {
  9070. if (path.length === 0 && !this.scope.contains(this.name)) {
  9071. this.disallowImportReassignment();
  9072. }
  9073. // We keep conditional chaining because an unknown Node could have an
  9074. // Identifier as property that might be deoptimized by default
  9075. this.variable?.deoptimizePath(path);
  9076. }
  9077. getLiteralValueAtPath(path, recursionTracker, origin) {
  9078. return this.getVariableRespectingTDZ().getLiteralValueAtPath(path, recursionTracker, origin);
  9079. }
  9080. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  9081. const [expression, isPure] = this.getVariableRespectingTDZ().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  9082. return [expression, isPure || this.isPureFunction(path)];
  9083. }
  9084. hasEffects(context) {
  9085. if (!this.deoptimized)
  9086. this.applyDeoptimizations();
  9087. if (this.isPossibleTDZ() && this.variable.kind !== 'var') {
  9088. return true;
  9089. }
  9090. return (this.context.options.treeshake.unknownGlobalSideEffects &&
  9091. this.variable instanceof GlobalVariable &&
  9092. !this.isPureFunction(EMPTY_PATH) &&
  9093. this.variable.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context));
  9094. }
  9095. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9096. switch (interaction.type) {
  9097. case INTERACTION_ACCESSED: {
  9098. return (this.variable !== null &&
  9099. !this.isPureFunction(path) &&
  9100. this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context));
  9101. }
  9102. case INTERACTION_ASSIGNED: {
  9103. return (path.length > 0 ? this.getVariableRespectingTDZ() : this.variable).hasEffectsOnInteractionAtPath(path, interaction, context);
  9104. }
  9105. case INTERACTION_CALLED: {
  9106. return (!this.isPureFunction(path) &&
  9107. this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context));
  9108. }
  9109. }
  9110. }
  9111. include() {
  9112. if (!this.deoptimized)
  9113. this.applyDeoptimizations();
  9114. if (!this.included) {
  9115. this.included = true;
  9116. if (this.variable !== null) {
  9117. this.context.includeVariableInModule(this.variable);
  9118. }
  9119. }
  9120. }
  9121. includeCallArguments(context, parameters) {
  9122. this.variable.includeCallArguments(context, parameters);
  9123. }
  9124. isPossibleTDZ() {
  9125. // return cached value to avoid issues with the next tree-shaking pass
  9126. if (this.isTDZAccess !== null)
  9127. return this.isTDZAccess;
  9128. if (!(this.variable instanceof LocalVariable &&
  9129. this.variable.kind &&
  9130. this.variable.kind in tdzVariableKinds &&
  9131. // we ignore possible TDZs due to circular module dependencies as
  9132. // otherwise we get many false positives
  9133. this.variable.module === this.context.module)) {
  9134. return (this.isTDZAccess = false);
  9135. }
  9136. let decl_id;
  9137. if (this.variable.declarations &&
  9138. this.variable.declarations.length === 1 &&
  9139. (decl_id = this.variable.declarations[0]) &&
  9140. this.start < decl_id.start &&
  9141. closestParentFunctionOrProgram(this) === closestParentFunctionOrProgram(decl_id)) {
  9142. // a variable accessed before its declaration
  9143. // in the same function or at top level of module
  9144. return (this.isTDZAccess = true);
  9145. }
  9146. if (!this.variable.initReached) {
  9147. // Either a const/let TDZ violation or
  9148. // var use before declaration was encountered.
  9149. return (this.isTDZAccess = true);
  9150. }
  9151. return (this.isTDZAccess = false);
  9152. }
  9153. markDeclarationReached() {
  9154. this.variable.initReached = true;
  9155. }
  9156. render(code, { snippets: { getPropertyAccess }, useOriginalName }, { renderedParentType, isCalleeOfRenderedParent, isShorthandProperty } = BLANK) {
  9157. if (this.variable) {
  9158. const name = this.variable.getName(getPropertyAccess, useOriginalName);
  9159. if (name !== this.name) {
  9160. code.overwrite(this.start, this.end, name, {
  9161. contentOnly: true,
  9162. storeName: true
  9163. });
  9164. if (isShorthandProperty) {
  9165. code.prependRight(this.start, `${this.name}: `);
  9166. }
  9167. }
  9168. // In strict mode, any variable named "eval" must be the actual "eval" function
  9169. if (name === 'eval' &&
  9170. renderedParentType === CallExpression$1 &&
  9171. isCalleeOfRenderedParent) {
  9172. code.appendRight(this.start, '0, ');
  9173. }
  9174. }
  9175. }
  9176. applyDeoptimizations() {
  9177. this.deoptimized = true;
  9178. if (this.variable instanceof LocalVariable) {
  9179. this.variable.consolidateInitializers();
  9180. this.context.requestTreeshakingPass();
  9181. }
  9182. }
  9183. disallowImportReassignment() {
  9184. return this.context.error(logIllegalImportReassignment(this.name, this.context.module.id), this.start);
  9185. }
  9186. getVariableRespectingTDZ() {
  9187. if (this.isPossibleTDZ()) {
  9188. return UNKNOWN_EXPRESSION;
  9189. }
  9190. return this.variable;
  9191. }
  9192. isPureFunction(path) {
  9193. let currentPureFunction = this.context.manualPureFunctions[this.name];
  9194. for (const segment of path) {
  9195. if (currentPureFunction) {
  9196. if (currentPureFunction[PureFunctionKey]) {
  9197. return true;
  9198. }
  9199. currentPureFunction = currentPureFunction[segment];
  9200. }
  9201. else {
  9202. return false;
  9203. }
  9204. }
  9205. return currentPureFunction?.[PureFunctionKey];
  9206. }
  9207. }
  9208. function closestParentFunctionOrProgram(node) {
  9209. while (node && !/^Program|Function/.test(node.type)) {
  9210. node = node.parent;
  9211. }
  9212. // one of: ArrowFunctionExpression, FunctionDeclaration, FunctionExpression or Program
  9213. return node;
  9214. }
  9215. function treeshakeNode(node, code, start, end) {
  9216. code.remove(start, end);
  9217. if (node.annotations) {
  9218. for (const annotation of node.annotations) {
  9219. if (annotation.start < start) {
  9220. code.remove(annotation.start, annotation.end);
  9221. }
  9222. else {
  9223. return;
  9224. }
  9225. }
  9226. }
  9227. }
  9228. function removeAnnotations(node, code) {
  9229. if (!node.annotations && node.parent.type === ExpressionStatement$1) {
  9230. node = node.parent;
  9231. }
  9232. if (node.annotations) {
  9233. for (const annotation of node.annotations) {
  9234. code.remove(annotation.start, annotation.end);
  9235. }
  9236. }
  9237. }
  9238. const NO_SEMICOLON = { isNoStatement: true };
  9239. // This assumes there are only white-space and comments between start and the string we are looking for
  9240. function findFirstOccurrenceOutsideComment(code, searchString, start = 0) {
  9241. let searchPos, charCodeAfterSlash;
  9242. searchPos = code.indexOf(searchString, start);
  9243. while (true) {
  9244. start = code.indexOf('/', start);
  9245. if (start === -1 || start >= searchPos)
  9246. return searchPos;
  9247. charCodeAfterSlash = code.charCodeAt(++start);
  9248. ++start;
  9249. // With our assumption, '/' always starts a comment. Determine comment type:
  9250. start =
  9251. charCodeAfterSlash === 47 /*"/"*/
  9252. ? code.indexOf('\n', start) + 1
  9253. : code.indexOf('*/', start) + 2;
  9254. if (start > searchPos) {
  9255. searchPos = code.indexOf(searchString, start);
  9256. }
  9257. }
  9258. }
  9259. const NON_WHITESPACE = /\S/g;
  9260. function findNonWhiteSpace(code, index) {
  9261. NON_WHITESPACE.lastIndex = index;
  9262. const result = NON_WHITESPACE.exec(code);
  9263. return result.index;
  9264. }
  9265. // This assumes "code" only contains white-space and comments
  9266. // Returns position of line-comment if applicable
  9267. function findFirstLineBreakOutsideComment(code) {
  9268. let lineBreakPos, charCodeAfterSlash, start = 0;
  9269. lineBreakPos = code.indexOf('\n', start);
  9270. while (true) {
  9271. start = code.indexOf('/', start);
  9272. if (start === -1 || start > lineBreakPos)
  9273. return [lineBreakPos, lineBreakPos + 1];
  9274. // With our assumption, '/' always starts a comment. Determine comment type:
  9275. charCodeAfterSlash = code.charCodeAt(start + 1);
  9276. if (charCodeAfterSlash === 47 /*"/"*/)
  9277. return [start, lineBreakPos + 1];
  9278. start = code.indexOf('*/', start + 3) + 2;
  9279. if (start > lineBreakPos) {
  9280. lineBreakPos = code.indexOf('\n', start);
  9281. }
  9282. }
  9283. }
  9284. function renderStatementList(statements, code, start, end, options) {
  9285. let currentNode, currentNodeStart, currentNodeNeedsBoundaries, nextNodeStart;
  9286. let nextNode = statements[0];
  9287. let nextNodeNeedsBoundaries = !nextNode.included || nextNode.needsBoundaries;
  9288. if (nextNodeNeedsBoundaries) {
  9289. nextNodeStart =
  9290. start + findFirstLineBreakOutsideComment(code.original.slice(start, nextNode.start))[1];
  9291. }
  9292. for (let nextIndex = 1; nextIndex <= statements.length; nextIndex++) {
  9293. currentNode = nextNode;
  9294. currentNodeStart = nextNodeStart;
  9295. currentNodeNeedsBoundaries = nextNodeNeedsBoundaries;
  9296. nextNode = statements[nextIndex];
  9297. nextNodeNeedsBoundaries =
  9298. nextNode === undefined ? false : !nextNode.included || nextNode.needsBoundaries;
  9299. if (currentNodeNeedsBoundaries || nextNodeNeedsBoundaries) {
  9300. nextNodeStart =
  9301. currentNode.end +
  9302. findFirstLineBreakOutsideComment(code.original.slice(currentNode.end, nextNode === undefined ? end : nextNode.start))[1];
  9303. if (currentNode.included) {
  9304. currentNodeNeedsBoundaries
  9305. ? currentNode.render(code, options, {
  9306. end: nextNodeStart,
  9307. start: currentNodeStart
  9308. })
  9309. : currentNode.render(code, options);
  9310. }
  9311. else {
  9312. treeshakeNode(currentNode, code, currentNodeStart, nextNodeStart);
  9313. }
  9314. }
  9315. else {
  9316. currentNode.render(code, options);
  9317. }
  9318. }
  9319. }
  9320. // This assumes that the first character is not part of the first node
  9321. function getCommaSeparatedNodesWithBoundaries(nodes, code, start, end) {
  9322. const splitUpNodes = [];
  9323. let node, nextNodeStart, contentEnd, char;
  9324. let separator = start - 1;
  9325. for (const nextNode of nodes) {
  9326. if (node !== undefined) {
  9327. separator =
  9328. node.end +
  9329. findFirstOccurrenceOutsideComment(code.original.slice(node.end, nextNode.start), ',');
  9330. }
  9331. nextNodeStart = contentEnd =
  9332. separator +
  9333. 1 +
  9334. findFirstLineBreakOutsideComment(code.original.slice(separator + 1, nextNode.start))[1];
  9335. while (((char = code.original.charCodeAt(nextNodeStart)),
  9336. char === 32 /*" "*/ || char === 9 /*"\t"*/ || char === 10 /*"\n"*/ || char === 13) /*"\r"*/)
  9337. nextNodeStart++;
  9338. if (node !== undefined) {
  9339. splitUpNodes.push({
  9340. contentEnd,
  9341. end: nextNodeStart,
  9342. node,
  9343. separator,
  9344. start
  9345. });
  9346. }
  9347. node = nextNode;
  9348. start = nextNodeStart;
  9349. }
  9350. splitUpNodes.push({
  9351. contentEnd: end,
  9352. end,
  9353. node: node,
  9354. separator: null,
  9355. start
  9356. });
  9357. return splitUpNodes;
  9358. }
  9359. // This assumes there are only white-space and comments between start and end
  9360. function removeLineBreaks(code, start, end) {
  9361. while (true) {
  9362. const [removeStart, removeEnd] = findFirstLineBreakOutsideComment(code.original.slice(start, end));
  9363. if (removeStart === -1) {
  9364. break;
  9365. }
  9366. code.remove(start + removeStart, (start += removeEnd));
  9367. }
  9368. }
  9369. class BlockScope extends ChildScope {
  9370. addDeclaration(identifier, context, init, isHoisted) {
  9371. if (isHoisted) {
  9372. const variable = this.parent.addDeclaration(identifier, context, init, isHoisted);
  9373. // Necessary to make sure the init is deoptimized for conditional declarations.
  9374. // We cannot call deoptimizePath here.
  9375. variable.markInitializersForDeoptimization();
  9376. return variable;
  9377. }
  9378. else {
  9379. return super.addDeclaration(identifier, context, init, false);
  9380. }
  9381. }
  9382. }
  9383. class ExpressionStatement extends NodeBase {
  9384. initialise() {
  9385. if (this.directive &&
  9386. this.directive !== 'use strict' &&
  9387. this.parent.type === Program$1) {
  9388. this.context.log(LOGLEVEL_WARN,
  9389. // This is necessary, because either way (deleting or not) can lead to errors.
  9390. logModuleLevelDirective(this.directive, this.context.module.id), this.start);
  9391. }
  9392. }
  9393. render(code, options) {
  9394. super.render(code, options);
  9395. if (this.included)
  9396. this.insertSemicolon(code);
  9397. }
  9398. shouldBeIncluded(context) {
  9399. if (this.directive && this.directive !== 'use strict')
  9400. return this.parent.type !== Program$1;
  9401. return super.shouldBeIncluded(context);
  9402. }
  9403. applyDeoptimizations() { }
  9404. }
  9405. class BlockStatement extends NodeBase {
  9406. constructor() {
  9407. super(...arguments);
  9408. this.directlyIncluded = false;
  9409. }
  9410. addImplicitReturnExpressionToScope() {
  9411. const lastStatement = this.body[this.body.length - 1];
  9412. if (!lastStatement || lastStatement.type !== ReturnStatement$1) {
  9413. this.scope.addReturnExpression(UNKNOWN_EXPRESSION);
  9414. }
  9415. }
  9416. createScope(parentScope) {
  9417. this.scope = this.parent.preventChildBlockScope
  9418. ? parentScope
  9419. : new BlockScope(parentScope);
  9420. }
  9421. hasEffects(context) {
  9422. if (this.deoptimizeBody)
  9423. return true;
  9424. for (const node of this.body) {
  9425. if (context.brokenFlow)
  9426. break;
  9427. if (node.hasEffects(context))
  9428. return true;
  9429. }
  9430. return false;
  9431. }
  9432. include(context, includeChildrenRecursively) {
  9433. if (!(this.deoptimizeBody && this.directlyIncluded)) {
  9434. this.included = true;
  9435. this.directlyIncluded = true;
  9436. if (this.deoptimizeBody)
  9437. includeChildrenRecursively = true;
  9438. for (const node of this.body) {
  9439. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  9440. node.include(context, includeChildrenRecursively);
  9441. }
  9442. }
  9443. }
  9444. initialise() {
  9445. const firstBodyStatement = this.body[0];
  9446. this.deoptimizeBody =
  9447. firstBodyStatement instanceof ExpressionStatement &&
  9448. firstBodyStatement.directive === 'use asm';
  9449. }
  9450. render(code, options) {
  9451. if (this.body.length > 0) {
  9452. renderStatementList(this.body, code, this.start + 1, this.end - 1, options);
  9453. }
  9454. else {
  9455. super.render(code, options);
  9456. }
  9457. }
  9458. }
  9459. class RestElement extends NodeBase {
  9460. constructor() {
  9461. super(...arguments);
  9462. this.declarationInit = null;
  9463. }
  9464. addExportedVariables(variables, exportNamesByVariable) {
  9465. this.argument.addExportedVariables(variables, exportNamesByVariable);
  9466. }
  9467. declare(kind, init) {
  9468. this.declarationInit = init;
  9469. return this.argument.declare(kind, UNKNOWN_EXPRESSION);
  9470. }
  9471. deoptimizePath(path) {
  9472. path.length === 0 && this.argument.deoptimizePath(EMPTY_PATH);
  9473. }
  9474. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9475. return (path.length > 0 ||
  9476. this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context));
  9477. }
  9478. markDeclarationReached() {
  9479. this.argument.markDeclarationReached();
  9480. }
  9481. applyDeoptimizations() {
  9482. this.deoptimized = true;
  9483. if (this.declarationInit !== null) {
  9484. this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
  9485. this.context.requestTreeshakingPass();
  9486. }
  9487. }
  9488. }
  9489. class FunctionBase extends NodeBase {
  9490. constructor() {
  9491. super(...arguments);
  9492. this.objectEntity = null;
  9493. this.deoptimizedReturn = false;
  9494. }
  9495. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  9496. if (interaction.type === INTERACTION_CALLED) {
  9497. const { parameters } = this.scope;
  9498. const { args } = interaction;
  9499. let hasRest = false;
  9500. for (let position = 0; position < args.length - 1; position++) {
  9501. const parameter = this.params[position];
  9502. // Only the "this" argument arg[0] can be null
  9503. const argument = args[position + 1];
  9504. if (hasRest || parameter instanceof RestElement) {
  9505. hasRest = true;
  9506. argument.deoptimizePath(UNKNOWN_PATH);
  9507. }
  9508. else if (parameter instanceof Identifier) {
  9509. parameters[position][0].addEntityToBeDeoptimized(argument);
  9510. this.addArgumentToBeDeoptimized(argument);
  9511. }
  9512. else if (parameter) {
  9513. argument.deoptimizePath(UNKNOWN_PATH);
  9514. }
  9515. else {
  9516. this.addArgumentToBeDeoptimized(argument);
  9517. }
  9518. }
  9519. }
  9520. else {
  9521. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  9522. }
  9523. }
  9524. deoptimizePath(path) {
  9525. this.getObjectEntity().deoptimizePath(path);
  9526. if (path.length === 1 && path[0] === UnknownKey) {
  9527. // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
  9528. // which means the return expression and parameters need to be reassigned
  9529. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  9530. for (const parameterList of this.scope.parameters) {
  9531. for (const parameter of parameterList) {
  9532. parameter.deoptimizePath(UNKNOWN_PATH);
  9533. }
  9534. }
  9535. }
  9536. }
  9537. getLiteralValueAtPath(path, recursionTracker, origin) {
  9538. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  9539. }
  9540. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  9541. if (path.length > 0) {
  9542. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  9543. }
  9544. if (this.async) {
  9545. if (!this.deoptimizedReturn) {
  9546. this.deoptimizedReturn = true;
  9547. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  9548. this.context.requestTreeshakingPass();
  9549. }
  9550. return UNKNOWN_RETURN_EXPRESSION;
  9551. }
  9552. return [this.scope.getReturnExpression(), false];
  9553. }
  9554. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9555. if (path.length > 0 || interaction.type !== INTERACTION_CALLED) {
  9556. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  9557. }
  9558. if (this.annotationNoSideEffects) {
  9559. return false;
  9560. }
  9561. if (this.async) {
  9562. const { propertyReadSideEffects } = this.context.options
  9563. .treeshake;
  9564. const returnExpression = this.scope.getReturnExpression();
  9565. if (returnExpression.hasEffectsOnInteractionAtPath(['then'], NODE_INTERACTION_UNKNOWN_CALL, context) ||
  9566. (propertyReadSideEffects &&
  9567. (propertyReadSideEffects === 'always' ||
  9568. returnExpression.hasEffectsOnInteractionAtPath(['then'], NODE_INTERACTION_UNKNOWN_ACCESS, context)))) {
  9569. return true;
  9570. }
  9571. }
  9572. for (const parameter of this.params) {
  9573. if (parameter.hasEffects(context))
  9574. return true;
  9575. }
  9576. return false;
  9577. }
  9578. include(context, includeChildrenRecursively) {
  9579. if (!this.deoptimized)
  9580. this.applyDeoptimizations();
  9581. this.included = true;
  9582. const { brokenFlow } = context;
  9583. context.brokenFlow = false;
  9584. this.body.include(context, includeChildrenRecursively);
  9585. context.brokenFlow = brokenFlow;
  9586. }
  9587. includeCallArguments(context, parameters) {
  9588. this.scope.includeCallArguments(context, parameters);
  9589. }
  9590. initialise() {
  9591. this.scope.addParameterVariables(this.params.map(parameter => parameter.declare('parameter', UNKNOWN_EXPRESSION)), this.params[this.params.length - 1] instanceof RestElement);
  9592. if (this.body instanceof BlockStatement) {
  9593. this.body.addImplicitReturnExpressionToScope();
  9594. }
  9595. else {
  9596. this.scope.addReturnExpression(this.body);
  9597. }
  9598. }
  9599. parseNode(esTreeNode) {
  9600. if (esTreeNode.body.type === BlockStatement$1) {
  9601. this.body = new BlockStatement(esTreeNode.body, this, this.scope.hoistedBodyVarScope);
  9602. }
  9603. super.parseNode(esTreeNode);
  9604. }
  9605. addArgumentToBeDeoptimized(_argument) { }
  9606. applyDeoptimizations() { }
  9607. }
  9608. FunctionBase.prototype.preventChildBlockScope = true;
  9609. class ArrowFunctionExpression extends FunctionBase {
  9610. constructor() {
  9611. super(...arguments);
  9612. this.objectEntity = null;
  9613. }
  9614. createScope(parentScope) {
  9615. this.scope = new ReturnValueScope(parentScope, this.context);
  9616. }
  9617. hasEffects() {
  9618. if (!this.deoptimized)
  9619. this.applyDeoptimizations();
  9620. return false;
  9621. }
  9622. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9623. if (super.hasEffectsOnInteractionAtPath(path, interaction, context)) {
  9624. return true;
  9625. }
  9626. if (this.annotationNoSideEffects) {
  9627. return false;
  9628. }
  9629. if (interaction.type === INTERACTION_CALLED) {
  9630. const { ignore, brokenFlow } = context;
  9631. context.ignore = {
  9632. breaks: false,
  9633. continues: false,
  9634. labels: new Set(),
  9635. returnYield: true,
  9636. this: false
  9637. };
  9638. if (this.body.hasEffects(context))
  9639. return true;
  9640. context.ignore = ignore;
  9641. context.brokenFlow = brokenFlow;
  9642. }
  9643. return false;
  9644. }
  9645. include(context, includeChildrenRecursively) {
  9646. super.include(context, includeChildrenRecursively);
  9647. for (const parameter of this.params) {
  9648. if (!(parameter instanceof Identifier)) {
  9649. parameter.include(context, includeChildrenRecursively);
  9650. }
  9651. }
  9652. }
  9653. getObjectEntity() {
  9654. if (this.objectEntity !== null) {
  9655. return this.objectEntity;
  9656. }
  9657. return (this.objectEntity = new ObjectEntity([], OBJECT_PROTOTYPE));
  9658. }
  9659. }
  9660. function getSystemExportStatement(exportedVariables, { exportNamesByVariable, snippets: { _, getObject, getPropertyAccess } }, modifier = '') {
  9661. if (exportedVariables.length === 1 &&
  9662. exportNamesByVariable.get(exportedVariables[0]).length === 1) {
  9663. const variable = exportedVariables[0];
  9664. return `exports('${exportNamesByVariable.get(variable)}',${_}${variable.getName(getPropertyAccess)}${modifier})`;
  9665. }
  9666. else {
  9667. const fields = [];
  9668. for (const variable of exportedVariables) {
  9669. for (const exportName of exportNamesByVariable.get(variable)) {
  9670. fields.push([exportName, variable.getName(getPropertyAccess) + modifier]);
  9671. }
  9672. }
  9673. return `exports(${getObject(fields, { lineBreakIndent: null })})`;
  9674. }
  9675. }
  9676. function renderSystemExportExpression(exportedVariable, expressionStart, expressionEnd, code, { exportNamesByVariable, snippets: { _ } }) {
  9677. code.prependRight(expressionStart, `exports('${exportNamesByVariable.get(exportedVariable)}',${_}`);
  9678. code.appendLeft(expressionEnd, ')');
  9679. }
  9680. function renderSystemExportFunction(exportedVariables, expressionStart, expressionEnd, needsParens, code, options) {
  9681. const { _, getDirectReturnIifeLeft } = options.snippets;
  9682. code.prependRight(expressionStart, getDirectReturnIifeLeft(['v'], `${getSystemExportStatement(exportedVariables, options)},${_}v`, { needsArrowReturnParens: true, needsWrappedFunction: needsParens }));
  9683. code.appendLeft(expressionEnd, ')');
  9684. }
  9685. function renderSystemExportSequenceAfterExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options) {
  9686. const { _, getPropertyAccess } = options.snippets;
  9687. code.appendLeft(expressionEnd, `,${_}${getSystemExportStatement([exportedVariable], options)},${_}${exportedVariable.getName(getPropertyAccess)}`);
  9688. if (needsParens) {
  9689. code.prependRight(expressionStart, '(');
  9690. code.appendLeft(expressionEnd, ')');
  9691. }
  9692. }
  9693. function renderSystemExportSequenceBeforeExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options, modifier) {
  9694. const { _ } = options.snippets;
  9695. code.prependRight(expressionStart, `${getSystemExportStatement([exportedVariable], options, modifier)},${_}`);
  9696. if (needsParens) {
  9697. code.prependRight(expressionStart, '(');
  9698. code.appendLeft(expressionEnd, ')');
  9699. }
  9700. }
  9701. class ObjectPattern extends NodeBase {
  9702. addExportedVariables(variables, exportNamesByVariable) {
  9703. for (const property of this.properties) {
  9704. if (property.type === Property$1) {
  9705. property.value.addExportedVariables(variables, exportNamesByVariable);
  9706. }
  9707. else {
  9708. property.argument.addExportedVariables(variables, exportNamesByVariable);
  9709. }
  9710. }
  9711. }
  9712. declare(kind, init) {
  9713. const variables = [];
  9714. for (const property of this.properties) {
  9715. variables.push(...property.declare(kind, init));
  9716. }
  9717. return variables;
  9718. }
  9719. deoptimizePath(path) {
  9720. if (path.length === 0) {
  9721. for (const property of this.properties) {
  9722. property.deoptimizePath(path);
  9723. }
  9724. }
  9725. }
  9726. hasEffectsOnInteractionAtPath(
  9727. // At the moment, this is only triggered for assignment left-hand sides,
  9728. // where the path is empty
  9729. _path, interaction, context) {
  9730. for (const property of this.properties) {
  9731. if (property.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context))
  9732. return true;
  9733. }
  9734. return false;
  9735. }
  9736. markDeclarationReached() {
  9737. for (const property of this.properties) {
  9738. property.markDeclarationReached();
  9739. }
  9740. }
  9741. }
  9742. class AssignmentExpression extends NodeBase {
  9743. hasEffects(context) {
  9744. const { deoptimized, left, operator, right } = this;
  9745. if (!deoptimized)
  9746. this.applyDeoptimizations();
  9747. // MemberExpressions do not access the property before assignments if the
  9748. // operator is '='.
  9749. return (right.hasEffects(context) || left.hasEffectsAsAssignmentTarget(context, operator !== '='));
  9750. }
  9751. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9752. return this.right.hasEffectsOnInteractionAtPath(path, interaction, context);
  9753. }
  9754. include(context, includeChildrenRecursively) {
  9755. const { deoptimized, left, right, operator } = this;
  9756. if (!deoptimized)
  9757. this.applyDeoptimizations();
  9758. this.included = true;
  9759. if (includeChildrenRecursively ||
  9760. operator !== '=' ||
  9761. left.included ||
  9762. left.hasEffectsAsAssignmentTarget(createHasEffectsContext(), false)) {
  9763. left.includeAsAssignmentTarget(context, includeChildrenRecursively, operator !== '=');
  9764. }
  9765. right.include(context, includeChildrenRecursively);
  9766. }
  9767. initialise() {
  9768. this.left.setAssignedValue(this.right);
  9769. }
  9770. render(code, options, { preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  9771. const { left, right, start, end, parent } = this;
  9772. if (left.included) {
  9773. left.render(code, options);
  9774. right.render(code, options);
  9775. }
  9776. else {
  9777. const inclusionStart = findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, '=', left.end) + 1);
  9778. code.remove(start, inclusionStart);
  9779. if (preventASI) {
  9780. removeLineBreaks(code, inclusionStart, right.start);
  9781. }
  9782. right.render(code, options, {
  9783. renderedParentType: renderedParentType || parent.type,
  9784. renderedSurroundingElement: renderedSurroundingElement || parent.type
  9785. });
  9786. }
  9787. if (options.format === 'system') {
  9788. if (left instanceof Identifier) {
  9789. const variable = left.variable;
  9790. const exportNames = options.exportNamesByVariable.get(variable);
  9791. if (exportNames) {
  9792. if (exportNames.length === 1) {
  9793. renderSystemExportExpression(variable, start, end, code, options);
  9794. }
  9795. else {
  9796. renderSystemExportSequenceAfterExpression(variable, start, end, parent.type !== ExpressionStatement$1, code, options);
  9797. }
  9798. return;
  9799. }
  9800. }
  9801. else {
  9802. const systemPatternExports = [];
  9803. left.addExportedVariables(systemPatternExports, options.exportNamesByVariable);
  9804. if (systemPatternExports.length > 0) {
  9805. renderSystemExportFunction(systemPatternExports, start, end, renderedSurroundingElement === ExpressionStatement$1, code, options);
  9806. return;
  9807. }
  9808. }
  9809. }
  9810. if (left.included &&
  9811. left instanceof ObjectPattern &&
  9812. (renderedSurroundingElement === ExpressionStatement$1 ||
  9813. renderedSurroundingElement === ArrowFunctionExpression$1)) {
  9814. code.appendRight(start, '(');
  9815. code.prependLeft(end, ')');
  9816. }
  9817. }
  9818. applyDeoptimizations() {
  9819. this.deoptimized = true;
  9820. this.left.deoptimizePath(EMPTY_PATH);
  9821. this.right.deoptimizePath(UNKNOWN_PATH);
  9822. this.context.requestTreeshakingPass();
  9823. }
  9824. }
  9825. class AssignmentPattern extends NodeBase {
  9826. addExportedVariables(variables, exportNamesByVariable) {
  9827. this.left.addExportedVariables(variables, exportNamesByVariable);
  9828. }
  9829. declare(kind, init) {
  9830. return this.left.declare(kind, init);
  9831. }
  9832. deoptimizePath(path) {
  9833. path.length === 0 && this.left.deoptimizePath(path);
  9834. }
  9835. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9836. return (path.length > 0 || this.left.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context));
  9837. }
  9838. markDeclarationReached() {
  9839. this.left.markDeclarationReached();
  9840. }
  9841. render(code, options, { isShorthandProperty } = BLANK) {
  9842. this.left.render(code, options, { isShorthandProperty });
  9843. this.right.render(code, options);
  9844. }
  9845. applyDeoptimizations() {
  9846. this.deoptimized = true;
  9847. this.left.deoptimizePath(EMPTY_PATH);
  9848. this.right.deoptimizePath(UNKNOWN_PATH);
  9849. this.context.requestTreeshakingPass();
  9850. }
  9851. }
  9852. class ArgumentsVariable extends LocalVariable {
  9853. constructor(context) {
  9854. super('arguments', null, UNKNOWN_EXPRESSION, context);
  9855. this.deoptimizedArguments = [];
  9856. }
  9857. addArgumentToBeDeoptimized(argument) {
  9858. if (this.included) {
  9859. argument.deoptimizePath(UNKNOWN_PATH);
  9860. }
  9861. else {
  9862. this.deoptimizedArguments.push(argument);
  9863. }
  9864. }
  9865. hasEffectsOnInteractionAtPath(path, { type }) {
  9866. return type !== INTERACTION_ACCESSED || path.length > 1;
  9867. }
  9868. include() {
  9869. super.include();
  9870. for (const argument of this.deoptimizedArguments) {
  9871. argument.deoptimizePath(UNKNOWN_PATH);
  9872. }
  9873. this.deoptimizedArguments.length = 0;
  9874. }
  9875. }
  9876. class ThisVariable extends ParameterVariable {
  9877. constructor(context) {
  9878. super('this', null, context);
  9879. }
  9880. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9881. return (context.replacedVariableInits.get(this) || UNKNOWN_EXPRESSION).hasEffectsOnInteractionAtPath(path, interaction, context);
  9882. }
  9883. }
  9884. class FunctionScope extends ReturnValueScope {
  9885. constructor(parent, context) {
  9886. super(parent, context);
  9887. this.variables.set('arguments', (this.argumentsVariable = new ArgumentsVariable(context)));
  9888. this.variables.set('this', (this.thisVariable = new ThisVariable(context)));
  9889. }
  9890. findLexicalBoundary() {
  9891. return this;
  9892. }
  9893. includeCallArguments(context, parameters) {
  9894. super.includeCallArguments(context, parameters);
  9895. if (this.argumentsVariable.included) {
  9896. for (const argument of parameters) {
  9897. if (!argument.included) {
  9898. argument.include(context, false);
  9899. }
  9900. }
  9901. }
  9902. }
  9903. }
  9904. class FunctionNode extends FunctionBase {
  9905. constructor() {
  9906. super(...arguments);
  9907. this.objectEntity = null;
  9908. }
  9909. createScope(parentScope) {
  9910. this.scope = new FunctionScope(parentScope, this.context);
  9911. this.constructedEntity = new ObjectEntity(Object.create(null), OBJECT_PROTOTYPE);
  9912. // This makes sure that all deoptimizations of "this" are applied to the
  9913. // constructed entity.
  9914. this.scope.thisVariable.addEntityToBeDeoptimized(this.constructedEntity);
  9915. }
  9916. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  9917. super.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  9918. if (interaction.type === INTERACTION_CALLED && path.length === 0 && interaction.args[0]) {
  9919. // args[0] is the "this" argument
  9920. this.scope.thisVariable.addEntityToBeDeoptimized(interaction.args[0]);
  9921. }
  9922. }
  9923. hasEffects(context) {
  9924. if (!this.deoptimized)
  9925. this.applyDeoptimizations();
  9926. if (this.annotationNoSideEffects) {
  9927. return false;
  9928. }
  9929. return !!this.id?.hasEffects(context);
  9930. }
  9931. hasEffectsOnInteractionAtPath(path, interaction, context) {
  9932. if (super.hasEffectsOnInteractionAtPath(path, interaction, context))
  9933. return true;
  9934. if (this.annotationNoSideEffects) {
  9935. return false;
  9936. }
  9937. if (interaction.type === INTERACTION_CALLED) {
  9938. const thisInit = context.replacedVariableInits.get(this.scope.thisVariable);
  9939. context.replacedVariableInits.set(this.scope.thisVariable, interaction.withNew ? this.constructedEntity : UNKNOWN_EXPRESSION);
  9940. const { brokenFlow, ignore, replacedVariableInits } = context;
  9941. context.ignore = {
  9942. breaks: false,
  9943. continues: false,
  9944. labels: new Set(),
  9945. returnYield: true,
  9946. this: interaction.withNew
  9947. };
  9948. if (this.body.hasEffects(context))
  9949. return true;
  9950. context.brokenFlow = brokenFlow;
  9951. if (thisInit) {
  9952. replacedVariableInits.set(this.scope.thisVariable, thisInit);
  9953. }
  9954. else {
  9955. replacedVariableInits.delete(this.scope.thisVariable);
  9956. }
  9957. context.ignore = ignore;
  9958. }
  9959. return false;
  9960. }
  9961. include(context, includeChildrenRecursively) {
  9962. super.include(context, includeChildrenRecursively);
  9963. this.id?.include();
  9964. const hasArguments = this.scope.argumentsVariable.included;
  9965. for (const parameter of this.params) {
  9966. if (!(parameter instanceof Identifier) || hasArguments) {
  9967. parameter.include(context, includeChildrenRecursively);
  9968. }
  9969. }
  9970. }
  9971. initialise() {
  9972. super.initialise();
  9973. this.id?.declare('function', this);
  9974. }
  9975. addArgumentToBeDeoptimized(argument) {
  9976. this.scope.argumentsVariable.addArgumentToBeDeoptimized(argument);
  9977. }
  9978. getObjectEntity() {
  9979. if (this.objectEntity !== null) {
  9980. return this.objectEntity;
  9981. }
  9982. return (this.objectEntity = new ObjectEntity([
  9983. {
  9984. key: 'prototype',
  9985. kind: 'init',
  9986. property: new ObjectEntity([], OBJECT_PROTOTYPE)
  9987. }
  9988. ], OBJECT_PROTOTYPE));
  9989. }
  9990. }
  9991. class AwaitExpression extends NodeBase {
  9992. hasEffects() {
  9993. if (!this.deoptimized)
  9994. this.applyDeoptimizations();
  9995. return true;
  9996. }
  9997. include(context, includeChildrenRecursively) {
  9998. if (!this.deoptimized)
  9999. this.applyDeoptimizations();
  10000. if (!this.included) {
  10001. this.included = true;
  10002. checkTopLevelAwait: if (!this.context.usesTopLevelAwait) {
  10003. let parent = this.parent;
  10004. do {
  10005. if (parent instanceof FunctionNode || parent instanceof ArrowFunctionExpression)
  10006. break checkTopLevelAwait;
  10007. } while ((parent = parent.parent));
  10008. this.context.usesTopLevelAwait = true;
  10009. }
  10010. }
  10011. this.argument.include(context, includeChildrenRecursively);
  10012. }
  10013. }
  10014. const binaryOperators = {
  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. // At the moment, "**" will be transpiled to Math.pow
  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. '>': (left, right) => left > right,
  10031. '>=': (left, right) => left >= right,
  10032. '>>': (left, right) => left >> right,
  10033. '>>>': (left, right) => left >>> right,
  10034. '^': (left, right) => left ^ right,
  10035. '|': (left, right) => left | right
  10036. // We use the fallback for cases where we return something unknown
  10037. // in: () => UnknownValue,
  10038. // instanceof: () => UnknownValue,
  10039. };
  10040. class BinaryExpression extends NodeBase {
  10041. deoptimizeCache() { }
  10042. getLiteralValueAtPath(path, recursionTracker, origin) {
  10043. if (path.length > 0)
  10044. return UnknownValue;
  10045. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  10046. if (typeof leftValue === 'symbol')
  10047. return UnknownValue;
  10048. const rightValue = this.right.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  10049. if (typeof rightValue === 'symbol')
  10050. return UnknownValue;
  10051. const operatorFunction = binaryOperators[this.operator];
  10052. if (!operatorFunction)
  10053. return UnknownValue;
  10054. return operatorFunction(leftValue, rightValue);
  10055. }
  10056. hasEffects(context) {
  10057. // support some implicit type coercion runtime errors
  10058. if (this.operator === '+' &&
  10059. this.parent instanceof ExpressionStatement &&
  10060. this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) === '') {
  10061. return true;
  10062. }
  10063. return super.hasEffects(context);
  10064. }
  10065. hasEffectsOnInteractionAtPath(path, { type }) {
  10066. return type !== INTERACTION_ACCESSED || path.length > 1;
  10067. }
  10068. render(code, options, { renderedSurroundingElement } = BLANK) {
  10069. this.left.render(code, options, { renderedSurroundingElement });
  10070. this.right.render(code, options);
  10071. }
  10072. }
  10073. class BreakStatement extends NodeBase {
  10074. hasEffects(context) {
  10075. if (this.label) {
  10076. if (!context.ignore.labels.has(this.label.name))
  10077. return true;
  10078. context.includedLabels.add(this.label.name);
  10079. }
  10080. else {
  10081. if (!context.ignore.breaks)
  10082. return true;
  10083. context.hasBreak = true;
  10084. }
  10085. context.brokenFlow = true;
  10086. return false;
  10087. }
  10088. include(context) {
  10089. this.included = true;
  10090. if (this.label) {
  10091. this.label.include();
  10092. context.includedLabels.add(this.label.name);
  10093. }
  10094. else {
  10095. context.hasBreak = true;
  10096. }
  10097. context.brokenFlow = true;
  10098. }
  10099. }
  10100. function renderCallArguments(code, options, node) {
  10101. if (node.arguments.length > 0) {
  10102. if (node.arguments[node.arguments.length - 1].included) {
  10103. for (const argument of node.arguments) {
  10104. argument.render(code, options);
  10105. }
  10106. }
  10107. else {
  10108. let lastIncludedIndex = node.arguments.length - 2;
  10109. while (lastIncludedIndex >= 0 && !node.arguments[lastIncludedIndex].included) {
  10110. lastIncludedIndex--;
  10111. }
  10112. if (lastIncludedIndex >= 0) {
  10113. for (let index = 0; index <= lastIncludedIndex; index++) {
  10114. node.arguments[index].render(code, options);
  10115. }
  10116. code.remove(findFirstOccurrenceOutsideComment(code.original, ',', node.arguments[lastIncludedIndex].end), node.end - 1);
  10117. }
  10118. else {
  10119. code.remove(findFirstOccurrenceOutsideComment(code.original, '(', node.callee.end) + 1, node.end - 1);
  10120. }
  10121. }
  10122. }
  10123. }
  10124. class Literal extends NodeBase {
  10125. deoptimizeArgumentsOnInteractionAtPath() { }
  10126. getLiteralValueAtPath(path) {
  10127. if (path.length > 0 ||
  10128. // unknown literals can also be null but do not start with an "n"
  10129. (this.value === null && this.context.code.charCodeAt(this.start) !== 110) ||
  10130. typeof this.value === 'bigint' ||
  10131. // to support shims for regular expressions
  10132. this.context.code.charCodeAt(this.start) === 47) {
  10133. return UnknownValue;
  10134. }
  10135. return this.value;
  10136. }
  10137. getReturnExpressionWhenCalledAtPath(path) {
  10138. if (path.length !== 1)
  10139. return UNKNOWN_RETURN_EXPRESSION;
  10140. return getMemberReturnExpressionWhenCalled(this.members, path[0]);
  10141. }
  10142. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10143. switch (interaction.type) {
  10144. case INTERACTION_ACCESSED: {
  10145. return path.length > (this.value === null ? 0 : 1);
  10146. }
  10147. case INTERACTION_ASSIGNED: {
  10148. return true;
  10149. }
  10150. case INTERACTION_CALLED: {
  10151. if (this.included &&
  10152. this.value instanceof RegExp &&
  10153. (this.value.global || this.value.sticky)) {
  10154. return true;
  10155. }
  10156. return (path.length !== 1 ||
  10157. hasMemberEffectWhenCalled(this.members, path[0], interaction, context));
  10158. }
  10159. }
  10160. }
  10161. initialise() {
  10162. this.members = getLiteralMembersForValue(this.value);
  10163. }
  10164. parseNode(esTreeNode) {
  10165. this.value = esTreeNode.value;
  10166. this.regex = esTreeNode.regex;
  10167. super.parseNode(esTreeNode);
  10168. }
  10169. render(code) {
  10170. if (typeof this.value === 'string') {
  10171. code.indentExclusionRanges.push([this.start + 1, this.end - 1]);
  10172. }
  10173. }
  10174. }
  10175. // To avoid infinite recursions
  10176. const MAX_PATH_DEPTH = 7;
  10177. function getResolvablePropertyKey(memberExpression) {
  10178. return memberExpression.computed
  10179. ? getResolvableComputedPropertyKey(memberExpression.property)
  10180. : memberExpression.property.name;
  10181. }
  10182. function getResolvableComputedPropertyKey(propertyKey) {
  10183. if (propertyKey instanceof Literal) {
  10184. return String(propertyKey.value);
  10185. }
  10186. return null;
  10187. }
  10188. function getPathIfNotComputed(memberExpression) {
  10189. const nextPathKey = memberExpression.propertyKey;
  10190. const object = memberExpression.object;
  10191. if (typeof nextPathKey === 'string') {
  10192. if (object instanceof Identifier) {
  10193. return [
  10194. { key: object.name, pos: object.start },
  10195. { key: nextPathKey, pos: memberExpression.property.start }
  10196. ];
  10197. }
  10198. if (object instanceof MemberExpression) {
  10199. const parentPath = getPathIfNotComputed(object);
  10200. return (parentPath && [...parentPath, { key: nextPathKey, pos: memberExpression.property.start }]);
  10201. }
  10202. }
  10203. return null;
  10204. }
  10205. function getStringFromPath(path) {
  10206. let pathString = path[0].key;
  10207. for (let index = 1; index < path.length; index++) {
  10208. pathString += '.' + path[index].key;
  10209. }
  10210. return pathString;
  10211. }
  10212. class MemberExpression extends NodeBase {
  10213. constructor() {
  10214. super(...arguments);
  10215. this.variable = null;
  10216. this.assignmentDeoptimized = false;
  10217. this.bound = false;
  10218. this.expressionsToBeDeoptimized = [];
  10219. this.isUndefined = false;
  10220. }
  10221. bind() {
  10222. this.bound = true;
  10223. const path = getPathIfNotComputed(this);
  10224. const baseVariable = path && this.scope.findVariable(path[0].key);
  10225. if (baseVariable?.isNamespace) {
  10226. const resolvedVariable = resolveNamespaceVariables(baseVariable, path.slice(1), this.context);
  10227. if (!resolvedVariable) {
  10228. super.bind();
  10229. }
  10230. else if (resolvedVariable === 'undefined') {
  10231. this.isUndefined = true;
  10232. }
  10233. else {
  10234. this.variable = resolvedVariable;
  10235. this.scope.addNamespaceMemberAccess(getStringFromPath(path), resolvedVariable);
  10236. }
  10237. }
  10238. else {
  10239. super.bind();
  10240. }
  10241. }
  10242. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  10243. if (this.variable) {
  10244. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  10245. }
  10246. else if (!this.isUndefined) {
  10247. if (path.length < MAX_PATH_DEPTH) {
  10248. this.object.deoptimizeArgumentsOnInteractionAtPath(interaction, [this.getPropertyKey(), ...path], recursionTracker);
  10249. }
  10250. else {
  10251. deoptimizeInteraction(interaction);
  10252. }
  10253. }
  10254. }
  10255. deoptimizeCache() {
  10256. const { expressionsToBeDeoptimized, object } = this;
  10257. this.expressionsToBeDeoptimized = EMPTY_ARRAY;
  10258. this.propertyKey = UnknownKey;
  10259. object.deoptimizePath(UNKNOWN_PATH);
  10260. for (const expression of expressionsToBeDeoptimized) {
  10261. expression.deoptimizeCache();
  10262. }
  10263. }
  10264. deoptimizePath(path) {
  10265. if (path.length === 0)
  10266. this.disallowNamespaceReassignment();
  10267. if (this.variable) {
  10268. this.variable.deoptimizePath(path);
  10269. }
  10270. else if (!this.isUndefined && path.length < MAX_PATH_DEPTH) {
  10271. const propertyKey = this.getPropertyKey();
  10272. this.object.deoptimizePath([
  10273. propertyKey === UnknownKey ? UnknownNonAccessorKey : propertyKey,
  10274. ...path
  10275. ]);
  10276. }
  10277. }
  10278. getLiteralValueAtPath(path, recursionTracker, origin) {
  10279. if (this.variable) {
  10280. return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
  10281. }
  10282. if (this.isUndefined) {
  10283. return undefined;
  10284. }
  10285. if (this.propertyKey !== UnknownKey && path.length < MAX_PATH_DEPTH) {
  10286. this.expressionsToBeDeoptimized.push(origin);
  10287. return this.object.getLiteralValueAtPath([this.getPropertyKey(), ...path], recursionTracker, origin);
  10288. }
  10289. return UnknownValue;
  10290. }
  10291. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  10292. if (this.variable) {
  10293. return this.variable.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  10294. }
  10295. if (this.isUndefined) {
  10296. return [UNDEFINED_EXPRESSION, false];
  10297. }
  10298. if (this.propertyKey !== UnknownKey && path.length < MAX_PATH_DEPTH) {
  10299. this.expressionsToBeDeoptimized.push(origin);
  10300. return this.object.getReturnExpressionWhenCalledAtPath([this.getPropertyKey(), ...path], interaction, recursionTracker, origin);
  10301. }
  10302. return UNKNOWN_RETURN_EXPRESSION;
  10303. }
  10304. hasEffects(context) {
  10305. if (!this.deoptimized)
  10306. this.applyDeoptimizations();
  10307. return (this.property.hasEffects(context) ||
  10308. this.object.hasEffects(context) ||
  10309. this.hasAccessEffect(context));
  10310. }
  10311. hasEffectsAsAssignmentTarget(context, checkAccess) {
  10312. if (checkAccess && !this.deoptimized)
  10313. this.applyDeoptimizations();
  10314. if (!this.assignmentDeoptimized)
  10315. this.applyAssignmentDeoptimization();
  10316. return (this.property.hasEffects(context) ||
  10317. this.object.hasEffects(context) ||
  10318. (checkAccess && this.hasAccessEffect(context)) ||
  10319. this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
  10320. }
  10321. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10322. if (this.variable) {
  10323. return this.variable.hasEffectsOnInteractionAtPath(path, interaction, context);
  10324. }
  10325. if (this.isUndefined) {
  10326. return true;
  10327. }
  10328. if (path.length < MAX_PATH_DEPTH) {
  10329. return this.object.hasEffectsOnInteractionAtPath([this.getPropertyKey(), ...path], interaction, context);
  10330. }
  10331. return true;
  10332. }
  10333. include(context, includeChildrenRecursively) {
  10334. if (!this.deoptimized)
  10335. this.applyDeoptimizations();
  10336. this.includeProperties(context, includeChildrenRecursively);
  10337. }
  10338. includeAsAssignmentTarget(context, includeChildrenRecursively, deoptimizeAccess) {
  10339. if (!this.assignmentDeoptimized)
  10340. this.applyAssignmentDeoptimization();
  10341. if (deoptimizeAccess) {
  10342. this.include(context, includeChildrenRecursively);
  10343. }
  10344. else {
  10345. this.includeProperties(context, includeChildrenRecursively);
  10346. }
  10347. }
  10348. includeCallArguments(context, parameters) {
  10349. if (this.variable) {
  10350. this.variable.includeCallArguments(context, parameters);
  10351. }
  10352. else {
  10353. super.includeCallArguments(context, parameters);
  10354. }
  10355. }
  10356. initialise() {
  10357. this.propertyKey = getResolvablePropertyKey(this);
  10358. this.accessInteraction = { args: [this.object], type: INTERACTION_ACCESSED };
  10359. }
  10360. isSkippedAsOptional(origin) {
  10361. return (!this.variable &&
  10362. !this.isUndefined &&
  10363. (this.object.isSkippedAsOptional?.(origin) ||
  10364. (this.optional &&
  10365. this.object.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, origin) == null)));
  10366. }
  10367. render(code, options, { renderedParentType, isCalleeOfRenderedParent, renderedSurroundingElement } = BLANK) {
  10368. if (this.variable || this.isUndefined) {
  10369. const { snippets: { getPropertyAccess } } = options;
  10370. let replacement = this.variable ? this.variable.getName(getPropertyAccess) : 'undefined';
  10371. if (renderedParentType && isCalleeOfRenderedParent)
  10372. replacement = '0, ' + replacement;
  10373. code.overwrite(this.start, this.end, replacement, {
  10374. contentOnly: true,
  10375. storeName: true
  10376. });
  10377. }
  10378. else {
  10379. if (renderedParentType && isCalleeOfRenderedParent) {
  10380. code.appendRight(this.start, '0, ');
  10381. }
  10382. this.object.render(code, options, { renderedSurroundingElement });
  10383. this.property.render(code, options);
  10384. }
  10385. }
  10386. setAssignedValue(value) {
  10387. this.assignmentInteraction = {
  10388. args: [this.object, value],
  10389. type: INTERACTION_ASSIGNED
  10390. };
  10391. }
  10392. applyDeoptimizations() {
  10393. this.deoptimized = true;
  10394. const { propertyReadSideEffects } = this.context.options
  10395. .treeshake;
  10396. if (
  10397. // Namespaces are not bound and should not be deoptimized
  10398. this.bound &&
  10399. propertyReadSideEffects &&
  10400. !(this.variable || this.isUndefined)) {
  10401. const propertyKey = this.getPropertyKey();
  10402. this.object.deoptimizeArgumentsOnInteractionAtPath(this.accessInteraction, [propertyKey], SHARED_RECURSION_TRACKER);
  10403. this.context.requestTreeshakingPass();
  10404. }
  10405. }
  10406. applyAssignmentDeoptimization() {
  10407. this.assignmentDeoptimized = true;
  10408. const { propertyReadSideEffects } = this.context.options
  10409. .treeshake;
  10410. if (
  10411. // Namespaces are not bound and should not be deoptimized
  10412. this.bound &&
  10413. propertyReadSideEffects &&
  10414. !(this.variable || this.isUndefined)) {
  10415. this.object.deoptimizeArgumentsOnInteractionAtPath(this.assignmentInteraction, [this.getPropertyKey()], SHARED_RECURSION_TRACKER);
  10416. this.context.requestTreeshakingPass();
  10417. }
  10418. }
  10419. disallowNamespaceReassignment() {
  10420. if (this.object instanceof Identifier) {
  10421. const variable = this.scope.findVariable(this.object.name);
  10422. if (variable.isNamespace) {
  10423. if (this.variable) {
  10424. this.context.includeVariableInModule(this.variable);
  10425. }
  10426. this.context.log(LOGLEVEL_WARN, logIllegalImportReassignment(this.object.name, this.context.module.id), this.start);
  10427. }
  10428. }
  10429. }
  10430. getPropertyKey() {
  10431. if (this.propertyKey === null) {
  10432. this.propertyKey = UnknownKey;
  10433. const value = this.property.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  10434. return (this.propertyKey =
  10435. value === SymbolToStringTag
  10436. ? value
  10437. : typeof value === 'symbol'
  10438. ? UnknownKey
  10439. : String(value));
  10440. }
  10441. return this.propertyKey;
  10442. }
  10443. hasAccessEffect(context) {
  10444. const { propertyReadSideEffects } = this.context.options
  10445. .treeshake;
  10446. return (!(this.variable || this.isUndefined) &&
  10447. propertyReadSideEffects &&
  10448. (propertyReadSideEffects === 'always' ||
  10449. this.object.hasEffectsOnInteractionAtPath([this.getPropertyKey()], this.accessInteraction, context)));
  10450. }
  10451. includeProperties(context, includeChildrenRecursively) {
  10452. if (!this.included) {
  10453. this.included = true;
  10454. if (this.variable) {
  10455. this.context.includeVariableInModule(this.variable);
  10456. }
  10457. }
  10458. this.object.include(context, includeChildrenRecursively);
  10459. this.property.include(context, includeChildrenRecursively);
  10460. }
  10461. }
  10462. function resolveNamespaceVariables(baseVariable, path, astContext) {
  10463. if (path.length === 0)
  10464. return baseVariable;
  10465. if (!baseVariable.isNamespace || baseVariable instanceof ExternalVariable)
  10466. return null;
  10467. const exportName = path[0].key;
  10468. const variable = baseVariable.context.traceExport(exportName);
  10469. if (!variable) {
  10470. if (path.length === 1) {
  10471. const fileName = baseVariable.context.fileName;
  10472. astContext.log(LOGLEVEL_WARN, logMissingExport(exportName, astContext.module.id, fileName), path[0].pos);
  10473. return 'undefined';
  10474. }
  10475. return null;
  10476. }
  10477. return resolveNamespaceVariables(variable, path.slice(1), astContext);
  10478. }
  10479. class CallExpressionBase extends NodeBase {
  10480. constructor() {
  10481. super(...arguments);
  10482. this.returnExpression = null;
  10483. this.deoptimizableDependentExpressions = [];
  10484. this.expressionsToBeDeoptimized = new Set();
  10485. }
  10486. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  10487. const { args } = interaction;
  10488. const [returnExpression, isPure] = this.getReturnExpression(recursionTracker);
  10489. if (isPure)
  10490. return;
  10491. const deoptimizedExpressions = args.filter(expression => !!expression && expression !== UNKNOWN_EXPRESSION);
  10492. if (deoptimizedExpressions.length === 0)
  10493. return;
  10494. if (returnExpression === UNKNOWN_EXPRESSION) {
  10495. for (const expression of deoptimizedExpressions) {
  10496. expression.deoptimizePath(UNKNOWN_PATH);
  10497. }
  10498. }
  10499. else {
  10500. recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  10501. for (const expression of deoptimizedExpressions) {
  10502. this.expressionsToBeDeoptimized.add(expression);
  10503. }
  10504. returnExpression.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  10505. }, null);
  10506. }
  10507. }
  10508. deoptimizeCache() {
  10509. if (this.returnExpression?.[0] !== UNKNOWN_EXPRESSION) {
  10510. this.returnExpression = UNKNOWN_RETURN_EXPRESSION;
  10511. const { deoptimizableDependentExpressions, expressionsToBeDeoptimized } = this;
  10512. this.expressionsToBeDeoptimized = EMPTY_SET;
  10513. this.deoptimizableDependentExpressions = EMPTY_ARRAY;
  10514. for (const expression of deoptimizableDependentExpressions) {
  10515. expression.deoptimizeCache();
  10516. }
  10517. for (const expression of expressionsToBeDeoptimized) {
  10518. expression.deoptimizePath(UNKNOWN_PATH);
  10519. }
  10520. }
  10521. }
  10522. deoptimizePath(path) {
  10523. if (path.length === 0 ||
  10524. this.context.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  10525. return;
  10526. }
  10527. const [returnExpression] = this.getReturnExpression();
  10528. if (returnExpression !== UNKNOWN_EXPRESSION) {
  10529. returnExpression.deoptimizePath(path);
  10530. }
  10531. }
  10532. getLiteralValueAtPath(path, recursionTracker, origin) {
  10533. const [returnExpression] = this.getReturnExpression(recursionTracker);
  10534. if (returnExpression === UNKNOWN_EXPRESSION) {
  10535. return UnknownValue;
  10536. }
  10537. return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  10538. this.deoptimizableDependentExpressions.push(origin);
  10539. return returnExpression.getLiteralValueAtPath(path, recursionTracker, origin);
  10540. }, UnknownValue);
  10541. }
  10542. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  10543. const returnExpression = this.getReturnExpression(recursionTracker);
  10544. if (returnExpression[0] === UNKNOWN_EXPRESSION) {
  10545. return returnExpression;
  10546. }
  10547. return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  10548. this.deoptimizableDependentExpressions.push(origin);
  10549. const [expression, isPure] = returnExpression[0].getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  10550. return [expression, isPure || returnExpression[1]];
  10551. }, UNKNOWN_RETURN_EXPRESSION);
  10552. }
  10553. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10554. const { type } = interaction;
  10555. if (type === INTERACTION_CALLED) {
  10556. const { args, withNew } = interaction;
  10557. if ((withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, args, this)) {
  10558. return false;
  10559. }
  10560. }
  10561. else if ((type === INTERACTION_ASSIGNED
  10562. ? context.assigned
  10563. : context.accessed).trackEntityAtPathAndGetIfTracked(path, this)) {
  10564. return false;
  10565. }
  10566. const [returnExpression, isPure] = this.getReturnExpression();
  10567. return ((type === INTERACTION_ASSIGNED || !isPure) &&
  10568. returnExpression.hasEffectsOnInteractionAtPath(path, interaction, context));
  10569. }
  10570. }
  10571. class CallExpression extends CallExpressionBase {
  10572. bind() {
  10573. super.bind();
  10574. if (this.callee instanceof Identifier) {
  10575. const variable = this.scope.findVariable(this.callee.name);
  10576. if (variable.isNamespace) {
  10577. this.context.log(LOGLEVEL_WARN, logCannotCallNamespace(this.callee.name), this.start);
  10578. }
  10579. if (this.callee.name === 'eval') {
  10580. this.context.log(LOGLEVEL_WARN, logEval(this.context.module.id), this.start);
  10581. }
  10582. }
  10583. this.interaction = {
  10584. args: [
  10585. this.callee instanceof MemberExpression && !this.callee.variable
  10586. ? this.callee.object
  10587. : null,
  10588. ...this.arguments
  10589. ],
  10590. type: INTERACTION_CALLED,
  10591. withNew: false
  10592. };
  10593. }
  10594. hasEffects(context) {
  10595. try {
  10596. for (const argument of this.arguments) {
  10597. if (argument.hasEffects(context))
  10598. return true;
  10599. }
  10600. if (this.annotationPure) {
  10601. return false;
  10602. }
  10603. return (this.callee.hasEffects(context) ||
  10604. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  10605. }
  10606. finally {
  10607. if (!this.deoptimized)
  10608. this.applyDeoptimizations();
  10609. }
  10610. }
  10611. include(context, includeChildrenRecursively) {
  10612. if (!this.deoptimized)
  10613. this.applyDeoptimizations();
  10614. if (includeChildrenRecursively) {
  10615. super.include(context, includeChildrenRecursively);
  10616. if (includeChildrenRecursively === INCLUDE_PARAMETERS &&
  10617. this.callee instanceof Identifier &&
  10618. this.callee.variable) {
  10619. this.callee.variable.markCalledFromTryStatement();
  10620. }
  10621. }
  10622. else {
  10623. this.included = true;
  10624. this.callee.include(context, false);
  10625. }
  10626. this.callee.includeCallArguments(context, this.arguments);
  10627. }
  10628. isSkippedAsOptional(origin) {
  10629. return (this.callee.isSkippedAsOptional?.(origin) ||
  10630. (this.optional &&
  10631. this.callee.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, origin) == null));
  10632. }
  10633. render(code, options, { renderedSurroundingElement } = BLANK) {
  10634. this.callee.render(code, options, {
  10635. isCalleeOfRenderedParent: true,
  10636. renderedSurroundingElement
  10637. });
  10638. renderCallArguments(code, options, this);
  10639. }
  10640. applyDeoptimizations() {
  10641. this.deoptimized = true;
  10642. this.callee.deoptimizeArgumentsOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  10643. this.context.requestTreeshakingPass();
  10644. }
  10645. getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) {
  10646. if (this.returnExpression === null) {
  10647. this.returnExpression = UNKNOWN_RETURN_EXPRESSION;
  10648. return (this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.interaction, recursionTracker, this));
  10649. }
  10650. return this.returnExpression;
  10651. }
  10652. }
  10653. class CatchScope extends ParameterScope {
  10654. addDeclaration(identifier, context, init, isHoisted) {
  10655. const existingParameter = this.variables.get(identifier.name);
  10656. if (existingParameter) {
  10657. // While we still create a hoisted declaration, the initializer goes to
  10658. // the parameter. Note that technically, the declaration now belongs to
  10659. // two variables, which is not correct but should not cause issues.
  10660. this.parent.addDeclaration(identifier, context, UNDEFINED_EXPRESSION, isHoisted);
  10661. existingParameter.addDeclaration(identifier, init);
  10662. return existingParameter;
  10663. }
  10664. return this.parent.addDeclaration(identifier, context, init, isHoisted);
  10665. }
  10666. }
  10667. class CatchClause extends NodeBase {
  10668. createScope(parentScope) {
  10669. this.scope = new CatchScope(parentScope, this.context);
  10670. }
  10671. parseNode(esTreeNode) {
  10672. // Parameters need to be declared first as the logic is that initializers
  10673. // of hoisted body variables are associated with parameters of the same
  10674. // name instead of the variable
  10675. const { param } = esTreeNode;
  10676. if (param) {
  10677. this.param = new (this.context.getNodeConstructor(param.type))(param, this, this.scope);
  10678. this.param.declare('parameter', UNKNOWN_EXPRESSION);
  10679. }
  10680. super.parseNode(esTreeNode);
  10681. }
  10682. }
  10683. class ChainExpression extends NodeBase {
  10684. // deoptimizations are not relevant as we are not caching values
  10685. deoptimizeCache() { }
  10686. getLiteralValueAtPath(path, recursionTracker, origin) {
  10687. if (this.expression.isSkippedAsOptional(origin))
  10688. return undefined;
  10689. return this.expression.getLiteralValueAtPath(path, recursionTracker, origin);
  10690. }
  10691. hasEffects(context) {
  10692. if (this.expression.isSkippedAsOptional(this))
  10693. return false;
  10694. return this.expression.hasEffects(context);
  10695. }
  10696. }
  10697. class ClassBodyScope extends ChildScope {
  10698. constructor(parent, classNode, context) {
  10699. super(parent);
  10700. this.variables.set('this', (this.thisVariable = new LocalVariable('this', null, classNode, context)));
  10701. this.instanceScope = new ChildScope(this);
  10702. this.instanceScope.variables.set('this', new ThisVariable(context));
  10703. }
  10704. findLexicalBoundary() {
  10705. return this;
  10706. }
  10707. }
  10708. class ClassBody extends NodeBase {
  10709. createScope(parentScope) {
  10710. this.scope = new ClassBodyScope(parentScope, this.parent, this.context);
  10711. }
  10712. include(context, includeChildrenRecursively) {
  10713. this.included = true;
  10714. this.context.includeVariableInModule(this.scope.thisVariable);
  10715. for (const definition of this.body) {
  10716. definition.include(context, includeChildrenRecursively);
  10717. }
  10718. }
  10719. parseNode(esTreeNode) {
  10720. const body = (this.body = []);
  10721. for (const definition of esTreeNode.body) {
  10722. body.push(new (this.context.getNodeConstructor(definition.type))(definition, this, definition.static ? this.scope : this.scope.instanceScope));
  10723. }
  10724. super.parseNode(esTreeNode);
  10725. }
  10726. applyDeoptimizations() { }
  10727. }
  10728. class MethodBase extends NodeBase {
  10729. constructor() {
  10730. super(...arguments);
  10731. this.accessedValue = null;
  10732. }
  10733. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  10734. if (interaction.type === INTERACTION_ACCESSED && this.kind === 'get' && path.length === 0) {
  10735. return this.value.deoptimizeArgumentsOnInteractionAtPath({
  10736. args: interaction.args,
  10737. type: INTERACTION_CALLED,
  10738. withNew: false
  10739. }, EMPTY_PATH, recursionTracker);
  10740. }
  10741. if (interaction.type === INTERACTION_ASSIGNED && this.kind === 'set' && path.length === 0) {
  10742. return this.value.deoptimizeArgumentsOnInteractionAtPath({
  10743. args: interaction.args,
  10744. type: INTERACTION_CALLED,
  10745. withNew: false
  10746. }, EMPTY_PATH, recursionTracker);
  10747. }
  10748. this.getAccessedValue()[0].deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  10749. }
  10750. // As getter properties directly receive their values from fixed function
  10751. // expressions, there is no known situation where a getter is deoptimized.
  10752. deoptimizeCache() { }
  10753. deoptimizePath(path) {
  10754. this.getAccessedValue()[0].deoptimizePath(path);
  10755. }
  10756. getLiteralValueAtPath(path, recursionTracker, origin) {
  10757. return this.getAccessedValue()[0].getLiteralValueAtPath(path, recursionTracker, origin);
  10758. }
  10759. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  10760. return this.getAccessedValue()[0].getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  10761. }
  10762. hasEffects(context) {
  10763. return this.key.hasEffects(context);
  10764. }
  10765. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10766. if (this.kind === 'get' && interaction.type === INTERACTION_ACCESSED && path.length === 0) {
  10767. return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
  10768. args: interaction.args,
  10769. type: INTERACTION_CALLED,
  10770. withNew: false
  10771. }, context);
  10772. }
  10773. // setters are only called for empty paths
  10774. if (this.kind === 'set' && interaction.type === INTERACTION_ASSIGNED) {
  10775. return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
  10776. args: interaction.args,
  10777. type: INTERACTION_CALLED,
  10778. withNew: false
  10779. }, context);
  10780. }
  10781. return this.getAccessedValue()[0].hasEffectsOnInteractionAtPath(path, interaction, context);
  10782. }
  10783. applyDeoptimizations() { }
  10784. getAccessedValue() {
  10785. if (this.accessedValue === null) {
  10786. if (this.kind === 'get') {
  10787. this.accessedValue = UNKNOWN_RETURN_EXPRESSION;
  10788. return (this.accessedValue = this.value.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, SHARED_RECURSION_TRACKER, this));
  10789. }
  10790. else {
  10791. return (this.accessedValue = [this.value, false]);
  10792. }
  10793. }
  10794. return this.accessedValue;
  10795. }
  10796. }
  10797. class MethodDefinition extends MethodBase {
  10798. applyDeoptimizations() { }
  10799. }
  10800. class ObjectMember extends ExpressionEntity {
  10801. constructor(object, key) {
  10802. super();
  10803. this.object = object;
  10804. this.key = key;
  10805. }
  10806. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  10807. this.object.deoptimizeArgumentsOnInteractionAtPath(interaction, [this.key, ...path], recursionTracker);
  10808. }
  10809. deoptimizePath(path) {
  10810. this.object.deoptimizePath([this.key, ...path]);
  10811. }
  10812. getLiteralValueAtPath(path, recursionTracker, origin) {
  10813. return this.object.getLiteralValueAtPath([this.key, ...path], recursionTracker, origin);
  10814. }
  10815. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  10816. return this.object.getReturnExpressionWhenCalledAtPath([this.key, ...path], interaction, recursionTracker, origin);
  10817. }
  10818. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10819. return this.object.hasEffectsOnInteractionAtPath([this.key, ...path], interaction, context);
  10820. }
  10821. }
  10822. class ClassNode extends NodeBase {
  10823. constructor() {
  10824. super(...arguments);
  10825. this.objectEntity = null;
  10826. }
  10827. createScope(parentScope) {
  10828. this.scope = new ChildScope(parentScope);
  10829. }
  10830. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  10831. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  10832. }
  10833. deoptimizeCache() {
  10834. this.getObjectEntity().deoptimizeAllProperties();
  10835. }
  10836. deoptimizePath(path) {
  10837. this.getObjectEntity().deoptimizePath(path);
  10838. }
  10839. getLiteralValueAtPath(path, recursionTracker, origin) {
  10840. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  10841. }
  10842. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  10843. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  10844. }
  10845. hasEffects(context) {
  10846. if (!this.deoptimized)
  10847. this.applyDeoptimizations();
  10848. const initEffect = this.superClass?.hasEffects(context) || this.body.hasEffects(context);
  10849. this.id?.markDeclarationReached();
  10850. return initEffect || super.hasEffects(context);
  10851. }
  10852. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10853. return interaction.type === INTERACTION_CALLED && path.length === 0
  10854. ? !interaction.withNew ||
  10855. (this.classConstructor === null
  10856. ? this.superClass?.hasEffectsOnInteractionAtPath(path, interaction, context)
  10857. : this.classConstructor.hasEffectsOnInteractionAtPath(path, interaction, context)) ||
  10858. false
  10859. : this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  10860. }
  10861. include(context, includeChildrenRecursively) {
  10862. if (!this.deoptimized)
  10863. this.applyDeoptimizations();
  10864. this.included = true;
  10865. this.superClass?.include(context, includeChildrenRecursively);
  10866. this.body.include(context, includeChildrenRecursively);
  10867. if (this.id) {
  10868. this.id.markDeclarationReached();
  10869. this.id.include();
  10870. }
  10871. }
  10872. initialise() {
  10873. this.id?.declare('class', this);
  10874. for (const method of this.body.body) {
  10875. if (method instanceof MethodDefinition && method.kind === 'constructor') {
  10876. this.classConstructor = method;
  10877. return;
  10878. }
  10879. }
  10880. this.classConstructor = null;
  10881. }
  10882. applyDeoptimizations() {
  10883. this.deoptimized = true;
  10884. for (const definition of this.body.body) {
  10885. if (!(definition.static ||
  10886. (definition instanceof MethodDefinition && definition.kind === 'constructor'))) {
  10887. // Calls to methods are not tracked, ensure that the return value is deoptimized
  10888. definition.deoptimizePath(UNKNOWN_PATH);
  10889. }
  10890. }
  10891. this.context.requestTreeshakingPass();
  10892. }
  10893. getObjectEntity() {
  10894. if (this.objectEntity !== null) {
  10895. return this.objectEntity;
  10896. }
  10897. const staticProperties = [];
  10898. const dynamicMethods = [];
  10899. for (const definition of this.body.body) {
  10900. const properties = definition.static ? staticProperties : dynamicMethods;
  10901. const definitionKind = definition.kind;
  10902. // Note that class fields do not end up on the prototype
  10903. if (properties === dynamicMethods && !definitionKind)
  10904. continue;
  10905. const kind = definitionKind === 'set' || definitionKind === 'get' ? definitionKind : 'init';
  10906. let key;
  10907. if (definition.computed) {
  10908. const keyValue = definition.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  10909. if (typeof keyValue === 'symbol') {
  10910. properties.push({ key: UnknownKey, kind, property: definition });
  10911. continue;
  10912. }
  10913. else {
  10914. key = String(keyValue);
  10915. }
  10916. }
  10917. else {
  10918. key =
  10919. definition.key instanceof Identifier
  10920. ? definition.key.name
  10921. : String(definition.key.value);
  10922. }
  10923. properties.push({ key, kind, property: definition });
  10924. }
  10925. staticProperties.unshift({
  10926. key: 'prototype',
  10927. kind: 'init',
  10928. property: new ObjectEntity(dynamicMethods, this.superClass ? new ObjectMember(this.superClass, 'prototype') : OBJECT_PROTOTYPE)
  10929. });
  10930. return (this.objectEntity = new ObjectEntity(staticProperties, this.superClass || OBJECT_PROTOTYPE));
  10931. }
  10932. }
  10933. class ClassDeclaration extends ClassNode {
  10934. initialise() {
  10935. super.initialise();
  10936. if (this.id !== null) {
  10937. this.id.variable.isId = true;
  10938. }
  10939. }
  10940. parseNode(esTreeNode) {
  10941. if (esTreeNode.id !== null) {
  10942. this.id = new Identifier(esTreeNode.id, this, this.scope.parent);
  10943. }
  10944. super.parseNode(esTreeNode);
  10945. }
  10946. render(code, options) {
  10947. const { exportNamesByVariable, format, snippets: { _, getPropertyAccess } } = options;
  10948. if (this.id) {
  10949. const { variable, name } = this.id;
  10950. if (format === 'system' && exportNamesByVariable.has(variable)) {
  10951. code.appendLeft(this.end, `${_}${getSystemExportStatement([variable], options)};`);
  10952. }
  10953. const renderedVariable = variable.getName(getPropertyAccess);
  10954. if (renderedVariable !== name) {
  10955. this.superClass?.render(code, options);
  10956. this.body.render(code, {
  10957. ...options,
  10958. useOriginalName: (_variable) => _variable === variable
  10959. });
  10960. code.prependRight(this.start, `let ${renderedVariable}${_}=${_}`);
  10961. code.prependLeft(this.end, ';');
  10962. return;
  10963. }
  10964. }
  10965. super.render(code, options);
  10966. }
  10967. applyDeoptimizations() {
  10968. super.applyDeoptimizations();
  10969. const { id, scope } = this;
  10970. if (id) {
  10971. const { name, variable } = id;
  10972. for (const accessedVariable of scope.accessedOutsideVariables.values()) {
  10973. if (accessedVariable !== variable) {
  10974. accessedVariable.forbidName(name);
  10975. }
  10976. }
  10977. }
  10978. }
  10979. }
  10980. class ClassExpression extends ClassNode {
  10981. render(code, options, { renderedSurroundingElement } = BLANK) {
  10982. super.render(code, options);
  10983. if (renderedSurroundingElement === ExpressionStatement$1) {
  10984. code.appendRight(this.start, '(');
  10985. code.prependLeft(this.end, ')');
  10986. }
  10987. }
  10988. }
  10989. class MultiExpression extends ExpressionEntity {
  10990. constructor(expressions) {
  10991. super();
  10992. this.expressions = expressions;
  10993. this.included = false;
  10994. }
  10995. deoptimizePath(path) {
  10996. for (const expression of this.expressions) {
  10997. expression.deoptimizePath(path);
  10998. }
  10999. }
  11000. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  11001. return [
  11002. new MultiExpression(this.expressions.map(expression => expression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0])),
  11003. false
  11004. ];
  11005. }
  11006. hasEffectsOnInteractionAtPath(path, interaction, context) {
  11007. for (const expression of this.expressions) {
  11008. if (expression.hasEffectsOnInteractionAtPath(path, interaction, context))
  11009. return true;
  11010. }
  11011. return false;
  11012. }
  11013. }
  11014. class ConditionalExpression extends NodeBase {
  11015. constructor() {
  11016. super(...arguments);
  11017. this.expressionsToBeDeoptimized = [];
  11018. this.isBranchResolutionAnalysed = false;
  11019. this.usedBranch = null;
  11020. }
  11021. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  11022. this.consequent.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  11023. this.alternate.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  11024. }
  11025. deoptimizeCache() {
  11026. if (this.usedBranch !== null) {
  11027. const unusedBranch = this.usedBranch === this.consequent ? this.alternate : this.consequent;
  11028. this.usedBranch = null;
  11029. unusedBranch.deoptimizePath(UNKNOWN_PATH);
  11030. const { expressionsToBeDeoptimized } = this;
  11031. this.expressionsToBeDeoptimized = EMPTY_ARRAY;
  11032. for (const expression of expressionsToBeDeoptimized) {
  11033. expression.deoptimizeCache();
  11034. }
  11035. }
  11036. }
  11037. deoptimizePath(path) {
  11038. const usedBranch = this.getUsedBranch();
  11039. if (usedBranch) {
  11040. usedBranch.deoptimizePath(path);
  11041. }
  11042. else {
  11043. this.consequent.deoptimizePath(path);
  11044. this.alternate.deoptimizePath(path);
  11045. }
  11046. }
  11047. getLiteralValueAtPath(path, recursionTracker, origin) {
  11048. const usedBranch = this.getUsedBranch();
  11049. if (!usedBranch)
  11050. return UnknownValue;
  11051. this.expressionsToBeDeoptimized.push(origin);
  11052. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  11053. }
  11054. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  11055. const usedBranch = this.getUsedBranch();
  11056. if (!usedBranch)
  11057. return [
  11058. new MultiExpression([
  11059. this.consequent.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0],
  11060. this.alternate.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0]
  11061. ]),
  11062. false
  11063. ];
  11064. this.expressionsToBeDeoptimized.push(origin);
  11065. return usedBranch.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  11066. }
  11067. hasEffects(context) {
  11068. if (this.test.hasEffects(context))
  11069. return true;
  11070. const usedBranch = this.getUsedBranch();
  11071. if (!usedBranch) {
  11072. return this.consequent.hasEffects(context) || this.alternate.hasEffects(context);
  11073. }
  11074. return usedBranch.hasEffects(context);
  11075. }
  11076. hasEffectsOnInteractionAtPath(path, interaction, context) {
  11077. const usedBranch = this.getUsedBranch();
  11078. if (!usedBranch) {
  11079. return (this.consequent.hasEffectsOnInteractionAtPath(path, interaction, context) ||
  11080. this.alternate.hasEffectsOnInteractionAtPath(path, interaction, context));
  11081. }
  11082. return usedBranch.hasEffectsOnInteractionAtPath(path, interaction, context);
  11083. }
  11084. include(context, includeChildrenRecursively) {
  11085. this.included = true;
  11086. const usedBranch = this.getUsedBranch();
  11087. if (includeChildrenRecursively || this.test.shouldBeIncluded(context) || usedBranch === null) {
  11088. this.test.include(context, includeChildrenRecursively);
  11089. this.consequent.include(context, includeChildrenRecursively);
  11090. this.alternate.include(context, includeChildrenRecursively);
  11091. }
  11092. else {
  11093. usedBranch.include(context, includeChildrenRecursively);
  11094. }
  11095. }
  11096. includeCallArguments(context, parameters) {
  11097. const usedBranch = this.getUsedBranch();
  11098. if (usedBranch) {
  11099. usedBranch.includeCallArguments(context, parameters);
  11100. }
  11101. else {
  11102. this.consequent.includeCallArguments(context, parameters);
  11103. this.alternate.includeCallArguments(context, parameters);
  11104. }
  11105. }
  11106. render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  11107. const usedBranch = this.getUsedBranch();
  11108. if (this.test.included) {
  11109. this.test.render(code, options, { renderedSurroundingElement });
  11110. this.consequent.render(code, options);
  11111. this.alternate.render(code, options);
  11112. }
  11113. else {
  11114. const colonPos = findFirstOccurrenceOutsideComment(code.original, ':', this.consequent.end);
  11115. const inclusionStart = findNonWhiteSpace(code.original, (this.consequent.included
  11116. ? findFirstOccurrenceOutsideComment(code.original, '?', this.test.end)
  11117. : colonPos) + 1);
  11118. if (preventASI) {
  11119. removeLineBreaks(code, inclusionStart, usedBranch.start);
  11120. }
  11121. code.remove(this.start, inclusionStart);
  11122. if (this.consequent.included) {
  11123. code.remove(colonPos, this.end);
  11124. }
  11125. removeAnnotations(this, code);
  11126. usedBranch.render(code, options, {
  11127. isCalleeOfRenderedParent,
  11128. preventASI: true,
  11129. renderedParentType: renderedParentType || this.parent.type,
  11130. renderedSurroundingElement: renderedSurroundingElement || this.parent.type
  11131. });
  11132. }
  11133. }
  11134. getUsedBranch() {
  11135. if (this.isBranchResolutionAnalysed) {
  11136. return this.usedBranch;
  11137. }
  11138. this.isBranchResolutionAnalysed = true;
  11139. const testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  11140. return typeof testValue === 'symbol'
  11141. ? null
  11142. : (this.usedBranch = testValue ? this.consequent : this.alternate);
  11143. }
  11144. }
  11145. class ContinueStatement extends NodeBase {
  11146. hasEffects(context) {
  11147. if (this.label) {
  11148. if (!context.ignore.labels.has(this.label.name))
  11149. return true;
  11150. context.includedLabels.add(this.label.name);
  11151. }
  11152. else {
  11153. if (!context.ignore.continues)
  11154. return true;
  11155. context.hasContinue = true;
  11156. }
  11157. context.brokenFlow = true;
  11158. return false;
  11159. }
  11160. include(context) {
  11161. this.included = true;
  11162. if (this.label) {
  11163. this.label.include();
  11164. context.includedLabels.add(this.label.name);
  11165. }
  11166. else {
  11167. context.hasContinue = true;
  11168. }
  11169. context.brokenFlow = true;
  11170. }
  11171. }
  11172. function hasLoopBodyEffects(context, body) {
  11173. const { brokenFlow, hasBreak, hasContinue, ignore } = context;
  11174. const { breaks, continues } = ignore;
  11175. ignore.breaks = true;
  11176. ignore.continues = true;
  11177. context.hasBreak = false;
  11178. context.hasContinue = false;
  11179. if (body.hasEffects(context))
  11180. return true;
  11181. ignore.breaks = breaks;
  11182. ignore.continues = continues;
  11183. context.hasBreak = hasBreak;
  11184. context.hasContinue = hasContinue;
  11185. context.brokenFlow = brokenFlow;
  11186. return false;
  11187. }
  11188. function includeLoopBody(context, body, includeChildrenRecursively) {
  11189. const { brokenFlow, hasBreak, hasContinue } = context;
  11190. context.hasBreak = false;
  11191. context.hasContinue = false;
  11192. body.include(context, includeChildrenRecursively, { asSingleStatement: true });
  11193. context.hasBreak = hasBreak;
  11194. context.hasContinue = hasContinue;
  11195. context.brokenFlow = brokenFlow;
  11196. }
  11197. class DoWhileStatement extends NodeBase {
  11198. hasEffects(context) {
  11199. if (this.test.hasEffects(context))
  11200. return true;
  11201. return hasLoopBodyEffects(context, this.body);
  11202. }
  11203. include(context, includeChildrenRecursively) {
  11204. this.included = true;
  11205. this.test.include(context, includeChildrenRecursively);
  11206. includeLoopBody(context, this.body, includeChildrenRecursively);
  11207. }
  11208. }
  11209. class EmptyStatement extends NodeBase {
  11210. hasEffects() {
  11211. return false;
  11212. }
  11213. }
  11214. class ExportAllDeclaration extends NodeBase {
  11215. hasEffects() {
  11216. return false;
  11217. }
  11218. initialise() {
  11219. this.context.addExport(this);
  11220. }
  11221. render(code, _options, nodeRenderOptions) {
  11222. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  11223. }
  11224. applyDeoptimizations() { }
  11225. }
  11226. ExportAllDeclaration.prototype.needsBoundaries = true;
  11227. class FunctionDeclaration extends FunctionNode {
  11228. initialise() {
  11229. super.initialise();
  11230. if (this.id !== null) {
  11231. this.id.variable.isId = true;
  11232. }
  11233. }
  11234. parseNode(esTreeNode) {
  11235. if (esTreeNode.id !== null) {
  11236. this.id = new Identifier(esTreeNode.id, this, this.scope.parent);
  11237. }
  11238. super.parseNode(esTreeNode);
  11239. }
  11240. }
  11241. // The header ends at the first non-white-space after "default"
  11242. function getDeclarationStart(code, start) {
  11243. return findNonWhiteSpace(code, findFirstOccurrenceOutsideComment(code, 'default', start) + 7);
  11244. }
  11245. function getFunctionIdInsertPosition(code, start) {
  11246. const declarationEnd = findFirstOccurrenceOutsideComment(code, 'function', start) + 'function'.length;
  11247. code = code.slice(declarationEnd, findFirstOccurrenceOutsideComment(code, '(', declarationEnd));
  11248. const generatorStarPos = findFirstOccurrenceOutsideComment(code, '*');
  11249. if (generatorStarPos === -1) {
  11250. return declarationEnd;
  11251. }
  11252. return declarationEnd + generatorStarPos + 1;
  11253. }
  11254. class ExportDefaultDeclaration extends NodeBase {
  11255. include(context, includeChildrenRecursively) {
  11256. super.include(context, includeChildrenRecursively);
  11257. if (includeChildrenRecursively) {
  11258. this.context.includeVariableInModule(this.variable);
  11259. }
  11260. }
  11261. initialise() {
  11262. const declaration = this.declaration;
  11263. this.declarationName =
  11264. (declaration.id && declaration.id.name) || this.declaration.name;
  11265. this.variable = this.scope.addExportDefaultDeclaration(this.declarationName || this.context.getModuleName(), this, this.context);
  11266. this.context.addExport(this);
  11267. }
  11268. render(code, options, nodeRenderOptions) {
  11269. const { start, end } = nodeRenderOptions;
  11270. const declarationStart = getDeclarationStart(code.original, this.start);
  11271. if (this.declaration instanceof FunctionDeclaration) {
  11272. this.renderNamedDeclaration(code, declarationStart, this.declaration.id === null
  11273. ? getFunctionIdInsertPosition(code.original, declarationStart)
  11274. : null, options);
  11275. }
  11276. else if (this.declaration instanceof ClassDeclaration) {
  11277. this.renderNamedDeclaration(code, declarationStart, this.declaration.id === null
  11278. ? findFirstOccurrenceOutsideComment(code.original, 'class', start) + 'class'.length
  11279. : null, options);
  11280. }
  11281. else if (this.variable.getOriginalVariable() !== this.variable) {
  11282. // Remove altogether to prevent re-declaring the same variable
  11283. treeshakeNode(this, code, start, end);
  11284. return;
  11285. }
  11286. else if (this.variable.included) {
  11287. this.renderVariableDeclaration(code, declarationStart, options);
  11288. }
  11289. else {
  11290. code.remove(this.start, declarationStart);
  11291. this.declaration.render(code, options, {
  11292. renderedSurroundingElement: ExpressionStatement$1
  11293. });
  11294. if (code.original[this.end - 1] !== ';') {
  11295. code.appendLeft(this.end, ';');
  11296. }
  11297. return;
  11298. }
  11299. this.declaration.render(code, options);
  11300. }
  11301. applyDeoptimizations() { }
  11302. renderNamedDeclaration(code, declarationStart, idInsertPosition, options) {
  11303. const { exportNamesByVariable, format, snippets: { getPropertyAccess } } = options;
  11304. const name = this.variable.getName(getPropertyAccess);
  11305. // Remove `export default`
  11306. code.remove(this.start, declarationStart);
  11307. if (idInsertPosition !== null) {
  11308. code.appendLeft(idInsertPosition, ` ${name}`);
  11309. }
  11310. if (format === 'system' &&
  11311. this.declaration instanceof ClassDeclaration &&
  11312. exportNamesByVariable.has(this.variable)) {
  11313. code.appendLeft(this.end, ` ${getSystemExportStatement([this.variable], options)};`);
  11314. }
  11315. }
  11316. renderVariableDeclaration(code, declarationStart, { format, exportNamesByVariable, snippets: { cnst, getPropertyAccess } }) {
  11317. const hasTrailingSemicolon = code.original.charCodeAt(this.end - 1) === 59; /*";"*/
  11318. const systemExportNames = format === 'system' && exportNamesByVariable.get(this.variable);
  11319. if (systemExportNames) {
  11320. code.overwrite(this.start, declarationStart, `${cnst} ${this.variable.getName(getPropertyAccess)} = exports('${systemExportNames[0]}', `);
  11321. code.appendRight(hasTrailingSemicolon ? this.end - 1 : this.end, ')' + (hasTrailingSemicolon ? '' : ';'));
  11322. }
  11323. else {
  11324. code.overwrite(this.start, declarationStart, `${cnst} ${this.variable.getName(getPropertyAccess)} = `);
  11325. if (!hasTrailingSemicolon) {
  11326. code.appendLeft(this.end, ';');
  11327. }
  11328. }
  11329. }
  11330. }
  11331. ExportDefaultDeclaration.prototype.needsBoundaries = true;
  11332. class ExportNamedDeclaration extends NodeBase {
  11333. bind() {
  11334. // Do not bind specifiers
  11335. this.declaration?.bind();
  11336. }
  11337. hasEffects(context) {
  11338. return !!this.declaration?.hasEffects(context);
  11339. }
  11340. initialise() {
  11341. this.context.addExport(this);
  11342. }
  11343. render(code, options, nodeRenderOptions) {
  11344. const { start, end } = nodeRenderOptions;
  11345. if (this.declaration === null) {
  11346. code.remove(start, end);
  11347. }
  11348. else {
  11349. code.remove(this.start, this.declaration.start);
  11350. this.declaration.render(code, options, { end, start });
  11351. }
  11352. }
  11353. applyDeoptimizations() { }
  11354. }
  11355. ExportNamedDeclaration.prototype.needsBoundaries = true;
  11356. class ExportSpecifier extends NodeBase {
  11357. applyDeoptimizations() { }
  11358. }
  11359. class ForInStatement extends NodeBase {
  11360. createScope(parentScope) {
  11361. this.scope = new BlockScope(parentScope);
  11362. }
  11363. hasEffects(context) {
  11364. const { body, deoptimized, left, right } = this;
  11365. if (!deoptimized)
  11366. this.applyDeoptimizations();
  11367. if (left.hasEffectsAsAssignmentTarget(context, false) || right.hasEffects(context))
  11368. return true;
  11369. return hasLoopBodyEffects(context, body);
  11370. }
  11371. include(context, includeChildrenRecursively) {
  11372. const { body, deoptimized, left, right } = this;
  11373. if (!deoptimized)
  11374. this.applyDeoptimizations();
  11375. this.included = true;
  11376. left.includeAsAssignmentTarget(context, includeChildrenRecursively || true, false);
  11377. right.include(context, includeChildrenRecursively);
  11378. includeLoopBody(context, body, includeChildrenRecursively);
  11379. }
  11380. initialise() {
  11381. this.left.setAssignedValue(UNKNOWN_EXPRESSION);
  11382. }
  11383. render(code, options) {
  11384. this.left.render(code, options, NO_SEMICOLON);
  11385. this.right.render(code, options, NO_SEMICOLON);
  11386. // handle no space between "in" and the right side
  11387. if (code.original.charCodeAt(this.right.start - 1) === 110 /* n */) {
  11388. code.prependLeft(this.right.start, ' ');
  11389. }
  11390. this.body.render(code, options);
  11391. }
  11392. applyDeoptimizations() {
  11393. this.deoptimized = true;
  11394. this.left.deoptimizePath(EMPTY_PATH);
  11395. this.context.requestTreeshakingPass();
  11396. }
  11397. }
  11398. class ForOfStatement extends NodeBase {
  11399. createScope(parentScope) {
  11400. this.scope = new BlockScope(parentScope);
  11401. }
  11402. hasEffects() {
  11403. if (!this.deoptimized)
  11404. this.applyDeoptimizations();
  11405. // Placeholder until proper Symbol.Iterator support
  11406. return true;
  11407. }
  11408. include(context, includeChildrenRecursively) {
  11409. const { body, deoptimized, left, right } = this;
  11410. if (!deoptimized)
  11411. this.applyDeoptimizations();
  11412. this.included = true;
  11413. left.includeAsAssignmentTarget(context, includeChildrenRecursively || true, false);
  11414. right.include(context, includeChildrenRecursively);
  11415. includeLoopBody(context, body, includeChildrenRecursively);
  11416. }
  11417. initialise() {
  11418. this.left.setAssignedValue(UNKNOWN_EXPRESSION);
  11419. }
  11420. render(code, options) {
  11421. this.left.render(code, options, NO_SEMICOLON);
  11422. this.right.render(code, options, NO_SEMICOLON);
  11423. // handle no space between "of" and the right side
  11424. if (code.original.charCodeAt(this.right.start - 1) === 102 /* f */) {
  11425. code.prependLeft(this.right.start, ' ');
  11426. }
  11427. this.body.render(code, options);
  11428. }
  11429. applyDeoptimizations() {
  11430. this.deoptimized = true;
  11431. this.left.deoptimizePath(EMPTY_PATH);
  11432. this.right.deoptimizePath(UNKNOWN_PATH);
  11433. this.context.requestTreeshakingPass();
  11434. }
  11435. }
  11436. class ForStatement extends NodeBase {
  11437. createScope(parentScope) {
  11438. this.scope = new BlockScope(parentScope);
  11439. }
  11440. hasEffects(context) {
  11441. if (this.init?.hasEffects(context) ||
  11442. this.test?.hasEffects(context) ||
  11443. this.update?.hasEffects(context)) {
  11444. return true;
  11445. }
  11446. return hasLoopBodyEffects(context, this.body);
  11447. }
  11448. include(context, includeChildrenRecursively) {
  11449. this.included = true;
  11450. this.init?.include(context, includeChildrenRecursively, { asSingleStatement: true });
  11451. this.test?.include(context, includeChildrenRecursively);
  11452. this.update?.include(context, includeChildrenRecursively);
  11453. includeLoopBody(context, this.body, includeChildrenRecursively);
  11454. }
  11455. render(code, options) {
  11456. this.init?.render(code, options, NO_SEMICOLON);
  11457. this.test?.render(code, options, NO_SEMICOLON);
  11458. this.update?.render(code, options, NO_SEMICOLON);
  11459. this.body.render(code, options);
  11460. }
  11461. }
  11462. class FunctionExpression extends FunctionNode {
  11463. render(code, options, { renderedSurroundingElement } = BLANK) {
  11464. super.render(code, options);
  11465. if (renderedSurroundingElement === ExpressionStatement$1) {
  11466. code.appendRight(this.start, '(');
  11467. code.prependLeft(this.end, ')');
  11468. }
  11469. }
  11470. }
  11471. class TrackingScope extends BlockScope {
  11472. constructor() {
  11473. super(...arguments);
  11474. this.hoistedDeclarations = [];
  11475. }
  11476. addDeclaration(identifier, context, init, isHoisted) {
  11477. this.hoistedDeclarations.push(identifier);
  11478. return super.addDeclaration(identifier, context, init, isHoisted);
  11479. }
  11480. }
  11481. const unset = Symbol('unset');
  11482. class IfStatement extends NodeBase {
  11483. constructor() {
  11484. super(...arguments);
  11485. this.testValue = unset;
  11486. }
  11487. deoptimizeCache() {
  11488. this.testValue = UnknownValue;
  11489. }
  11490. hasEffects(context) {
  11491. if (this.test.hasEffects(context)) {
  11492. return true;
  11493. }
  11494. const testValue = this.getTestValue();
  11495. if (typeof testValue === 'symbol') {
  11496. const { brokenFlow } = context;
  11497. if (this.consequent.hasEffects(context))
  11498. return true;
  11499. // eslint-disable-next-line unicorn/consistent-destructuring
  11500. const consequentBrokenFlow = context.brokenFlow;
  11501. context.brokenFlow = brokenFlow;
  11502. if (this.alternate === null)
  11503. return false;
  11504. if (this.alternate.hasEffects(context))
  11505. return true;
  11506. // eslint-disable-next-line unicorn/consistent-destructuring
  11507. context.brokenFlow = context.brokenFlow && consequentBrokenFlow;
  11508. return false;
  11509. }
  11510. return testValue ? this.consequent.hasEffects(context) : !!this.alternate?.hasEffects(context);
  11511. }
  11512. include(context, includeChildrenRecursively) {
  11513. this.included = true;
  11514. if (includeChildrenRecursively) {
  11515. this.includeRecursively(includeChildrenRecursively, context);
  11516. }
  11517. else {
  11518. const testValue = this.getTestValue();
  11519. if (typeof testValue === 'symbol') {
  11520. this.includeUnknownTest(context);
  11521. }
  11522. else {
  11523. this.includeKnownTest(context, testValue);
  11524. }
  11525. }
  11526. }
  11527. parseNode(esTreeNode) {
  11528. this.consequentScope = new TrackingScope(this.scope);
  11529. this.consequent = new (this.context.getNodeConstructor(esTreeNode.consequent.type))(esTreeNode.consequent, this, this.consequentScope);
  11530. if (esTreeNode.alternate) {
  11531. this.alternateScope = new TrackingScope(this.scope);
  11532. this.alternate = new (this.context.getNodeConstructor(esTreeNode.alternate.type))(esTreeNode.alternate, this, this.alternateScope);
  11533. }
  11534. super.parseNode(esTreeNode);
  11535. }
  11536. render(code, options) {
  11537. const { snippets: { getPropertyAccess } } = options;
  11538. // Note that unknown test values are always included
  11539. const testValue = this.getTestValue();
  11540. const hoistedDeclarations = [];
  11541. const includesIfElse = this.test.included;
  11542. const noTreeshake = !this.context.options.treeshake;
  11543. if (includesIfElse) {
  11544. this.test.render(code, options);
  11545. }
  11546. else {
  11547. code.remove(this.start, this.consequent.start);
  11548. }
  11549. if (this.consequent.included && (noTreeshake || typeof testValue === 'symbol' || testValue)) {
  11550. this.consequent.render(code, options);
  11551. }
  11552. else {
  11553. code.overwrite(this.consequent.start, this.consequent.end, includesIfElse ? ';' : '');
  11554. hoistedDeclarations.push(...this.consequentScope.hoistedDeclarations);
  11555. }
  11556. if (this.alternate) {
  11557. if (this.alternate.included && (noTreeshake || typeof testValue === 'symbol' || !testValue)) {
  11558. if (includesIfElse) {
  11559. if (code.original.charCodeAt(this.alternate.start - 1) === 101) {
  11560. code.prependLeft(this.alternate.start, ' ');
  11561. }
  11562. }
  11563. else {
  11564. code.remove(this.consequent.end, this.alternate.start);
  11565. }
  11566. this.alternate.render(code, options);
  11567. }
  11568. else {
  11569. if (includesIfElse && this.shouldKeepAlternateBranch()) {
  11570. code.overwrite(this.alternate.start, this.end, ';');
  11571. }
  11572. else {
  11573. code.remove(this.consequent.end, this.end);
  11574. }
  11575. hoistedDeclarations.push(...this.alternateScope.hoistedDeclarations);
  11576. }
  11577. }
  11578. this.renderHoistedDeclarations(hoistedDeclarations, code, getPropertyAccess);
  11579. }
  11580. applyDeoptimizations() { }
  11581. getTestValue() {
  11582. if (this.testValue === unset) {
  11583. return (this.testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this));
  11584. }
  11585. return this.testValue;
  11586. }
  11587. includeKnownTest(context, testValue) {
  11588. if (this.test.shouldBeIncluded(context)) {
  11589. this.test.include(context, false);
  11590. }
  11591. if (testValue && this.consequent.shouldBeIncluded(context)) {
  11592. this.consequent.include(context, false, { asSingleStatement: true });
  11593. }
  11594. if (!testValue && this.alternate?.shouldBeIncluded(context)) {
  11595. this.alternate.include(context, false, { asSingleStatement: true });
  11596. }
  11597. }
  11598. includeRecursively(includeChildrenRecursively, context) {
  11599. this.test.include(context, includeChildrenRecursively);
  11600. this.consequent.include(context, includeChildrenRecursively);
  11601. this.alternate?.include(context, includeChildrenRecursively);
  11602. }
  11603. includeUnknownTest(context) {
  11604. this.test.include(context, false);
  11605. const { brokenFlow } = context;
  11606. let consequentBrokenFlow = false;
  11607. if (this.consequent.shouldBeIncluded(context)) {
  11608. this.consequent.include(context, false, { asSingleStatement: true });
  11609. // eslint-disable-next-line unicorn/consistent-destructuring
  11610. consequentBrokenFlow = context.brokenFlow;
  11611. context.brokenFlow = brokenFlow;
  11612. }
  11613. if (this.alternate?.shouldBeIncluded(context)) {
  11614. this.alternate.include(context, false, { asSingleStatement: true });
  11615. // eslint-disable-next-line unicorn/consistent-destructuring
  11616. context.brokenFlow = context.brokenFlow && consequentBrokenFlow;
  11617. }
  11618. }
  11619. renderHoistedDeclarations(hoistedDeclarations, code, getPropertyAccess) {
  11620. const hoistedVariables = [
  11621. ...new Set(hoistedDeclarations.map(identifier => {
  11622. const variable = identifier.variable;
  11623. return variable.included ? variable.getName(getPropertyAccess) : '';
  11624. }))
  11625. ]
  11626. .filter(Boolean)
  11627. .join(', ');
  11628. if (hoistedVariables) {
  11629. const parentType = this.parent.type;
  11630. const needsBraces = parentType !== Program$1 && parentType !== BlockStatement$1;
  11631. code.prependRight(this.start, `${needsBraces ? '{ ' : ''}var ${hoistedVariables}; `);
  11632. if (needsBraces) {
  11633. code.appendLeft(this.end, ` }`);
  11634. }
  11635. }
  11636. }
  11637. shouldKeepAlternateBranch() {
  11638. let currentParent = this.parent;
  11639. do {
  11640. if (currentParent instanceof IfStatement && currentParent.alternate) {
  11641. return true;
  11642. }
  11643. if (currentParent instanceof BlockStatement) {
  11644. return false;
  11645. }
  11646. currentParent = currentParent.parent;
  11647. } while (currentParent);
  11648. return false;
  11649. }
  11650. }
  11651. class ImportAttribute extends NodeBase {
  11652. }
  11653. class ImportDeclaration extends NodeBase {
  11654. // Do not bind specifiers or assertions
  11655. bind() { }
  11656. hasEffects() {
  11657. return false;
  11658. }
  11659. initialise() {
  11660. this.context.addImport(this);
  11661. }
  11662. render(code, _options, nodeRenderOptions) {
  11663. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  11664. }
  11665. applyDeoptimizations() { }
  11666. }
  11667. ImportDeclaration.prototype.needsBoundaries = true;
  11668. class ImportDefaultSpecifier extends NodeBase {
  11669. applyDeoptimizations() { }
  11670. }
  11671. const INTEROP_DEFAULT_VARIABLE = '_interopDefault';
  11672. const INTEROP_DEFAULT_COMPAT_VARIABLE = '_interopDefaultCompat';
  11673. const INTEROP_NAMESPACE_VARIABLE = '_interopNamespace';
  11674. const INTEROP_NAMESPACE_COMPAT_VARIABLE = '_interopNamespaceCompat';
  11675. const INTEROP_NAMESPACE_DEFAULT_VARIABLE = '_interopNamespaceDefault';
  11676. const INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE = '_interopNamespaceDefaultOnly';
  11677. const MERGE_NAMESPACES_VARIABLE = '_mergeNamespaces';
  11678. const DOCUMENT_CURRENT_SCRIPT = '_documentCurrentScript';
  11679. const defaultInteropHelpersByInteropType = {
  11680. auto: INTEROP_DEFAULT_VARIABLE,
  11681. compat: INTEROP_DEFAULT_COMPAT_VARIABLE,
  11682. default: null,
  11683. defaultOnly: null,
  11684. esModule: null
  11685. };
  11686. const isDefaultAProperty = (interopType, externalLiveBindings) => interopType === 'esModule' ||
  11687. (externalLiveBindings && (interopType === 'auto' || interopType === 'compat'));
  11688. const namespaceInteropHelpersByInteropType = {
  11689. auto: INTEROP_NAMESPACE_VARIABLE,
  11690. compat: INTEROP_NAMESPACE_COMPAT_VARIABLE,
  11691. default: INTEROP_NAMESPACE_DEFAULT_VARIABLE,
  11692. defaultOnly: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE,
  11693. esModule: null
  11694. };
  11695. const canDefaultBeTakenFromNamespace = (interopType, externalLiveBindings) => interopType !== 'esModule' && isDefaultAProperty(interopType, externalLiveBindings);
  11696. const getHelpersBlock = (additionalHelpers, accessedGlobals, indent, snippets, liveBindings, freeze, namespaceToStringTag) => {
  11697. const usedHelpers = new Set(additionalHelpers);
  11698. for (const variable of HELPER_NAMES) {
  11699. if (accessedGlobals.has(variable)) {
  11700. usedHelpers.add(variable);
  11701. }
  11702. }
  11703. return HELPER_NAMES.map(variable => usedHelpers.has(variable)
  11704. ? HELPER_GENERATORS[variable](indent, snippets, liveBindings, freeze, namespaceToStringTag, usedHelpers)
  11705. : '').join('');
  11706. };
  11707. const HELPER_GENERATORS = {
  11708. [DOCUMENT_CURRENT_SCRIPT](_t, { _, n }) {
  11709. return `var${_}${DOCUMENT_CURRENT_SCRIPT}${_}=${_}typeof${_}document${_}!==${_}'undefined'${_}?${_}document.currentScript${_}:${_}null;${n}`;
  11710. },
  11711. [INTEROP_DEFAULT_COMPAT_VARIABLE](_t, snippets, liveBindings) {
  11712. const { _, getDirectReturnFunction, n } = snippets;
  11713. const [left, right] = getDirectReturnFunction(['e'], {
  11714. functionReturn: true,
  11715. lineBreakIndent: null,
  11716. name: INTEROP_DEFAULT_COMPAT_VARIABLE
  11717. });
  11718. return (`${left}${getIsCompatNamespace(snippets)}${_}?${_}` +
  11719. `${liveBindings ? getDefaultLiveBinding(snippets) : getDefaultStatic(snippets)}${right}${n}${n}`);
  11720. },
  11721. [INTEROP_DEFAULT_VARIABLE](_t, snippets, liveBindings) {
  11722. const { _, getDirectReturnFunction, n } = snippets;
  11723. const [left, right] = getDirectReturnFunction(['e'], {
  11724. functionReturn: true,
  11725. lineBreakIndent: null,
  11726. name: INTEROP_DEFAULT_VARIABLE
  11727. });
  11728. return (`${left}e${_}&&${_}e.__esModule${_}?${_}` +
  11729. `${liveBindings ? getDefaultLiveBinding(snippets) : getDefaultStatic(snippets)}${right}${n}${n}`);
  11730. },
  11731. [INTEROP_NAMESPACE_COMPAT_VARIABLE](t, snippets, liveBindings, freeze, namespaceToStringTag, usedHelpers) {
  11732. const { _, getDirectReturnFunction, n } = snippets;
  11733. if (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)) {
  11734. const [left, right] = getDirectReturnFunction(['e'], {
  11735. functionReturn: true,
  11736. lineBreakIndent: null,
  11737. name: INTEROP_NAMESPACE_COMPAT_VARIABLE
  11738. });
  11739. return `${left}${getIsCompatNamespace(snippets)}${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${right}${n}${n}`;
  11740. }
  11741. return (`function ${INTEROP_NAMESPACE_COMPAT_VARIABLE}(e)${_}{${n}` +
  11742. `${t}if${_}(${getIsCompatNamespace(snippets)})${_}return e;${n}` +
  11743. createNamespaceObject(t, t, snippets, liveBindings, freeze, namespaceToStringTag) +
  11744. `}${n}${n}`);
  11745. },
  11746. [INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE](_t, snippets, _liveBindings, freeze, namespaceToStringTag) {
  11747. const { getDirectReturnFunction, getObject, n } = snippets;
  11748. const [left, right] = getDirectReturnFunction(['e'], {
  11749. functionReturn: true,
  11750. lineBreakIndent: null,
  11751. name: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE
  11752. });
  11753. return `${left}${getFrozen(freeze, getWithToStringTag(namespaceToStringTag, getObject([
  11754. ['__proto__', 'null'],
  11755. ['default', 'e']
  11756. ], { lineBreakIndent: null }), snippets))}${right}${n}${n}`;
  11757. },
  11758. [INTEROP_NAMESPACE_DEFAULT_VARIABLE](t, snippets, liveBindings, freeze, namespaceToStringTag) {
  11759. const { _, n } = snippets;
  11760. return (`function ${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${_}{${n}` +
  11761. createNamespaceObject(t, t, snippets, liveBindings, freeze, namespaceToStringTag) +
  11762. `}${n}${n}`);
  11763. },
  11764. [INTEROP_NAMESPACE_VARIABLE](t, snippets, liveBindings, freeze, namespaceToStringTag, usedHelpers) {
  11765. const { _, getDirectReturnFunction, n } = snippets;
  11766. if (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)) {
  11767. const [left, right] = getDirectReturnFunction(['e'], {
  11768. functionReturn: true,
  11769. lineBreakIndent: null,
  11770. name: INTEROP_NAMESPACE_VARIABLE
  11771. });
  11772. return `${left}e${_}&&${_}e.__esModule${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${right}${n}${n}`;
  11773. }
  11774. return (`function ${INTEROP_NAMESPACE_VARIABLE}(e)${_}{${n}` +
  11775. `${t}if${_}(e${_}&&${_}e.__esModule)${_}return e;${n}` +
  11776. createNamespaceObject(t, t, snippets, liveBindings, freeze, namespaceToStringTag) +
  11777. `}${n}${n}`);
  11778. },
  11779. [MERGE_NAMESPACES_VARIABLE](t, snippets, liveBindings, freeze, namespaceToStringTag) {
  11780. const { _, cnst, n } = snippets;
  11781. const useForEach = cnst === 'var' && liveBindings;
  11782. return (`function ${MERGE_NAMESPACES_VARIABLE}(n, m)${_}{${n}` +
  11783. `${t}${loopOverNamespaces(`{${n}` +
  11784. `${t}${t}${t}if${_}(k${_}!==${_}'default'${_}&&${_}!(k in n))${_}{${n}` +
  11785. (liveBindings
  11786. ? useForEach
  11787. ? copyOwnPropertyLiveBinding
  11788. : copyPropertyLiveBinding
  11789. : copyPropertyStatic)(t, t + t + t + t, snippets) +
  11790. `${t}${t}${t}}${n}` +
  11791. `${t}${t}}`, useForEach, t, snippets)}${n}` +
  11792. `${t}return ${getFrozen(freeze, getWithToStringTag(namespaceToStringTag, 'n', snippets))};${n}` +
  11793. `}${n}${n}`);
  11794. }
  11795. };
  11796. const getDefaultLiveBinding = ({ _, getObject }) => `e${_}:${_}${getObject([['default', 'e']], { lineBreakIndent: null })}`;
  11797. const getDefaultStatic = ({ _, getPropertyAccess }) => `e${getPropertyAccess('default')}${_}:${_}e`;
  11798. const getIsCompatNamespace = ({ _ }) => `e${_}&&${_}typeof e${_}===${_}'object'${_}&&${_}'default'${_}in e`;
  11799. const createNamespaceObject = (t, index, snippets, liveBindings, freeze, namespaceToStringTag) => {
  11800. const { _, cnst, getObject, getPropertyAccess, n, s } = snippets;
  11801. const copyProperty = `{${n}` +
  11802. (liveBindings ? copyNonDefaultOwnPropertyLiveBinding : copyPropertyStatic)(t, index + t + t, snippets) +
  11803. `${index}${t}}`;
  11804. return (`${index}${cnst} n${_}=${_}Object.create(null${namespaceToStringTag
  11805. ? `,${_}{${_}[Symbol.toStringTag]:${_}${getToStringTagValue(getObject)}${_}}`
  11806. : ''});${n}` +
  11807. `${index}if${_}(e)${_}{${n}` +
  11808. `${index}${t}${loopOverKeys(copyProperty, !liveBindings, snippets)}${n}` +
  11809. `${index}}${n}` +
  11810. `${index}n${getPropertyAccess('default')}${_}=${_}e;${n}` +
  11811. `${index}return ${getFrozen(freeze, 'n')}${s}${n}`);
  11812. };
  11813. const loopOverKeys = (body, allowVariableLoopVariable, { _, cnst, getFunctionIntro, s }) => cnst !== 'var' || allowVariableLoopVariable
  11814. ? `for${_}(${cnst} k in e)${_}${body}`
  11815. : `Object.keys(e).forEach(${getFunctionIntro(['k'], {
  11816. isAsync: false,
  11817. name: null
  11818. })}${body})${s}`;
  11819. const loopOverNamespaces = (body, useForEach, t, { _, cnst, getDirectReturnFunction, getFunctionIntro, n }) => {
  11820. if (useForEach) {
  11821. const [left, right] = getDirectReturnFunction(['e'], {
  11822. functionReturn: false,
  11823. lineBreakIndent: { base: t, t },
  11824. name: null
  11825. });
  11826. return (`m.forEach(${left}` +
  11827. `e${_}&&${_}typeof e${_}!==${_}'string'${_}&&${_}!Array.isArray(e)${_}&&${_}Object.keys(e).forEach(${getFunctionIntro(['k'], {
  11828. isAsync: false,
  11829. name: null
  11830. })}${body})${right});`);
  11831. }
  11832. return (`for${_}(var i${_}=${_}0;${_}i${_}<${_}m.length;${_}i++)${_}{${n}` +
  11833. `${t}${t}${cnst} e${_}=${_}m[i];${n}` +
  11834. `${t}${t}if${_}(typeof e${_}!==${_}'string'${_}&&${_}!Array.isArray(e))${_}{${_}for${_}(${cnst} k in e)${_}${body}${_}}${n}${t}}`);
  11835. };
  11836. const copyNonDefaultOwnPropertyLiveBinding = (t, index, snippets) => {
  11837. const { _, n } = snippets;
  11838. return (`${index}if${_}(k${_}!==${_}'default')${_}{${n}` +
  11839. copyOwnPropertyLiveBinding(t, index + t, snippets) +
  11840. `${index}}${n}`);
  11841. };
  11842. const copyOwnPropertyLiveBinding = (t, index, { _, cnst, getDirectReturnFunction, n }) => {
  11843. const [left, right] = getDirectReturnFunction([], {
  11844. functionReturn: true,
  11845. lineBreakIndent: null,
  11846. name: null
  11847. });
  11848. return (`${index}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
  11849. `${index}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
  11850. `${index}${t}enumerable:${_}true,${n}` +
  11851. `${index}${t}get:${_}${left}e[k]${right}${n}` +
  11852. `${index}});${n}`);
  11853. };
  11854. const copyPropertyLiveBinding = (t, index, { _, cnst, getDirectReturnFunction, n }) => {
  11855. const [left, right] = getDirectReturnFunction([], {
  11856. functionReturn: true,
  11857. lineBreakIndent: null,
  11858. name: null
  11859. });
  11860. return (`${index}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
  11861. `${index}if${_}(d)${_}{${n}` +
  11862. `${index}${t}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
  11863. `${index}${t}${t}enumerable:${_}true,${n}` +
  11864. `${index}${t}${t}get:${_}${left}e[k]${right}${n}` +
  11865. `${index}${t}});${n}` +
  11866. `${index}}${n}`);
  11867. };
  11868. const copyPropertyStatic = (_t, index, { _, n }) => `${index}n[k]${_}=${_}e[k];${n}`;
  11869. const getFrozen = (freeze, fragment) => freeze ? `Object.freeze(${fragment})` : fragment;
  11870. const getWithToStringTag = (namespaceToStringTag, fragment, { _, getObject }) => namespaceToStringTag
  11871. ? `Object.defineProperty(${fragment},${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)})`
  11872. : fragment;
  11873. const HELPER_NAMES = Object.keys(HELPER_GENERATORS);
  11874. function getToStringTagValue(getObject) {
  11875. return getObject([['value', "'Module'"]], {
  11876. lineBreakIndent: null
  11877. });
  11878. }
  11879. function isReassignedExportsMember(variable, exportNamesByVariable) {
  11880. return (variable.renderBaseName !== null && exportNamesByVariable.has(variable) && variable.isReassigned);
  11881. }
  11882. class VariableDeclarator extends NodeBase {
  11883. declareDeclarator(kind) {
  11884. this.id.declare(kind, this.init || UNDEFINED_EXPRESSION);
  11885. }
  11886. deoptimizePath(path) {
  11887. this.id.deoptimizePath(path);
  11888. }
  11889. hasEffects(context) {
  11890. if (!this.deoptimized)
  11891. this.applyDeoptimizations();
  11892. const initEffect = this.init?.hasEffects(context);
  11893. this.id.markDeclarationReached();
  11894. return initEffect || this.id.hasEffects(context);
  11895. }
  11896. include(context, includeChildrenRecursively) {
  11897. const { deoptimized, id, init } = this;
  11898. if (!deoptimized)
  11899. this.applyDeoptimizations();
  11900. this.included = true;
  11901. init?.include(context, includeChildrenRecursively);
  11902. id.markDeclarationReached();
  11903. if (includeChildrenRecursively || id.shouldBeIncluded(context)) {
  11904. id.include(context, includeChildrenRecursively);
  11905. }
  11906. }
  11907. render(code, options) {
  11908. const { exportNamesByVariable, snippets: { _, getPropertyAccess } } = options;
  11909. const { end, id, init, start } = this;
  11910. const renderId = id.included;
  11911. if (renderId) {
  11912. id.render(code, options);
  11913. }
  11914. else {
  11915. const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', id.end);
  11916. code.remove(start, findNonWhiteSpace(code.original, operatorPos + 1));
  11917. }
  11918. if (init) {
  11919. if (id instanceof Identifier && init instanceof ClassExpression && !init.id) {
  11920. const renderedVariable = id.variable.getName(getPropertyAccess);
  11921. if (renderedVariable !== id.name) {
  11922. code.appendLeft(init.start + 5, ` ${id.name}`);
  11923. }
  11924. }
  11925. init.render(code, options, renderId ? BLANK : { renderedSurroundingElement: ExpressionStatement$1 });
  11926. }
  11927. else if (id instanceof Identifier &&
  11928. isReassignedExportsMember(id.variable, exportNamesByVariable)) {
  11929. code.appendLeft(end, `${_}=${_}void 0`);
  11930. }
  11931. }
  11932. applyDeoptimizations() {
  11933. this.deoptimized = true;
  11934. const { id, init } = this;
  11935. if (init && id instanceof Identifier && init instanceof ClassExpression && !init.id) {
  11936. const { name, variable } = id;
  11937. for (const accessedVariable of init.scope.accessedOutsideVariables.values()) {
  11938. if (accessedVariable !== variable) {
  11939. accessedVariable.forbidName(name);
  11940. }
  11941. }
  11942. }
  11943. }
  11944. }
  11945. // TODO once ImportExpression follows official ESTree specs with "null" as
  11946. // default, keys.ts should be updated
  11947. class ImportExpression extends NodeBase {
  11948. constructor() {
  11949. super(...arguments);
  11950. this.inlineNamespace = null;
  11951. this.assertions = null;
  11952. this.mechanism = null;
  11953. this.namespaceExportName = undefined;
  11954. this.resolution = null;
  11955. this.resolutionString = null;
  11956. }
  11957. // Do not bind assertions
  11958. bind() {
  11959. this.source.bind();
  11960. }
  11961. /**
  11962. * Get imported variables for deterministic usage, valid cases are:
  11963. *
  11964. * - `const { foo } = await import('bar')`.
  11965. * - `(await import('bar')).foo`
  11966. * - `import('bar').then(({ foo }) => {})`
  11967. *
  11968. * Returns empty array if it's side-effect only import.
  11969. * Returns undefined if it's not fully deterministic.
  11970. */
  11971. getDeterministicImportedNames() {
  11972. const parent1 = this.parent;
  11973. // Side-effect only: import('bar')
  11974. if (parent1 instanceof ExpressionStatement) {
  11975. return EMPTY_ARRAY;
  11976. }
  11977. if (parent1 instanceof AwaitExpression) {
  11978. const parent2 = parent1.parent;
  11979. // Side-effect only: await import('bar')
  11980. if (parent2 instanceof ExpressionStatement) {
  11981. return EMPTY_ARRAY;
  11982. }
  11983. // Case 1: const { foo } = await import('bar')
  11984. if (parent2 instanceof VariableDeclarator) {
  11985. const declaration = parent2.id;
  11986. return declaration instanceof ObjectPattern
  11987. ? getDeterministicObjectDestructure(declaration)
  11988. : undefined;
  11989. }
  11990. // Case 2: (await import('bar')).foo
  11991. if (parent2 instanceof MemberExpression) {
  11992. const id = parent2.property;
  11993. if (!parent2.computed && id instanceof Identifier) {
  11994. return [id.name];
  11995. }
  11996. }
  11997. return;
  11998. }
  11999. // Case 3: import('bar').then(({ foo }) => {})
  12000. if (parent1 instanceof MemberExpression) {
  12001. const callExpression = parent1.parent;
  12002. const property = parent1.property;
  12003. if (!(callExpression instanceof CallExpression) || !(property instanceof Identifier)) {
  12004. return;
  12005. }
  12006. const memberName = property.name;
  12007. // side-effect only, when only chaining .catch or .finally
  12008. if (callExpression.parent instanceof ExpressionStatement &&
  12009. ['catch', 'finally'].includes(memberName)) {
  12010. return EMPTY_ARRAY;
  12011. }
  12012. if (memberName !== 'then')
  12013. return;
  12014. // Side-effect only: import('bar').then()
  12015. if (callExpression.arguments.length === 0) {
  12016. return EMPTY_ARRAY;
  12017. }
  12018. const argument = callExpression.arguments[0];
  12019. if (callExpression.arguments.length !== 1 ||
  12020. !(argument instanceof ArrowFunctionExpression || argument instanceof FunctionExpression)) {
  12021. return;
  12022. }
  12023. // Side-effect only: import('bar').then(() => {})
  12024. if (argument.params.length === 0) {
  12025. return EMPTY_ARRAY;
  12026. }
  12027. const declaration = argument.params[0];
  12028. if (argument.params.length === 1 && declaration instanceof ObjectPattern) {
  12029. return getDeterministicObjectDestructure(declaration);
  12030. }
  12031. return;
  12032. }
  12033. }
  12034. hasEffects() {
  12035. return true;
  12036. }
  12037. include(context, includeChildrenRecursively) {
  12038. if (!this.included) {
  12039. this.included = true;
  12040. this.context.includeDynamicImport(this);
  12041. this.scope.addAccessedDynamicImport(this);
  12042. }
  12043. this.source.include(context, includeChildrenRecursively);
  12044. }
  12045. initialise() {
  12046. this.context.addDynamicImport(this);
  12047. }
  12048. parseNode(esTreeNode) {
  12049. // Keep the source AST to be used by renderDynamicImport
  12050. super.parseNode(esTreeNode, ['source']);
  12051. }
  12052. render(code, options) {
  12053. const { snippets: { _, getDirectReturnFunction, getObject, getPropertyAccess } } = options;
  12054. if (this.inlineNamespace) {
  12055. const [left, right] = getDirectReturnFunction([], {
  12056. functionReturn: true,
  12057. lineBreakIndent: null,
  12058. name: null
  12059. });
  12060. code.overwrite(this.start, this.end, `Promise.resolve().then(${left}${this.inlineNamespace.getName(getPropertyAccess)}${right})`);
  12061. return;
  12062. }
  12063. if (this.mechanism) {
  12064. code.overwrite(this.start, findFirstOccurrenceOutsideComment(code.original, '(', this.start + 6) + 1, this.mechanism.left);
  12065. code.overwrite(this.end - 1, this.end, this.mechanism.right);
  12066. }
  12067. if (this.resolutionString) {
  12068. code.overwrite(this.source.start, this.source.end, this.resolutionString);
  12069. if (this.namespaceExportName) {
  12070. const [left, right] = getDirectReturnFunction(['n'], {
  12071. functionReturn: true,
  12072. lineBreakIndent: null,
  12073. name: null
  12074. });
  12075. code.prependLeft(this.end, `.then(${left}n.${this.namespaceExportName}${right})`);
  12076. }
  12077. }
  12078. else {
  12079. this.source.render(code, options);
  12080. }
  12081. if (this.assertions !== true) {
  12082. if (this.arguments) {
  12083. code.overwrite(this.source.end, this.end - 1, '', { contentOnly: true });
  12084. }
  12085. if (this.assertions) {
  12086. code.appendLeft(this.end - 1, `,${_}${getObject([['assert', this.assertions]], {
  12087. lineBreakIndent: null
  12088. })}`);
  12089. }
  12090. }
  12091. }
  12092. setExternalResolution(exportMode, resolution, options, snippets, pluginDriver, accessedGlobalsByScope, resolutionString, namespaceExportName, assertions) {
  12093. const { format } = options;
  12094. this.inlineNamespace = null;
  12095. this.resolution = resolution;
  12096. this.resolutionString = resolutionString;
  12097. this.namespaceExportName = namespaceExportName;
  12098. this.assertions = assertions;
  12099. const accessedGlobals = [...(accessedImportGlobals[format] || [])];
  12100. let helper;
  12101. ({ helper, mechanism: this.mechanism } = this.getDynamicImportMechanismAndHelper(resolution, exportMode, options, snippets, pluginDriver));
  12102. if (helper) {
  12103. accessedGlobals.push(helper);
  12104. }
  12105. if (accessedGlobals.length > 0) {
  12106. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  12107. }
  12108. }
  12109. setInternalResolution(inlineNamespace) {
  12110. this.inlineNamespace = inlineNamespace;
  12111. }
  12112. applyDeoptimizations() { }
  12113. getDynamicImportMechanismAndHelper(resolution, exportMode, { compact, dynamicImportFunction, dynamicImportInCjs, format, generatedCode: { arrowFunctions }, interop }, { _, getDirectReturnFunction, getDirectReturnIifeLeft }, pluginDriver) {
  12114. const mechanism = pluginDriver.hookFirstSync('renderDynamicImport', [
  12115. {
  12116. customResolution: typeof this.resolution === 'string' ? this.resolution : null,
  12117. format,
  12118. moduleId: this.context.module.id,
  12119. targetModuleId: this.resolution && typeof this.resolution !== 'string' ? this.resolution.id : null
  12120. }
  12121. ]);
  12122. if (mechanism) {
  12123. return { helper: null, mechanism };
  12124. }
  12125. const hasDynamicTarget = !this.resolution || typeof this.resolution === 'string';
  12126. switch (format) {
  12127. case 'cjs': {
  12128. if (dynamicImportInCjs &&
  12129. (!resolution || typeof resolution === 'string' || resolution instanceof ExternalModule)) {
  12130. return { helper: null, mechanism: null };
  12131. }
  12132. const helper = getInteropHelper(resolution, exportMode, interop);
  12133. let left = `require(`;
  12134. let right = `)`;
  12135. if (helper) {
  12136. left = `/*#__PURE__*/${helper}(${left}`;
  12137. right += ')';
  12138. }
  12139. const [functionLeft, functionRight] = getDirectReturnFunction([], {
  12140. functionReturn: true,
  12141. lineBreakIndent: null,
  12142. name: null
  12143. });
  12144. left = `Promise.resolve().then(${functionLeft}${left}`;
  12145. right += `${functionRight})`;
  12146. if (!arrowFunctions && hasDynamicTarget) {
  12147. left = getDirectReturnIifeLeft(['t'], `${left}t${right}`, {
  12148. needsArrowReturnParens: false,
  12149. needsWrappedFunction: true
  12150. });
  12151. right = ')';
  12152. }
  12153. return {
  12154. helper,
  12155. mechanism: { left, right }
  12156. };
  12157. }
  12158. case 'amd': {
  12159. const resolve = compact ? 'c' : 'resolve';
  12160. const reject = compact ? 'e' : 'reject';
  12161. const helper = getInteropHelper(resolution, exportMode, interop);
  12162. const [resolveLeft, resolveRight] = getDirectReturnFunction(['m'], {
  12163. functionReturn: false,
  12164. lineBreakIndent: null,
  12165. name: null
  12166. });
  12167. const resolveNamespace = helper
  12168. ? `${resolveLeft}${resolve}(/*#__PURE__*/${helper}(m))${resolveRight}`
  12169. : resolve;
  12170. const [handlerLeft, handlerRight] = getDirectReturnFunction([resolve, reject], {
  12171. functionReturn: false,
  12172. lineBreakIndent: null,
  12173. name: null
  12174. });
  12175. let left = `new Promise(${handlerLeft}require([`;
  12176. let right = `],${_}${resolveNamespace},${_}${reject})${handlerRight})`;
  12177. if (!arrowFunctions && hasDynamicTarget) {
  12178. left = getDirectReturnIifeLeft(['t'], `${left}t${right}`, {
  12179. needsArrowReturnParens: false,
  12180. needsWrappedFunction: true
  12181. });
  12182. right = ')';
  12183. }
  12184. return {
  12185. helper,
  12186. mechanism: { left, right }
  12187. };
  12188. }
  12189. case 'system': {
  12190. return {
  12191. helper: null,
  12192. mechanism: {
  12193. left: 'module.import(',
  12194. right: ')'
  12195. }
  12196. };
  12197. }
  12198. case 'es': {
  12199. if (dynamicImportFunction) {
  12200. return {
  12201. helper: null,
  12202. mechanism: {
  12203. left: `${dynamicImportFunction}(`,
  12204. right: ')'
  12205. }
  12206. };
  12207. }
  12208. }
  12209. }
  12210. return { helper: null, mechanism: null };
  12211. }
  12212. }
  12213. function getInteropHelper(resolution, exportMode, interop) {
  12214. return exportMode === 'external'
  12215. ? namespaceInteropHelpersByInteropType[interop(resolution instanceof ExternalModule ? resolution.id : null)]
  12216. : exportMode === 'default'
  12217. ? INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE
  12218. : null;
  12219. }
  12220. const accessedImportGlobals = {
  12221. amd: ['require'],
  12222. cjs: ['require'],
  12223. system: ['module']
  12224. };
  12225. function getDeterministicObjectDestructure(objectPattern) {
  12226. const variables = [];
  12227. for (const property of objectPattern.properties) {
  12228. if (property.type === 'RestElement' || property.computed || property.key.type !== 'Identifier')
  12229. return;
  12230. variables.push(property.key.name);
  12231. }
  12232. return variables;
  12233. }
  12234. class ImportNamespaceSpecifier extends NodeBase {
  12235. applyDeoptimizations() { }
  12236. }
  12237. class ImportSpecifier extends NodeBase {
  12238. applyDeoptimizations() { }
  12239. }
  12240. class LabeledStatement extends NodeBase {
  12241. hasEffects(context) {
  12242. const brokenFlow = context.brokenFlow;
  12243. context.ignore.labels.add(this.label.name);
  12244. if (this.body.hasEffects(context))
  12245. return true;
  12246. context.ignore.labels.delete(this.label.name);
  12247. if (context.includedLabels.has(this.label.name)) {
  12248. context.includedLabels.delete(this.label.name);
  12249. context.brokenFlow = brokenFlow;
  12250. }
  12251. return false;
  12252. }
  12253. include(context, includeChildrenRecursively) {
  12254. this.included = true;
  12255. const brokenFlow = context.brokenFlow;
  12256. this.body.include(context, includeChildrenRecursively);
  12257. if (includeChildrenRecursively || context.includedLabels.has(this.label.name)) {
  12258. this.label.include();
  12259. context.includedLabels.delete(this.label.name);
  12260. context.brokenFlow = brokenFlow;
  12261. }
  12262. }
  12263. render(code, options) {
  12264. if (this.label.included) {
  12265. this.label.render(code, options);
  12266. }
  12267. else {
  12268. code.remove(this.start, findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, ':', this.label.end) + 1));
  12269. }
  12270. this.body.render(code, options);
  12271. }
  12272. }
  12273. class LogicalExpression extends NodeBase {
  12274. constructor() {
  12275. super(...arguments);
  12276. // We collect deoptimization information if usedBranch !== null
  12277. this.expressionsToBeDeoptimized = [];
  12278. this.isBranchResolutionAnalysed = false;
  12279. this.usedBranch = null;
  12280. }
  12281. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  12282. this.left.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  12283. this.right.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  12284. }
  12285. deoptimizeCache() {
  12286. if (this.usedBranch) {
  12287. const unusedBranch = this.usedBranch === this.left ? this.right : this.left;
  12288. this.usedBranch = null;
  12289. unusedBranch.deoptimizePath(UNKNOWN_PATH);
  12290. const { context, expressionsToBeDeoptimized } = this;
  12291. this.expressionsToBeDeoptimized = EMPTY_ARRAY;
  12292. for (const expression of expressionsToBeDeoptimized) {
  12293. expression.deoptimizeCache();
  12294. }
  12295. // Request another pass because we need to ensure "include" runs again if
  12296. // it is rendered
  12297. context.requestTreeshakingPass();
  12298. }
  12299. }
  12300. deoptimizePath(path) {
  12301. const usedBranch = this.getUsedBranch();
  12302. if (usedBranch) {
  12303. usedBranch.deoptimizePath(path);
  12304. }
  12305. else {
  12306. this.left.deoptimizePath(path);
  12307. this.right.deoptimizePath(path);
  12308. }
  12309. }
  12310. getLiteralValueAtPath(path, recursionTracker, origin) {
  12311. const usedBranch = this.getUsedBranch();
  12312. if (!usedBranch)
  12313. return UnknownValue;
  12314. this.expressionsToBeDeoptimized.push(origin);
  12315. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  12316. }
  12317. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  12318. const usedBranch = this.getUsedBranch();
  12319. if (!usedBranch)
  12320. return [
  12321. new MultiExpression([
  12322. this.left.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0],
  12323. this.right.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0]
  12324. ]),
  12325. false
  12326. ];
  12327. this.expressionsToBeDeoptimized.push(origin);
  12328. return usedBranch.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  12329. }
  12330. hasEffects(context) {
  12331. if (this.left.hasEffects(context)) {
  12332. return true;
  12333. }
  12334. if (this.getUsedBranch() !== this.left) {
  12335. return this.right.hasEffects(context);
  12336. }
  12337. return false;
  12338. }
  12339. hasEffectsOnInteractionAtPath(path, interaction, context) {
  12340. const usedBranch = this.getUsedBranch();
  12341. if (!usedBranch) {
  12342. return (this.left.hasEffectsOnInteractionAtPath(path, interaction, context) ||
  12343. this.right.hasEffectsOnInteractionAtPath(path, interaction, context));
  12344. }
  12345. return usedBranch.hasEffectsOnInteractionAtPath(path, interaction, context);
  12346. }
  12347. include(context, includeChildrenRecursively) {
  12348. this.included = true;
  12349. const usedBranch = this.getUsedBranch();
  12350. if (includeChildrenRecursively ||
  12351. (usedBranch === this.right && this.left.shouldBeIncluded(context)) ||
  12352. !usedBranch) {
  12353. this.left.include(context, includeChildrenRecursively);
  12354. this.right.include(context, includeChildrenRecursively);
  12355. }
  12356. else {
  12357. usedBranch.include(context, includeChildrenRecursively);
  12358. }
  12359. }
  12360. render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  12361. if (!this.left.included || !this.right.included) {
  12362. const operatorPos = findFirstOccurrenceOutsideComment(code.original, this.operator, this.left.end);
  12363. if (this.right.included) {
  12364. const removePos = findNonWhiteSpace(code.original, operatorPos + 2);
  12365. code.remove(this.start, removePos);
  12366. if (preventASI) {
  12367. removeLineBreaks(code, removePos, this.right.start);
  12368. }
  12369. }
  12370. else {
  12371. code.remove(operatorPos, this.end);
  12372. }
  12373. removeAnnotations(this, code);
  12374. this.getUsedBranch().render(code, options, {
  12375. isCalleeOfRenderedParent,
  12376. preventASI,
  12377. renderedParentType: renderedParentType || this.parent.type,
  12378. renderedSurroundingElement: renderedSurroundingElement || this.parent.type
  12379. });
  12380. }
  12381. else {
  12382. this.left.render(code, options, {
  12383. preventASI,
  12384. renderedSurroundingElement
  12385. });
  12386. this.right.render(code, options);
  12387. }
  12388. }
  12389. getUsedBranch() {
  12390. if (!this.isBranchResolutionAnalysed) {
  12391. this.isBranchResolutionAnalysed = true;
  12392. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  12393. if (typeof leftValue === 'symbol') {
  12394. return null;
  12395. }
  12396. else {
  12397. this.usedBranch =
  12398. (this.operator === '||' && leftValue) ||
  12399. (this.operator === '&&' && !leftValue) ||
  12400. (this.operator === '??' && leftValue != null)
  12401. ? this.left
  12402. : this.right;
  12403. }
  12404. }
  12405. return this.usedBranch;
  12406. }
  12407. }
  12408. const FILE_PREFIX = 'ROLLUP_FILE_URL_';
  12409. const IMPORT = 'import';
  12410. class MetaProperty extends NodeBase {
  12411. constructor() {
  12412. super(...arguments);
  12413. this.metaProperty = null;
  12414. this.preliminaryChunkId = null;
  12415. this.referenceId = null;
  12416. }
  12417. getReferencedFileName(outputPluginDriver) {
  12418. const { meta: { name }, metaProperty } = this;
  12419. if (name === IMPORT && metaProperty?.startsWith(FILE_PREFIX)) {
  12420. return outputPluginDriver.getFileName(metaProperty.slice(FILE_PREFIX.length));
  12421. }
  12422. return null;
  12423. }
  12424. hasEffects() {
  12425. return false;
  12426. }
  12427. hasEffectsOnInteractionAtPath(path, { type }) {
  12428. return path.length > 1 || type !== INTERACTION_ACCESSED;
  12429. }
  12430. include() {
  12431. if (!this.included) {
  12432. this.included = true;
  12433. if (this.meta.name === IMPORT) {
  12434. this.context.addImportMeta(this);
  12435. const parent = this.parent;
  12436. const metaProperty = (this.metaProperty =
  12437. parent instanceof MemberExpression && typeof parent.propertyKey === 'string'
  12438. ? parent.propertyKey
  12439. : null);
  12440. if (metaProperty?.startsWith(FILE_PREFIX)) {
  12441. this.referenceId = metaProperty.slice(FILE_PREFIX.length);
  12442. }
  12443. }
  12444. }
  12445. }
  12446. render(code, renderOptions) {
  12447. const { format, pluginDriver, snippets } = renderOptions;
  12448. const { context: { module }, meta: { name }, metaProperty, parent, preliminaryChunkId, referenceId, start, end } = this;
  12449. const { id: moduleId } = module;
  12450. if (name !== IMPORT)
  12451. return;
  12452. const chunkId = preliminaryChunkId;
  12453. if (referenceId) {
  12454. const fileName = pluginDriver.getFileName(referenceId);
  12455. const relativePath = normalize(node_path.relative(node_path.dirname(chunkId), fileName));
  12456. const replacement = pluginDriver.hookFirstSync('resolveFileUrl', [
  12457. { chunkId, fileName, format, moduleId, referenceId, relativePath }
  12458. ]) || relativeUrlMechanisms[format](relativePath);
  12459. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  12460. return;
  12461. }
  12462. let replacement = pluginDriver.hookFirstSync('resolveImportMeta', [
  12463. metaProperty,
  12464. { chunkId, format, moduleId }
  12465. ]);
  12466. if (!replacement) {
  12467. replacement = importMetaMechanisms[format]?.(metaProperty, { chunkId, snippets });
  12468. renderOptions.accessedDocumentCurrentScript || (renderOptions.accessedDocumentCurrentScript = formatsMaybeAccessDocumentCurrentScript.includes(format) && replacement !== 'undefined');
  12469. }
  12470. if (typeof replacement === 'string') {
  12471. if (parent instanceof MemberExpression) {
  12472. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  12473. }
  12474. else {
  12475. code.overwrite(start, end, replacement, { contentOnly: true });
  12476. }
  12477. }
  12478. }
  12479. setResolution(format, accessedGlobalsByScope, preliminaryChunkId) {
  12480. this.preliminaryChunkId = preliminaryChunkId;
  12481. const accessedGlobals = (this.metaProperty?.startsWith(FILE_PREFIX) ? accessedFileUrlGlobals : accessedMetaUrlGlobals)[format];
  12482. if (accessedGlobals.length > 0) {
  12483. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  12484. }
  12485. }
  12486. }
  12487. const formatsMaybeAccessDocumentCurrentScript = ['cjs', 'iife', 'umd'];
  12488. const accessedMetaUrlGlobals = {
  12489. amd: ['document', 'module', 'URL'],
  12490. cjs: ['document', 'require', 'URL', DOCUMENT_CURRENT_SCRIPT],
  12491. es: [],
  12492. iife: ['document', 'URL', DOCUMENT_CURRENT_SCRIPT],
  12493. system: ['module'],
  12494. umd: ['document', 'require', 'URL', DOCUMENT_CURRENT_SCRIPT]
  12495. };
  12496. const accessedFileUrlGlobals = {
  12497. amd: ['document', 'require', 'URL'],
  12498. cjs: ['document', 'require', 'URL'],
  12499. es: [],
  12500. iife: ['document', 'URL'],
  12501. system: ['module', 'URL'],
  12502. umd: ['document', 'require', 'URL']
  12503. };
  12504. const getResolveUrl = (path, URL = 'URL') => `new ${URL}(${path}).href`;
  12505. 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`);
  12506. const getGenericImportMetaMechanism = (getUrl) => (property, { chunkId }) => {
  12507. const urlMechanism = getUrl(chunkId);
  12508. return property === null
  12509. ? `({ url: ${urlMechanism} })`
  12510. : property === 'url'
  12511. ? urlMechanism
  12512. : 'undefined';
  12513. };
  12514. const getFileUrlFromFullPath = (path) => `require('u' + 'rl').pathToFileURL(${path}).href`;
  12515. const getFileUrlFromRelativePath = (path) => getFileUrlFromFullPath(`__dirname + '/${path}'`);
  12516. 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)`;
  12517. const relativeUrlMechanisms = {
  12518. amd: relativePath => {
  12519. if (relativePath[0] !== '.')
  12520. relativePath = './' + relativePath;
  12521. return getResolveUrl(`require.toUrl('${relativePath}'), document.baseURI`);
  12522. },
  12523. cjs: relativePath => `(typeof document === 'undefined' ? ${getFileUrlFromRelativePath(relativePath)} : ${getRelativeUrlFromDocument(relativePath)})`,
  12524. es: relativePath => getResolveUrl(`'${relativePath}', import.meta.url`),
  12525. iife: relativePath => getRelativeUrlFromDocument(relativePath),
  12526. system: relativePath => getResolveUrl(`'${relativePath}', module.meta.url`),
  12527. umd: relativePath => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getFileUrlFromRelativePath(relativePath)} : ${getRelativeUrlFromDocument(relativePath, true)})`
  12528. };
  12529. const importMetaMechanisms = {
  12530. amd: getGenericImportMetaMechanism(() => getResolveUrl(`module.uri, document.baseURI`)),
  12531. cjs: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' ? ${getFileUrlFromFullPath('__filename')} : ${getUrlFromDocument(chunkId)})`),
  12532. iife: getGenericImportMetaMechanism(chunkId => getUrlFromDocument(chunkId)),
  12533. system: (property, { snippets: { getPropertyAccess } }) => property === null ? `module.meta` : `module.meta${getPropertyAccess(property)}`,
  12534. umd: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getFileUrlFromFullPath('__filename')} : ${getUrlFromDocument(chunkId, true)})`)
  12535. };
  12536. class NewExpression extends NodeBase {
  12537. hasEffects(context) {
  12538. try {
  12539. for (const argument of this.arguments) {
  12540. if (argument.hasEffects(context))
  12541. return true;
  12542. }
  12543. if (this.annotationPure) {
  12544. return false;
  12545. }
  12546. return (this.callee.hasEffects(context) ||
  12547. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  12548. }
  12549. finally {
  12550. if (!this.deoptimized)
  12551. this.applyDeoptimizations();
  12552. }
  12553. }
  12554. hasEffectsOnInteractionAtPath(path, { type }) {
  12555. return path.length > 0 || type !== INTERACTION_ACCESSED;
  12556. }
  12557. include(context, includeChildrenRecursively) {
  12558. if (!this.deoptimized)
  12559. this.applyDeoptimizations();
  12560. if (includeChildrenRecursively) {
  12561. super.include(context, includeChildrenRecursively);
  12562. }
  12563. else {
  12564. this.included = true;
  12565. this.callee.include(context, false);
  12566. }
  12567. this.callee.includeCallArguments(context, this.arguments);
  12568. }
  12569. initialise() {
  12570. this.interaction = {
  12571. args: [null, ...this.arguments],
  12572. type: INTERACTION_CALLED,
  12573. withNew: true
  12574. };
  12575. }
  12576. render(code, options) {
  12577. this.callee.render(code, options);
  12578. renderCallArguments(code, options, this);
  12579. }
  12580. applyDeoptimizations() {
  12581. this.deoptimized = true;
  12582. this.callee.deoptimizeArgumentsOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  12583. this.context.requestTreeshakingPass();
  12584. }
  12585. }
  12586. class ObjectExpression extends NodeBase {
  12587. constructor() {
  12588. super(...arguments);
  12589. this.objectEntity = null;
  12590. }
  12591. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  12592. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  12593. }
  12594. deoptimizeCache() {
  12595. this.getObjectEntity().deoptimizeAllProperties();
  12596. }
  12597. deoptimizePath(path) {
  12598. this.getObjectEntity().deoptimizePath(path);
  12599. }
  12600. getLiteralValueAtPath(path, recursionTracker, origin) {
  12601. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  12602. }
  12603. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  12604. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  12605. }
  12606. hasEffectsOnInteractionAtPath(path, interaction, context) {
  12607. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  12608. }
  12609. render(code, options, { renderedSurroundingElement } = BLANK) {
  12610. super.render(code, options);
  12611. if (renderedSurroundingElement === ExpressionStatement$1 ||
  12612. renderedSurroundingElement === ArrowFunctionExpression$1) {
  12613. code.appendRight(this.start, '(');
  12614. code.prependLeft(this.end, ')');
  12615. }
  12616. }
  12617. applyDeoptimizations() { }
  12618. getObjectEntity() {
  12619. if (this.objectEntity !== null) {
  12620. return this.objectEntity;
  12621. }
  12622. let prototype = OBJECT_PROTOTYPE;
  12623. const properties = [];
  12624. for (const property of this.properties) {
  12625. if (property instanceof SpreadElement) {
  12626. properties.push({ key: UnknownKey, kind: 'init', property });
  12627. continue;
  12628. }
  12629. let key;
  12630. if (property.computed) {
  12631. const keyValue = property.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  12632. if (typeof keyValue === 'symbol') {
  12633. properties.push({ key: UnknownKey, kind: property.kind, property });
  12634. continue;
  12635. }
  12636. else {
  12637. key = String(keyValue);
  12638. }
  12639. }
  12640. else {
  12641. key =
  12642. property.key instanceof Identifier
  12643. ? property.key.name
  12644. : String(property.key.value);
  12645. if (key === '__proto__' && property.kind === 'init') {
  12646. prototype =
  12647. property.value instanceof Literal && property.value.value === null
  12648. ? null
  12649. : property.value;
  12650. continue;
  12651. }
  12652. }
  12653. properties.push({ key, kind: property.kind, property });
  12654. }
  12655. return (this.objectEntity = new ObjectEntity(properties, prototype));
  12656. }
  12657. }
  12658. class PrivateIdentifier extends NodeBase {
  12659. }
  12660. class Program extends NodeBase {
  12661. constructor() {
  12662. super(...arguments);
  12663. this.hasCachedEffect = null;
  12664. this.hasLoggedEffect = false;
  12665. }
  12666. hasCachedEffects() {
  12667. if (!this.included) {
  12668. return false;
  12669. }
  12670. return this.hasCachedEffect === null
  12671. ? (this.hasCachedEffect = this.hasEffects(createHasEffectsContext()))
  12672. : this.hasCachedEffect;
  12673. }
  12674. hasEffects(context) {
  12675. for (const node of this.body) {
  12676. if (node.hasEffects(context)) {
  12677. if (this.context.options.experimentalLogSideEffects && !this.hasLoggedEffect) {
  12678. this.hasLoggedEffect = true;
  12679. const { code, log, module } = this.context;
  12680. log(LOGLEVEL_INFO, logFirstSideEffect(code, module.id, locate(code, node.start, { offsetLine: 1 })), node.start);
  12681. }
  12682. return (this.hasCachedEffect = true);
  12683. }
  12684. }
  12685. return false;
  12686. }
  12687. include(context, includeChildrenRecursively) {
  12688. this.included = true;
  12689. for (const node of this.body) {
  12690. if (includeChildrenRecursively || node.shouldBeIncluded(context)) {
  12691. node.include(context, includeChildrenRecursively);
  12692. }
  12693. }
  12694. }
  12695. render(code, options) {
  12696. let start = this.start;
  12697. if (code.original.startsWith('#!')) {
  12698. start = Math.min(code.original.indexOf('\n') + 1, this.end);
  12699. code.remove(0, start);
  12700. }
  12701. if (this.body.length > 0) {
  12702. // Keep all consecutive lines that start with a comment
  12703. while (code.original[start] === '/' && /[*/]/.test(code.original[start + 1])) {
  12704. const firstLineBreak = findFirstLineBreakOutsideComment(code.original.slice(start, this.body[0].start));
  12705. if (firstLineBreak[0] === -1) {
  12706. break;
  12707. }
  12708. start += firstLineBreak[1];
  12709. }
  12710. renderStatementList(this.body, code, start, this.end, options);
  12711. }
  12712. else {
  12713. super.render(code, options);
  12714. }
  12715. }
  12716. applyDeoptimizations() { }
  12717. }
  12718. class Property extends MethodBase {
  12719. constructor() {
  12720. super(...arguments);
  12721. this.declarationInit = null;
  12722. }
  12723. declare(kind, init) {
  12724. this.declarationInit = init;
  12725. return this.value.declare(kind, UNKNOWN_EXPRESSION);
  12726. }
  12727. hasEffects(context) {
  12728. if (!this.deoptimized)
  12729. this.applyDeoptimizations();
  12730. const propertyReadSideEffects = this.context.options.treeshake
  12731. .propertyReadSideEffects;
  12732. return ((this.parent.type === 'ObjectPattern' && propertyReadSideEffects === 'always') ||
  12733. this.key.hasEffects(context) ||
  12734. this.value.hasEffects(context));
  12735. }
  12736. markDeclarationReached() {
  12737. this.value.markDeclarationReached();
  12738. }
  12739. render(code, options) {
  12740. if (!this.shorthand) {
  12741. this.key.render(code, options);
  12742. }
  12743. this.value.render(code, options, { isShorthandProperty: this.shorthand });
  12744. }
  12745. applyDeoptimizations() {
  12746. this.deoptimized = true;
  12747. if (this.declarationInit !== null) {
  12748. this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
  12749. this.context.requestTreeshakingPass();
  12750. }
  12751. }
  12752. }
  12753. class PropertyDefinition extends NodeBase {
  12754. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  12755. this.value?.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  12756. }
  12757. deoptimizePath(path) {
  12758. this.value?.deoptimizePath(path);
  12759. }
  12760. getLiteralValueAtPath(path, recursionTracker, origin) {
  12761. return this.value
  12762. ? this.value.getLiteralValueAtPath(path, recursionTracker, origin)
  12763. : UnknownValue;
  12764. }
  12765. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  12766. return this.value
  12767. ? this.value.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)
  12768. : UNKNOWN_RETURN_EXPRESSION;
  12769. }
  12770. hasEffects(context) {
  12771. return this.key.hasEffects(context) || (this.static && !!this.value?.hasEffects(context));
  12772. }
  12773. hasEffectsOnInteractionAtPath(path, interaction, context) {
  12774. return !this.value || this.value.hasEffectsOnInteractionAtPath(path, interaction, context);
  12775. }
  12776. applyDeoptimizations() { }
  12777. }
  12778. class ReturnStatement extends NodeBase {
  12779. hasEffects(context) {
  12780. if (!context.ignore.returnYield || this.argument?.hasEffects(context))
  12781. return true;
  12782. context.brokenFlow = true;
  12783. return false;
  12784. }
  12785. include(context, includeChildrenRecursively) {
  12786. this.included = true;
  12787. this.argument?.include(context, includeChildrenRecursively);
  12788. context.brokenFlow = true;
  12789. }
  12790. initialise() {
  12791. this.scope.addReturnExpression(this.argument || UNKNOWN_EXPRESSION);
  12792. }
  12793. render(code, options) {
  12794. if (this.argument) {
  12795. this.argument.render(code, options, { preventASI: true });
  12796. if (this.argument.start === this.start + 6 /* 'return'.length */) {
  12797. code.prependLeft(this.start + 6, ' ');
  12798. }
  12799. }
  12800. }
  12801. }
  12802. class SequenceExpression extends NodeBase {
  12803. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  12804. this.expressions[this.expressions.length - 1].deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  12805. }
  12806. deoptimizePath(path) {
  12807. this.expressions[this.expressions.length - 1].deoptimizePath(path);
  12808. }
  12809. getLiteralValueAtPath(path, recursionTracker, origin) {
  12810. return this.expressions[this.expressions.length - 1].getLiteralValueAtPath(path, recursionTracker, origin);
  12811. }
  12812. hasEffects(context) {
  12813. for (const expression of this.expressions) {
  12814. if (expression.hasEffects(context))
  12815. return true;
  12816. }
  12817. return false;
  12818. }
  12819. hasEffectsOnInteractionAtPath(path, interaction, context) {
  12820. return this.expressions[this.expressions.length - 1].hasEffectsOnInteractionAtPath(path, interaction, context);
  12821. }
  12822. include(context, includeChildrenRecursively) {
  12823. this.included = true;
  12824. const lastExpression = this.expressions[this.expressions.length - 1];
  12825. for (const expression of this.expressions) {
  12826. if (includeChildrenRecursively ||
  12827. (expression === lastExpression && !(this.parent instanceof ExpressionStatement)) ||
  12828. expression.shouldBeIncluded(context))
  12829. expression.include(context, includeChildrenRecursively);
  12830. }
  12831. }
  12832. render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
  12833. let includedNodes = 0;
  12834. let lastSeparatorPos = null;
  12835. const lastNode = this.expressions[this.expressions.length - 1];
  12836. for (const { node, separator, start, end } of getCommaSeparatedNodesWithBoundaries(this.expressions, code, this.start, this.end)) {
  12837. if (!node.included) {
  12838. treeshakeNode(node, code, start, end);
  12839. continue;
  12840. }
  12841. includedNodes++;
  12842. lastSeparatorPos = separator;
  12843. if (includedNodes === 1 && preventASI) {
  12844. removeLineBreaks(code, start, node.start);
  12845. }
  12846. if (includedNodes === 1) {
  12847. const parentType = renderedParentType || this.parent.type;
  12848. node.render(code, options, {
  12849. isCalleeOfRenderedParent: isCalleeOfRenderedParent && node === lastNode,
  12850. renderedParentType: parentType,
  12851. renderedSurroundingElement: parentType
  12852. });
  12853. }
  12854. else {
  12855. node.render(code, options);
  12856. }
  12857. }
  12858. if (lastSeparatorPos) {
  12859. code.remove(lastSeparatorPos, this.end);
  12860. }
  12861. }
  12862. }
  12863. class StaticBlock extends NodeBase {
  12864. createScope(parentScope) {
  12865. this.scope = new BlockScope(parentScope);
  12866. }
  12867. hasEffects(context) {
  12868. for (const node of this.body) {
  12869. if (node.hasEffects(context))
  12870. return true;
  12871. }
  12872. return false;
  12873. }
  12874. include(context, includeChildrenRecursively) {
  12875. this.included = true;
  12876. for (const node of this.body) {
  12877. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  12878. node.include(context, includeChildrenRecursively);
  12879. }
  12880. }
  12881. render(code, options) {
  12882. if (this.body.length > 0) {
  12883. const bodyStartPos = findFirstOccurrenceOutsideComment(code.original.slice(this.start, this.end), '{') + 1;
  12884. renderStatementList(this.body, code, this.start + bodyStartPos, this.end - 1, options);
  12885. }
  12886. else {
  12887. super.render(code, options);
  12888. }
  12889. }
  12890. }
  12891. class Super extends NodeBase {
  12892. bind() {
  12893. this.variable = this.scope.findVariable('this');
  12894. }
  12895. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  12896. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  12897. }
  12898. deoptimizePath(path) {
  12899. this.variable.deoptimizePath(path);
  12900. }
  12901. include() {
  12902. if (!this.included) {
  12903. this.included = true;
  12904. this.context.includeVariableInModule(this.variable);
  12905. }
  12906. }
  12907. }
  12908. class SwitchCase extends NodeBase {
  12909. hasEffects(context) {
  12910. if (this.test?.hasEffects(context))
  12911. return true;
  12912. for (const node of this.consequent) {
  12913. if (context.brokenFlow)
  12914. break;
  12915. if (node.hasEffects(context))
  12916. return true;
  12917. }
  12918. return false;
  12919. }
  12920. include(context, includeChildrenRecursively) {
  12921. this.included = true;
  12922. this.test?.include(context, includeChildrenRecursively);
  12923. for (const node of this.consequent) {
  12924. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  12925. node.include(context, includeChildrenRecursively);
  12926. }
  12927. }
  12928. render(code, options, nodeRenderOptions) {
  12929. if (this.consequent.length > 0) {
  12930. this.test && this.test.render(code, options);
  12931. const testEnd = this.test
  12932. ? this.test.end
  12933. : findFirstOccurrenceOutsideComment(code.original, 'default', this.start) + 7;
  12934. const consequentStart = findFirstOccurrenceOutsideComment(code.original, ':', testEnd) + 1;
  12935. renderStatementList(this.consequent, code, consequentStart, nodeRenderOptions.end, options);
  12936. }
  12937. else {
  12938. super.render(code, options);
  12939. }
  12940. }
  12941. }
  12942. SwitchCase.prototype.needsBoundaries = true;
  12943. class SwitchStatement extends NodeBase {
  12944. createScope(parentScope) {
  12945. this.parentScope = parentScope;
  12946. this.scope = new BlockScope(parentScope);
  12947. }
  12948. hasEffects(context) {
  12949. if (this.discriminant.hasEffects(context))
  12950. return true;
  12951. const { brokenFlow, hasBreak, ignore } = context;
  12952. const { breaks } = ignore;
  12953. ignore.breaks = true;
  12954. context.hasBreak = false;
  12955. let onlyHasBrokenFlow = true;
  12956. for (const switchCase of this.cases) {
  12957. if (switchCase.hasEffects(context))
  12958. return true;
  12959. // eslint-disable-next-line unicorn/consistent-destructuring
  12960. onlyHasBrokenFlow && (onlyHasBrokenFlow = context.brokenFlow && !context.hasBreak);
  12961. context.hasBreak = false;
  12962. context.brokenFlow = brokenFlow;
  12963. }
  12964. if (this.defaultCase !== null) {
  12965. context.brokenFlow = onlyHasBrokenFlow;
  12966. }
  12967. ignore.breaks = breaks;
  12968. context.hasBreak = hasBreak;
  12969. return false;
  12970. }
  12971. include(context, includeChildrenRecursively) {
  12972. this.included = true;
  12973. this.discriminant.include(context, includeChildrenRecursively);
  12974. const { brokenFlow, hasBreak } = context;
  12975. context.hasBreak = false;
  12976. let onlyHasBrokenFlow = true;
  12977. let isCaseIncluded = includeChildrenRecursively ||
  12978. (this.defaultCase !== null && this.defaultCase < this.cases.length - 1);
  12979. for (let caseIndex = this.cases.length - 1; caseIndex >= 0; caseIndex--) {
  12980. const switchCase = this.cases[caseIndex];
  12981. if (switchCase.included) {
  12982. isCaseIncluded = true;
  12983. }
  12984. if (!isCaseIncluded) {
  12985. const hasEffectsContext = createHasEffectsContext();
  12986. hasEffectsContext.ignore.breaks = true;
  12987. isCaseIncluded = switchCase.hasEffects(hasEffectsContext);
  12988. }
  12989. if (isCaseIncluded) {
  12990. switchCase.include(context, includeChildrenRecursively);
  12991. // eslint-disable-next-line unicorn/consistent-destructuring
  12992. onlyHasBrokenFlow && (onlyHasBrokenFlow = context.brokenFlow && !context.hasBreak);
  12993. context.hasBreak = false;
  12994. context.brokenFlow = brokenFlow;
  12995. }
  12996. else {
  12997. onlyHasBrokenFlow = brokenFlow;
  12998. }
  12999. }
  13000. if (isCaseIncluded && this.defaultCase !== null) {
  13001. context.brokenFlow = onlyHasBrokenFlow;
  13002. }
  13003. context.hasBreak = hasBreak;
  13004. }
  13005. initialise() {
  13006. for (let caseIndex = 0; caseIndex < this.cases.length; caseIndex++) {
  13007. if (this.cases[caseIndex].test === null) {
  13008. this.defaultCase = caseIndex;
  13009. return;
  13010. }
  13011. }
  13012. this.defaultCase = null;
  13013. }
  13014. parseNode(esTreeNode) {
  13015. this.discriminant = new (this.context.getNodeConstructor(esTreeNode.discriminant.type))(esTreeNode.discriminant, this, this.parentScope);
  13016. super.parseNode(esTreeNode);
  13017. }
  13018. render(code, options) {
  13019. this.discriminant.render(code, options);
  13020. if (this.cases.length > 0) {
  13021. renderStatementList(this.cases, code, this.cases[0].start, this.end - 1, options);
  13022. }
  13023. }
  13024. }
  13025. class TaggedTemplateExpression extends CallExpressionBase {
  13026. bind() {
  13027. super.bind();
  13028. if (this.tag.type === Identifier$1) {
  13029. const name = this.tag.name;
  13030. const variable = this.scope.findVariable(name);
  13031. if (variable.isNamespace) {
  13032. this.context.log(LOGLEVEL_WARN, logCannotCallNamespace(name), this.start);
  13033. }
  13034. }
  13035. }
  13036. hasEffects(context) {
  13037. try {
  13038. for (const argument of this.quasi.expressions) {
  13039. if (argument.hasEffects(context))
  13040. return true;
  13041. }
  13042. return (this.tag.hasEffects(context) ||
  13043. this.tag.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  13044. }
  13045. finally {
  13046. if (!this.deoptimized)
  13047. this.applyDeoptimizations();
  13048. }
  13049. }
  13050. include(context, includeChildrenRecursively) {
  13051. if (!this.deoptimized)
  13052. this.applyDeoptimizations();
  13053. if (includeChildrenRecursively) {
  13054. super.include(context, includeChildrenRecursively);
  13055. }
  13056. else {
  13057. this.included = true;
  13058. this.tag.include(context, includeChildrenRecursively);
  13059. this.quasi.include(context, includeChildrenRecursively);
  13060. }
  13061. this.tag.includeCallArguments(context, this.args);
  13062. const [returnExpression] = this.getReturnExpression();
  13063. if (!returnExpression.included) {
  13064. returnExpression.include(context, false);
  13065. }
  13066. }
  13067. initialise() {
  13068. this.args = [UNKNOWN_EXPRESSION, ...this.quasi.expressions];
  13069. this.interaction = {
  13070. args: [
  13071. this.tag instanceof MemberExpression && !this.tag.variable ? this.tag.object : null,
  13072. ...this.args
  13073. ],
  13074. type: INTERACTION_CALLED,
  13075. withNew: false
  13076. };
  13077. }
  13078. render(code, options) {
  13079. this.tag.render(code, options, { isCalleeOfRenderedParent: true });
  13080. this.quasi.render(code, options);
  13081. }
  13082. applyDeoptimizations() {
  13083. this.deoptimized = true;
  13084. this.tag.deoptimizeArgumentsOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  13085. this.context.requestTreeshakingPass();
  13086. }
  13087. getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) {
  13088. if (this.returnExpression === null) {
  13089. this.returnExpression = UNKNOWN_RETURN_EXPRESSION;
  13090. return (this.returnExpression = this.tag.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.interaction, recursionTracker, this));
  13091. }
  13092. return this.returnExpression;
  13093. }
  13094. }
  13095. class TemplateElement extends NodeBase {
  13096. // Do not try to bind value
  13097. bind() { }
  13098. hasEffects() {
  13099. return false;
  13100. }
  13101. include() {
  13102. this.included = true;
  13103. }
  13104. parseNode(esTreeNode) {
  13105. this.value = esTreeNode.value;
  13106. super.parseNode(esTreeNode);
  13107. }
  13108. render() { }
  13109. }
  13110. class TemplateLiteral extends NodeBase {
  13111. deoptimizeArgumentsOnInteractionAtPath() { }
  13112. getLiteralValueAtPath(path) {
  13113. if (path.length > 0 || this.quasis.length !== 1) {
  13114. return UnknownValue;
  13115. }
  13116. return this.quasis[0].value.cooked;
  13117. }
  13118. getReturnExpressionWhenCalledAtPath(path) {
  13119. if (path.length !== 1) {
  13120. return UNKNOWN_RETURN_EXPRESSION;
  13121. }
  13122. return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
  13123. }
  13124. hasEffectsOnInteractionAtPath(path, interaction, context) {
  13125. if (interaction.type === INTERACTION_ACCESSED) {
  13126. return path.length > 1;
  13127. }
  13128. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  13129. return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
  13130. }
  13131. return true;
  13132. }
  13133. render(code, options) {
  13134. code.indentExclusionRanges.push([this.start, this.end]);
  13135. super.render(code, options);
  13136. }
  13137. }
  13138. class UndefinedVariable extends Variable {
  13139. constructor() {
  13140. super('undefined');
  13141. }
  13142. getLiteralValueAtPath() {
  13143. return undefined;
  13144. }
  13145. }
  13146. class ExportDefaultVariable extends LocalVariable {
  13147. constructor(name, exportDefaultDeclaration, context) {
  13148. super(name, exportDefaultDeclaration, exportDefaultDeclaration.declaration, context);
  13149. this.hasId = false;
  13150. this.originalId = null;
  13151. this.originalVariable = null;
  13152. const declaration = exportDefaultDeclaration.declaration;
  13153. if ((declaration instanceof FunctionDeclaration || declaration instanceof ClassDeclaration) &&
  13154. declaration.id) {
  13155. this.hasId = true;
  13156. this.originalId = declaration.id;
  13157. }
  13158. else if (declaration instanceof Identifier) {
  13159. this.originalId = declaration;
  13160. }
  13161. }
  13162. addReference(identifier) {
  13163. if (!this.hasId) {
  13164. this.name = identifier.name;
  13165. }
  13166. }
  13167. forbidName(name) {
  13168. const original = this.getOriginalVariable();
  13169. if (original === this) {
  13170. super.forbidName(name);
  13171. }
  13172. else {
  13173. original.forbidName(name);
  13174. }
  13175. }
  13176. getAssignedVariableName() {
  13177. return (this.originalId && this.originalId.name) || null;
  13178. }
  13179. getBaseVariableName() {
  13180. const original = this.getOriginalVariable();
  13181. return original === this ? super.getBaseVariableName() : original.getBaseVariableName();
  13182. }
  13183. getDirectOriginalVariable() {
  13184. return this.originalId &&
  13185. (this.hasId ||
  13186. !(this.originalId.isPossibleTDZ() ||
  13187. this.originalId.variable.isReassigned ||
  13188. this.originalId.variable instanceof UndefinedVariable ||
  13189. // this avoids a circular dependency
  13190. 'syntheticNamespace' in this.originalId.variable))
  13191. ? this.originalId.variable
  13192. : null;
  13193. }
  13194. getName(getPropertyAccess) {
  13195. const original = this.getOriginalVariable();
  13196. return original === this
  13197. ? super.getName(getPropertyAccess)
  13198. : original.getName(getPropertyAccess);
  13199. }
  13200. getOriginalVariable() {
  13201. if (this.originalVariable)
  13202. return this.originalVariable;
  13203. // eslint-disable-next-line @typescript-eslint/no-this-alias
  13204. let original = this;
  13205. let currentVariable;
  13206. const checkedVariables = new Set();
  13207. do {
  13208. checkedVariables.add(original);
  13209. currentVariable = original;
  13210. original = currentVariable.getDirectOriginalVariable();
  13211. } while (original instanceof ExportDefaultVariable && !checkedVariables.has(original));
  13212. return (this.originalVariable = original || currentVariable);
  13213. }
  13214. }
  13215. class ModuleScope extends ChildScope {
  13216. constructor(parent, context) {
  13217. super(parent);
  13218. this.context = context;
  13219. this.variables.set('this', new LocalVariable('this', null, UNDEFINED_EXPRESSION, context));
  13220. }
  13221. addExportDefaultDeclaration(name, exportDefaultDeclaration, context) {
  13222. const variable = new ExportDefaultVariable(name, exportDefaultDeclaration, context);
  13223. this.variables.set('default', variable);
  13224. return variable;
  13225. }
  13226. addNamespaceMemberAccess() { }
  13227. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  13228. // all module level variables are already deconflicted when deconflicting the chunk
  13229. for (const scope of this.children)
  13230. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  13231. }
  13232. findLexicalBoundary() {
  13233. return this;
  13234. }
  13235. findVariable(name) {
  13236. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  13237. if (knownVariable) {
  13238. return knownVariable;
  13239. }
  13240. const variable = this.context.traceVariable(name) || this.parent.findVariable(name);
  13241. if (variable instanceof GlobalVariable) {
  13242. this.accessedOutsideVariables.set(name, variable);
  13243. }
  13244. return variable;
  13245. }
  13246. }
  13247. class ThisExpression extends NodeBase {
  13248. bind() {
  13249. this.variable = this.scope.findVariable('this');
  13250. }
  13251. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  13252. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  13253. }
  13254. deoptimizePath(path) {
  13255. this.variable.deoptimizePath(path);
  13256. }
  13257. hasEffectsOnInteractionAtPath(path, interaction, context) {
  13258. if (path.length === 0) {
  13259. return interaction.type !== INTERACTION_ACCESSED;
  13260. }
  13261. return this.variable.hasEffectsOnInteractionAtPath(path, interaction, context);
  13262. }
  13263. include() {
  13264. if (!this.included) {
  13265. this.included = true;
  13266. this.context.includeVariableInModule(this.variable);
  13267. }
  13268. }
  13269. initialise() {
  13270. this.alias =
  13271. this.scope.findLexicalBoundary() instanceof ModuleScope ? this.context.moduleContext : null;
  13272. if (this.alias === 'undefined') {
  13273. this.context.log(LOGLEVEL_WARN, logThisIsUndefined(), this.start);
  13274. }
  13275. }
  13276. render(code) {
  13277. if (this.alias !== null) {
  13278. code.overwrite(this.start, this.end, this.alias, {
  13279. contentOnly: false,
  13280. storeName: true
  13281. });
  13282. }
  13283. }
  13284. }
  13285. class ThrowStatement extends NodeBase {
  13286. hasEffects() {
  13287. return true;
  13288. }
  13289. include(context, includeChildrenRecursively) {
  13290. this.included = true;
  13291. this.argument.include(context, includeChildrenRecursively);
  13292. context.brokenFlow = true;
  13293. }
  13294. render(code, options) {
  13295. this.argument.render(code, options, { preventASI: true });
  13296. if (this.argument.start === this.start + 5 /* 'throw'.length */) {
  13297. code.prependLeft(this.start + 5, ' ');
  13298. }
  13299. }
  13300. }
  13301. class TryStatement extends NodeBase {
  13302. constructor() {
  13303. super(...arguments);
  13304. this.directlyIncluded = false;
  13305. this.includedLabelsAfterBlock = null;
  13306. }
  13307. hasEffects(context) {
  13308. return ((this.context.options.treeshake.tryCatchDeoptimization
  13309. ? this.block.body.length > 0
  13310. : this.block.hasEffects(context)) || !!this.finalizer?.hasEffects(context));
  13311. }
  13312. include(context, includeChildrenRecursively) {
  13313. const tryCatchDeoptimization = this.context.options.treeshake
  13314. ?.tryCatchDeoptimization;
  13315. const { brokenFlow, includedLabels } = context;
  13316. if (!this.directlyIncluded || !tryCatchDeoptimization) {
  13317. this.included = true;
  13318. this.directlyIncluded = true;
  13319. this.block.include(context, tryCatchDeoptimization ? INCLUDE_PARAMETERS : includeChildrenRecursively);
  13320. if (includedLabels.size > 0) {
  13321. this.includedLabelsAfterBlock = [...includedLabels];
  13322. }
  13323. context.brokenFlow = brokenFlow;
  13324. }
  13325. else if (this.includedLabelsAfterBlock) {
  13326. for (const label of this.includedLabelsAfterBlock) {
  13327. includedLabels.add(label);
  13328. }
  13329. }
  13330. if (this.handler !== null) {
  13331. this.handler.include(context, includeChildrenRecursively);
  13332. context.brokenFlow = brokenFlow;
  13333. }
  13334. this.finalizer?.include(context, includeChildrenRecursively);
  13335. }
  13336. }
  13337. const unaryOperators = {
  13338. '!': value => !value,
  13339. '+': value => +value,
  13340. '-': value => -value,
  13341. delete: () => UnknownValue,
  13342. typeof: value => typeof value,
  13343. void: () => undefined,
  13344. '~': value => ~value
  13345. };
  13346. class UnaryExpression extends NodeBase {
  13347. getLiteralValueAtPath(path, recursionTracker, origin) {
  13348. if (path.length > 0)
  13349. return UnknownValue;
  13350. const argumentValue = this.argument.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  13351. if (typeof argumentValue === 'symbol')
  13352. return UnknownValue;
  13353. return unaryOperators[this.operator](argumentValue);
  13354. }
  13355. hasEffects(context) {
  13356. if (!this.deoptimized)
  13357. this.applyDeoptimizations();
  13358. if (this.operator === 'typeof' && this.argument instanceof Identifier)
  13359. return false;
  13360. return (this.argument.hasEffects(context) ||
  13361. (this.operator === 'delete' &&
  13362. this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context)));
  13363. }
  13364. hasEffectsOnInteractionAtPath(path, { type }) {
  13365. return type !== INTERACTION_ACCESSED || path.length > (this.operator === 'void' ? 0 : 1);
  13366. }
  13367. applyDeoptimizations() {
  13368. this.deoptimized = true;
  13369. if (this.operator === 'delete') {
  13370. this.argument.deoptimizePath(EMPTY_PATH);
  13371. this.context.requestTreeshakingPass();
  13372. }
  13373. }
  13374. }
  13375. class UnknownNode extends NodeBase {
  13376. hasEffects() {
  13377. return true;
  13378. }
  13379. include(context) {
  13380. super.include(context, true);
  13381. }
  13382. }
  13383. class UpdateExpression extends NodeBase {
  13384. hasEffects(context) {
  13385. if (!this.deoptimized)
  13386. this.applyDeoptimizations();
  13387. return this.argument.hasEffectsAsAssignmentTarget(context, true);
  13388. }
  13389. hasEffectsOnInteractionAtPath(path, { type }) {
  13390. return path.length > 1 || type !== INTERACTION_ACCESSED;
  13391. }
  13392. include(context, includeChildrenRecursively) {
  13393. if (!this.deoptimized)
  13394. this.applyDeoptimizations();
  13395. this.included = true;
  13396. this.argument.includeAsAssignmentTarget(context, includeChildrenRecursively, true);
  13397. }
  13398. initialise() {
  13399. this.argument.setAssignedValue(UNKNOWN_EXPRESSION);
  13400. }
  13401. render(code, options) {
  13402. const { exportNamesByVariable, format, snippets: { _ } } = options;
  13403. this.argument.render(code, options);
  13404. if (format === 'system') {
  13405. const variable = this.argument.variable;
  13406. const exportNames = exportNamesByVariable.get(variable);
  13407. if (exportNames) {
  13408. if (this.prefix) {
  13409. if (exportNames.length === 1) {
  13410. renderSystemExportExpression(variable, this.start, this.end, code, options);
  13411. }
  13412. else {
  13413. renderSystemExportSequenceAfterExpression(variable, this.start, this.end, this.parent.type !== ExpressionStatement$1, code, options);
  13414. }
  13415. }
  13416. else {
  13417. const operator = this.operator[0];
  13418. renderSystemExportSequenceBeforeExpression(variable, this.start, this.end, this.parent.type !== ExpressionStatement$1, code, options, `${_}${operator}${_}1`);
  13419. }
  13420. }
  13421. }
  13422. }
  13423. applyDeoptimizations() {
  13424. this.deoptimized = true;
  13425. this.argument.deoptimizePath(EMPTY_PATH);
  13426. if (this.argument instanceof Identifier) {
  13427. const variable = this.scope.findVariable(this.argument.name);
  13428. variable.isReassigned = true;
  13429. }
  13430. this.context.requestTreeshakingPass();
  13431. }
  13432. }
  13433. function areAllDeclarationsIncludedAndNotExported(declarations, exportNamesByVariable) {
  13434. for (const declarator of declarations) {
  13435. if (!declarator.id.included)
  13436. return false;
  13437. if (declarator.id.type === Identifier$1) {
  13438. if (exportNamesByVariable.has(declarator.id.variable))
  13439. return false;
  13440. }
  13441. else {
  13442. const exportedVariables = [];
  13443. declarator.id.addExportedVariables(exportedVariables, exportNamesByVariable);
  13444. if (exportedVariables.length > 0)
  13445. return false;
  13446. }
  13447. }
  13448. return true;
  13449. }
  13450. class VariableDeclaration extends NodeBase {
  13451. deoptimizePath() {
  13452. for (const declarator of this.declarations) {
  13453. declarator.deoptimizePath(EMPTY_PATH);
  13454. }
  13455. }
  13456. hasEffectsOnInteractionAtPath() {
  13457. return false;
  13458. }
  13459. include(context, includeChildrenRecursively, { asSingleStatement } = BLANK) {
  13460. this.included = true;
  13461. for (const declarator of this.declarations) {
  13462. if (includeChildrenRecursively || declarator.shouldBeIncluded(context))
  13463. declarator.include(context, includeChildrenRecursively);
  13464. const { id, init } = declarator;
  13465. if (asSingleStatement) {
  13466. id.include(context, includeChildrenRecursively);
  13467. }
  13468. if (init &&
  13469. id.included &&
  13470. !init.included &&
  13471. (id instanceof ObjectPattern || id instanceof ArrayPattern)) {
  13472. init.include(context, includeChildrenRecursively);
  13473. }
  13474. }
  13475. }
  13476. initialise() {
  13477. for (const declarator of this.declarations) {
  13478. declarator.declareDeclarator(this.kind);
  13479. }
  13480. }
  13481. render(code, options, nodeRenderOptions = BLANK) {
  13482. if (areAllDeclarationsIncludedAndNotExported(this.declarations, options.exportNamesByVariable)) {
  13483. for (const declarator of this.declarations) {
  13484. declarator.render(code, options);
  13485. }
  13486. if (!nodeRenderOptions.isNoStatement &&
  13487. code.original.charCodeAt(this.end - 1) !== 59 /*";"*/) {
  13488. code.appendLeft(this.end, ';');
  13489. }
  13490. }
  13491. else {
  13492. this.renderReplacedDeclarations(code, options);
  13493. }
  13494. }
  13495. applyDeoptimizations() { }
  13496. renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, systemPatternExports, options) {
  13497. if (code.original.charCodeAt(this.end - 1) === 59 /*";"*/) {
  13498. code.remove(this.end - 1, this.end);
  13499. }
  13500. separatorString += ';';
  13501. if (lastSeparatorPos === null) {
  13502. code.appendLeft(renderedContentEnd, separatorString);
  13503. }
  13504. else {
  13505. if (code.original.charCodeAt(actualContentEnd - 1) === 10 /*"\n"*/ &&
  13506. (code.original.charCodeAt(this.end) === 10 /*"\n"*/ ||
  13507. code.original.charCodeAt(this.end) === 13) /*"\r"*/) {
  13508. actualContentEnd--;
  13509. if (code.original.charCodeAt(actualContentEnd) === 13 /*"\r"*/) {
  13510. actualContentEnd--;
  13511. }
  13512. }
  13513. if (actualContentEnd === lastSeparatorPos + 1) {
  13514. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString);
  13515. }
  13516. else {
  13517. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  13518. code.remove(actualContentEnd, renderedContentEnd);
  13519. }
  13520. }
  13521. if (systemPatternExports.length > 0) {
  13522. code.appendLeft(renderedContentEnd, ` ${getSystemExportStatement(systemPatternExports, options)};`);
  13523. }
  13524. }
  13525. renderReplacedDeclarations(code, options) {
  13526. const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.declarations, code, this.start + this.kind.length, this.end - (code.original.charCodeAt(this.end - 1) === 59 /*";"*/ ? 1 : 0));
  13527. let actualContentEnd, renderedContentEnd;
  13528. renderedContentEnd = findNonWhiteSpace(code.original, this.start + this.kind.length);
  13529. let lastSeparatorPos = renderedContentEnd - 1;
  13530. code.remove(this.start, lastSeparatorPos);
  13531. let isInDeclaration = false;
  13532. let hasRenderedContent = false;
  13533. let separatorString = '', leadingString, nextSeparatorString;
  13534. const aggregatedSystemExports = [];
  13535. const singleSystemExport = gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports);
  13536. for (const { node, start, separator, contentEnd, end } of separatedNodes) {
  13537. if (!node.included) {
  13538. code.remove(start, end);
  13539. continue;
  13540. }
  13541. node.render(code, options);
  13542. leadingString = '';
  13543. nextSeparatorString = '';
  13544. if (!node.id.included ||
  13545. (node.id instanceof Identifier &&
  13546. isReassignedExportsMember(node.id.variable, options.exportNamesByVariable))) {
  13547. if (hasRenderedContent) {
  13548. separatorString += ';';
  13549. }
  13550. isInDeclaration = false;
  13551. }
  13552. else {
  13553. if (singleSystemExport && singleSystemExport === node.id.variable) {
  13554. const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', node.id.end);
  13555. renderSystemExportExpression(singleSystemExport, findNonWhiteSpace(code.original, operatorPos + 1), separator === null ? contentEnd : separator, code, options);
  13556. }
  13557. if (isInDeclaration) {
  13558. separatorString += ',';
  13559. }
  13560. else {
  13561. if (hasRenderedContent) {
  13562. separatorString += ';';
  13563. }
  13564. leadingString += `${this.kind} `;
  13565. isInDeclaration = true;
  13566. }
  13567. }
  13568. if (renderedContentEnd === lastSeparatorPos + 1) {
  13569. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString + leadingString);
  13570. }
  13571. else {
  13572. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  13573. code.appendLeft(renderedContentEnd, leadingString);
  13574. }
  13575. actualContentEnd = contentEnd;
  13576. renderedContentEnd = end;
  13577. hasRenderedContent = true;
  13578. lastSeparatorPos = separator;
  13579. separatorString = nextSeparatorString;
  13580. }
  13581. this.renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, aggregatedSystemExports, options);
  13582. }
  13583. }
  13584. function gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports) {
  13585. let singleSystemExport = null;
  13586. if (options.format === 'system') {
  13587. for (const { node } of separatedNodes) {
  13588. if (node.id instanceof Identifier &&
  13589. node.init &&
  13590. aggregatedSystemExports.length === 0 &&
  13591. options.exportNamesByVariable.get(node.id.variable)?.length === 1) {
  13592. singleSystemExport = node.id.variable;
  13593. aggregatedSystemExports.push(singleSystemExport);
  13594. }
  13595. else {
  13596. node.id.addExportedVariables(aggregatedSystemExports, options.exportNamesByVariable);
  13597. }
  13598. }
  13599. if (aggregatedSystemExports.length > 1) {
  13600. singleSystemExport = null;
  13601. }
  13602. else if (singleSystemExport) {
  13603. aggregatedSystemExports.length = 0;
  13604. }
  13605. }
  13606. return singleSystemExport;
  13607. }
  13608. class WhileStatement extends NodeBase {
  13609. hasEffects(context) {
  13610. if (this.test.hasEffects(context))
  13611. return true;
  13612. return hasLoopBodyEffects(context, this.body);
  13613. }
  13614. include(context, includeChildrenRecursively) {
  13615. this.included = true;
  13616. this.test.include(context, includeChildrenRecursively);
  13617. includeLoopBody(context, this.body, includeChildrenRecursively);
  13618. }
  13619. }
  13620. class YieldExpression extends NodeBase {
  13621. hasEffects(context) {
  13622. if (!this.deoptimized)
  13623. this.applyDeoptimizations();
  13624. return !(context.ignore.returnYield && !this.argument?.hasEffects(context));
  13625. }
  13626. render(code, options) {
  13627. if (this.argument) {
  13628. this.argument.render(code, options, { preventASI: true });
  13629. if (this.argument.start === this.start + 5 /* 'yield'.length */) {
  13630. code.prependLeft(this.start + 5, ' ');
  13631. }
  13632. }
  13633. }
  13634. }
  13635. const nodeConstructors = {
  13636. ArrayExpression,
  13637. ArrayPattern,
  13638. ArrowFunctionExpression,
  13639. AssignmentExpression,
  13640. AssignmentPattern,
  13641. AwaitExpression,
  13642. BinaryExpression,
  13643. BlockStatement,
  13644. BreakStatement,
  13645. CallExpression,
  13646. CatchClause,
  13647. ChainExpression,
  13648. ClassBody,
  13649. ClassDeclaration,
  13650. ClassExpression,
  13651. ConditionalExpression,
  13652. ContinueStatement,
  13653. DoWhileStatement,
  13654. EmptyStatement,
  13655. ExportAllDeclaration,
  13656. ExportDefaultDeclaration,
  13657. ExportNamedDeclaration,
  13658. ExportSpecifier,
  13659. ExpressionStatement,
  13660. ForInStatement,
  13661. ForOfStatement,
  13662. ForStatement,
  13663. FunctionDeclaration,
  13664. FunctionExpression,
  13665. Identifier,
  13666. IfStatement,
  13667. ImportAttribute,
  13668. ImportDeclaration,
  13669. ImportDefaultSpecifier,
  13670. ImportExpression,
  13671. ImportNamespaceSpecifier,
  13672. ImportSpecifier,
  13673. LabeledStatement,
  13674. Literal,
  13675. LogicalExpression,
  13676. MemberExpression,
  13677. MetaProperty,
  13678. MethodDefinition,
  13679. NewExpression,
  13680. ObjectExpression,
  13681. ObjectPattern,
  13682. PrivateIdentifier,
  13683. Program,
  13684. Property,
  13685. PropertyDefinition,
  13686. RestElement,
  13687. ReturnStatement,
  13688. SequenceExpression,
  13689. SpreadElement,
  13690. StaticBlock,
  13691. Super,
  13692. SwitchCase,
  13693. SwitchStatement,
  13694. TaggedTemplateExpression,
  13695. TemplateElement,
  13696. TemplateLiteral,
  13697. ThisExpression,
  13698. ThrowStatement,
  13699. TryStatement,
  13700. UnaryExpression,
  13701. UnknownNode,
  13702. UpdateExpression,
  13703. VariableDeclaration,
  13704. VariableDeclarator,
  13705. WhileStatement,
  13706. YieldExpression
  13707. };
  13708. const MISSING_EXPORT_SHIM_VARIABLE = '_missingExportShim';
  13709. class ExportShimVariable extends Variable {
  13710. constructor(module) {
  13711. super(MISSING_EXPORT_SHIM_VARIABLE);
  13712. this.module = module;
  13713. }
  13714. include() {
  13715. super.include();
  13716. this.module.needsExportShim = true;
  13717. }
  13718. }
  13719. class NamespaceVariable extends Variable {
  13720. constructor(context) {
  13721. super(context.getModuleName());
  13722. this.memberVariables = null;
  13723. this.mergedNamespaces = [];
  13724. this.referencedEarly = false;
  13725. this.references = [];
  13726. this.context = context;
  13727. this.module = context.module;
  13728. }
  13729. addReference(identifier) {
  13730. this.references.push(identifier);
  13731. this.name = identifier.name;
  13732. }
  13733. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  13734. if (path.length > 1 || (path.length === 1 && interaction.type === INTERACTION_CALLED)) {
  13735. const key = path[0];
  13736. if (typeof key === 'string') {
  13737. this.getMemberVariables()[key]?.deoptimizeArgumentsOnInteractionAtPath(interaction, path.slice(1), recursionTracker);
  13738. }
  13739. else {
  13740. deoptimizeInteraction(interaction);
  13741. }
  13742. }
  13743. }
  13744. deoptimizePath(path) {
  13745. if (path.length > 1) {
  13746. const key = path[0];
  13747. if (typeof key === 'string') {
  13748. this.getMemberVariables()[key]?.deoptimizePath(path.slice(1));
  13749. }
  13750. }
  13751. }
  13752. getLiteralValueAtPath(path) {
  13753. if (path[0] === SymbolToStringTag) {
  13754. return 'Module';
  13755. }
  13756. return UnknownValue;
  13757. }
  13758. getMemberVariables() {
  13759. if (this.memberVariables) {
  13760. return this.memberVariables;
  13761. }
  13762. const memberVariables = Object.create(null);
  13763. const sortedExports = [...this.context.getExports(), ...this.context.getReexports()].sort();
  13764. for (const name of sortedExports) {
  13765. if (name[0] !== '*' && name !== this.module.info.syntheticNamedExports) {
  13766. const exportedVariable = this.context.traceExport(name);
  13767. if (exportedVariable) {
  13768. memberVariables[name] = exportedVariable;
  13769. }
  13770. }
  13771. }
  13772. return (this.memberVariables = memberVariables);
  13773. }
  13774. hasEffectsOnInteractionAtPath(path, interaction, context) {
  13775. const { type } = interaction;
  13776. if (path.length === 0) {
  13777. // This can only be a call anyway
  13778. return true;
  13779. }
  13780. if (path.length === 1 && type !== INTERACTION_CALLED) {
  13781. return type === INTERACTION_ASSIGNED;
  13782. }
  13783. const key = path[0];
  13784. if (typeof key !== 'string') {
  13785. return true;
  13786. }
  13787. const memberVariable = this.getMemberVariables()[key];
  13788. return (!memberVariable ||
  13789. memberVariable.hasEffectsOnInteractionAtPath(path.slice(1), interaction, context));
  13790. }
  13791. include() {
  13792. this.included = true;
  13793. this.context.includeAllExports();
  13794. }
  13795. prepare(accessedGlobalsByScope) {
  13796. if (this.mergedNamespaces.length > 0) {
  13797. this.module.scope.addAccessedGlobals([MERGE_NAMESPACES_VARIABLE], accessedGlobalsByScope);
  13798. }
  13799. }
  13800. renderBlock(options) {
  13801. const { exportNamesByVariable, format, freeze, indent: t, namespaceToStringTag, snippets: { _, cnst, getObject, getPropertyAccess, n, s } } = options;
  13802. const memberVariables = this.getMemberVariables();
  13803. const members = Object.entries(memberVariables)
  13804. .filter(([_, variable]) => variable.included)
  13805. .map(([name, variable]) => {
  13806. if (this.referencedEarly || variable.isReassigned || variable === this) {
  13807. return [
  13808. null,
  13809. `get ${name}${_}()${_}{${_}return ${variable.getName(getPropertyAccess)}${s}${_}}`
  13810. ];
  13811. }
  13812. return [name, variable.getName(getPropertyAccess)];
  13813. });
  13814. members.unshift([null, `__proto__:${_}null`]);
  13815. let output = getObject(members, { lineBreakIndent: { base: '', t } });
  13816. if (this.mergedNamespaces.length > 0) {
  13817. const assignmentArguments = this.mergedNamespaces.map(variable => variable.getName(getPropertyAccess));
  13818. output = `/*#__PURE__*/${MERGE_NAMESPACES_VARIABLE}(${output},${_}[${assignmentArguments.join(`,${_}`)}])`;
  13819. }
  13820. else {
  13821. // The helper to merge namespaces will also take care of freezing and toStringTag
  13822. if (namespaceToStringTag) {
  13823. output = `/*#__PURE__*/Object.defineProperty(${output},${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)})`;
  13824. }
  13825. if (freeze) {
  13826. output = `/*#__PURE__*/Object.freeze(${output})`;
  13827. }
  13828. }
  13829. const name = this.getName(getPropertyAccess);
  13830. output = `${cnst} ${name}${_}=${_}${output};`;
  13831. if (format === 'system' && exportNamesByVariable.has(this)) {
  13832. output += `${n}${getSystemExportStatement([this], options)};`;
  13833. }
  13834. return output;
  13835. }
  13836. renderFirst() {
  13837. return this.referencedEarly;
  13838. }
  13839. setMergedNamespaces(mergedNamespaces) {
  13840. this.mergedNamespaces = mergedNamespaces;
  13841. const moduleExecIndex = this.context.getModuleExecIndex();
  13842. for (const identifier of this.references) {
  13843. if (identifier.context.getModuleExecIndex() <= moduleExecIndex) {
  13844. this.referencedEarly = true;
  13845. break;
  13846. }
  13847. }
  13848. }
  13849. }
  13850. NamespaceVariable.prototype.isNamespace = true;
  13851. class SyntheticNamedExportVariable extends Variable {
  13852. constructor(context, name, syntheticNamespace) {
  13853. super(name);
  13854. this.baseVariable = null;
  13855. this.context = context;
  13856. this.module = context.module;
  13857. this.syntheticNamespace = syntheticNamespace;
  13858. }
  13859. getBaseVariable() {
  13860. if (this.baseVariable)
  13861. return this.baseVariable;
  13862. let baseVariable = this.syntheticNamespace;
  13863. while (baseVariable instanceof ExportDefaultVariable ||
  13864. baseVariable instanceof SyntheticNamedExportVariable) {
  13865. if (baseVariable instanceof ExportDefaultVariable) {
  13866. const original = baseVariable.getOriginalVariable();
  13867. if (original === baseVariable)
  13868. break;
  13869. baseVariable = original;
  13870. }
  13871. if (baseVariable instanceof SyntheticNamedExportVariable) {
  13872. baseVariable = baseVariable.syntheticNamespace;
  13873. }
  13874. }
  13875. return (this.baseVariable = baseVariable);
  13876. }
  13877. getBaseVariableName() {
  13878. return this.syntheticNamespace.getBaseVariableName();
  13879. }
  13880. getName(getPropertyAccess) {
  13881. return `${this.syntheticNamespace.getName(getPropertyAccess)}${getPropertyAccess(this.name)}`;
  13882. }
  13883. include() {
  13884. this.included = true;
  13885. this.context.includeVariableInModule(this.syntheticNamespace);
  13886. }
  13887. setRenderNames(baseName, name) {
  13888. super.setRenderNames(baseName, name);
  13889. }
  13890. }
  13891. const sourceMapCache = new WeakMap();
  13892. /**
  13893. * This clears the decoded array and falls back to the encoded string form.
  13894. * Sourcemap mappings arrays can be very large and holding on to them for longer
  13895. * than is necessary leads to poor heap utilization.
  13896. */
  13897. function resetCacheToEncoded(cache) {
  13898. if (cache.encodedMappings === undefined && cache.decodedMappings) {
  13899. cache.encodedMappings = encode(cache.decodedMappings);
  13900. }
  13901. cache.decodedMappings = undefined;
  13902. }
  13903. function resetSourcemapCache(map, sourcemapChain) {
  13904. if (map) {
  13905. const cache = sourceMapCache.get(map);
  13906. if (cache) {
  13907. resetCacheToEncoded(cache);
  13908. }
  13909. }
  13910. if (!sourcemapChain) {
  13911. return;
  13912. }
  13913. for (const map of sourcemapChain) {
  13914. if (map.missing)
  13915. continue;
  13916. resetSourcemapCache(map);
  13917. }
  13918. }
  13919. function decodedSourcemap(map) {
  13920. if (!map)
  13921. return null;
  13922. if (typeof map === 'string') {
  13923. map = JSON.parse(map);
  13924. }
  13925. if (!map.mappings) {
  13926. return {
  13927. mappings: [],
  13928. names: [],
  13929. sources: [],
  13930. version: 3
  13931. };
  13932. }
  13933. const originalMappings = map.mappings;
  13934. const isAlreadyDecoded = Array.isArray(originalMappings);
  13935. const cache = {
  13936. decodedMappings: isAlreadyDecoded ? originalMappings : undefined,
  13937. encodedMappings: isAlreadyDecoded ? undefined : originalMappings
  13938. };
  13939. const decodedMap = {
  13940. ...map,
  13941. // By moving mappings behind an accessor, we can avoid unneeded computation for cases
  13942. // where the mappings field is never actually accessed. This appears to greatly reduce
  13943. // the overhead of sourcemap decoding in terms of both compute time and memory usage.
  13944. get mappings() {
  13945. if (cache.decodedMappings) {
  13946. return cache.decodedMappings;
  13947. }
  13948. // If decodedMappings doesn't exist then encodedMappings should.
  13949. // The only scenario where cache.encodedMappings should be undefined is if the map
  13950. // this was constructed from was already decoded, or if mappings was set to a new
  13951. // decoded string. In either case, this line shouldn't get hit.
  13952. cache.decodedMappings = cache.encodedMappings ? decode(cache.encodedMappings) : [];
  13953. cache.encodedMappings = undefined;
  13954. return cache.decodedMappings;
  13955. }
  13956. };
  13957. sourceMapCache.set(decodedMap, cache);
  13958. return decodedMap;
  13959. }
  13960. function getId(m) {
  13961. return m.id;
  13962. }
  13963. function getOriginalLocation(sourcemapChain, location) {
  13964. const filteredSourcemapChain = sourcemapChain.filter((sourcemap) => !sourcemap.missing);
  13965. traceSourcemap: while (filteredSourcemapChain.length > 0) {
  13966. const sourcemap = filteredSourcemapChain.pop();
  13967. const line = sourcemap.mappings[location.line - 1];
  13968. if (line) {
  13969. const filteredLine = line.filter((segment) => segment.length > 1);
  13970. const lastSegment = filteredLine[filteredLine.length - 1];
  13971. for (const segment of filteredLine) {
  13972. if (segment[0] >= location.column || segment === lastSegment) {
  13973. location = {
  13974. column: segment[3],
  13975. line: segment[2] + 1
  13976. };
  13977. continue traceSourcemap;
  13978. }
  13979. }
  13980. }
  13981. throw new Error("Can't resolve original location of error.");
  13982. }
  13983. return location;
  13984. }
  13985. function getAssertionsFromImportExpression(node) {
  13986. const assertProperty = node.arguments?.[0]?.properties.find((property) => getPropertyKey(property) === 'assert')?.value;
  13987. if (!assertProperty) {
  13988. return EMPTY_OBJECT;
  13989. }
  13990. const assertFields = assertProperty.properties
  13991. .map(property => {
  13992. const key = getPropertyKey(property);
  13993. if (typeof key === 'string' &&
  13994. typeof property.value.value === 'string') {
  13995. return [key, property.value.value];
  13996. }
  13997. return null;
  13998. })
  13999. .filter((property) => !!property);
  14000. if (assertFields.length > 0) {
  14001. return Object.fromEntries(assertFields);
  14002. }
  14003. return EMPTY_OBJECT;
  14004. }
  14005. const getPropertyKey = (property) => {
  14006. const key = property.key;
  14007. return key && (key.name || key.value);
  14008. };
  14009. function getAssertionsFromImportExportDeclaration(assertions) {
  14010. return assertions?.length
  14011. ? Object.fromEntries(assertions.map(assertion => [getPropertyKey(assertion), assertion.value.value]))
  14012. : EMPTY_OBJECT;
  14013. }
  14014. function doAssertionsDiffer(assertionA, assertionB) {
  14015. const keysA = Object.keys(assertionA);
  14016. return (keysA.length !== Object.keys(assertionB).length ||
  14017. keysA.some(key => assertionA[key] !== assertionB[key]));
  14018. }
  14019. let timers = new Map();
  14020. function getPersistedLabel(label, level) {
  14021. switch (level) {
  14022. case 1: {
  14023. return `# ${label}`;
  14024. }
  14025. case 2: {
  14026. return `## ${label}`;
  14027. }
  14028. case 3: {
  14029. return label;
  14030. }
  14031. default: {
  14032. return `${' '.repeat(level - 4)}- ${label}`;
  14033. }
  14034. }
  14035. }
  14036. function timeStartImpl(label, level = 3) {
  14037. label = getPersistedLabel(label, level);
  14038. const startMemory = process$1.memoryUsage().heapUsed;
  14039. const startTime = node_perf_hooks.performance.now();
  14040. const timer = timers.get(label);
  14041. if (timer === undefined) {
  14042. timers.set(label, {
  14043. memory: 0,
  14044. startMemory,
  14045. startTime,
  14046. time: 0,
  14047. totalMemory: 0
  14048. });
  14049. }
  14050. else {
  14051. timer.startMemory = startMemory;
  14052. timer.startTime = startTime;
  14053. }
  14054. }
  14055. function timeEndImpl(label, level = 3) {
  14056. label = getPersistedLabel(label, level);
  14057. const timer = timers.get(label);
  14058. if (timer !== undefined) {
  14059. const currentMemory = process$1.memoryUsage().heapUsed;
  14060. timer.memory += currentMemory - timer.startMemory;
  14061. timer.time += node_perf_hooks.performance.now() - timer.startTime;
  14062. timer.totalMemory = Math.max(timer.totalMemory, currentMemory);
  14063. }
  14064. }
  14065. function getTimings() {
  14066. const newTimings = {};
  14067. for (const [label, { memory, time, totalMemory }] of timers) {
  14068. newTimings[label] = [time, memory, totalMemory];
  14069. }
  14070. return newTimings;
  14071. }
  14072. let timeStart = doNothing;
  14073. let timeEnd = doNothing;
  14074. const TIMED_PLUGIN_HOOKS = [
  14075. 'augmentChunkHash',
  14076. 'buildEnd',
  14077. 'buildStart',
  14078. 'generateBundle',
  14079. 'load',
  14080. 'moduleParsed',
  14081. 'options',
  14082. 'outputOptions',
  14083. 'renderChunk',
  14084. 'renderDynamicImport',
  14085. 'renderStart',
  14086. 'resolveDynamicImport',
  14087. 'resolveFileUrl',
  14088. 'resolveId',
  14089. 'resolveImportMeta',
  14090. 'shouldTransformCachedModule',
  14091. 'transform',
  14092. 'writeBundle'
  14093. ];
  14094. function getPluginWithTimers(plugin, index) {
  14095. if (plugin._hasTimer)
  14096. return plugin;
  14097. plugin._hasTimer = true;
  14098. for (const hook of TIMED_PLUGIN_HOOKS) {
  14099. if (hook in plugin) {
  14100. let timerLabel = `plugin ${index}`;
  14101. if (plugin.name) {
  14102. timerLabel += ` (${plugin.name})`;
  14103. }
  14104. timerLabel += ` - ${hook}`;
  14105. const handler = function (...parameters) {
  14106. timeStart(timerLabel, 4);
  14107. const result = hookFunction.apply(this, parameters);
  14108. timeEnd(timerLabel, 4);
  14109. return result;
  14110. };
  14111. let hookFunction;
  14112. if (typeof plugin[hook].handler === 'function') {
  14113. hookFunction = plugin[hook].handler;
  14114. plugin[hook].handler = handler;
  14115. }
  14116. else {
  14117. hookFunction = plugin[hook];
  14118. plugin[hook] = handler;
  14119. }
  14120. }
  14121. }
  14122. return plugin;
  14123. }
  14124. function initialiseTimers(inputOptions) {
  14125. if (inputOptions.perf) {
  14126. timers = new Map();
  14127. timeStart = timeStartImpl;
  14128. timeEnd = timeEndImpl;
  14129. inputOptions.plugins = inputOptions.plugins.map(getPluginWithTimers);
  14130. }
  14131. else {
  14132. timeStart = doNothing;
  14133. timeEnd = doNothing;
  14134. }
  14135. }
  14136. function markModuleAndImpureDependenciesAsExecuted(baseModule) {
  14137. baseModule.isExecuted = true;
  14138. const modules = [baseModule];
  14139. const visitedModules = new Set();
  14140. for (const module of modules) {
  14141. for (const dependency of [...module.dependencies, ...module.implicitlyLoadedBefore]) {
  14142. if (!(dependency instanceof ExternalModule) &&
  14143. !dependency.isExecuted &&
  14144. (dependency.info.moduleSideEffects || module.implicitlyLoadedBefore.has(dependency)) &&
  14145. !visitedModules.has(dependency.id)) {
  14146. dependency.isExecuted = true;
  14147. visitedModules.add(dependency.id);
  14148. modules.push(dependency);
  14149. }
  14150. }
  14151. }
  14152. }
  14153. const MISSING_EXPORT_SHIM_DESCRIPTION = {
  14154. identifier: null,
  14155. localName: MISSING_EXPORT_SHIM_VARIABLE
  14156. };
  14157. function getVariableForExportNameRecursive(target, name, importerForSideEffects, isExportAllSearch, searchedNamesAndModules = new Map()) {
  14158. const searchedModules = searchedNamesAndModules.get(name);
  14159. if (searchedModules) {
  14160. if (searchedModules.has(target)) {
  14161. return isExportAllSearch ? [null] : error(logCircularReexport(name, target.id));
  14162. }
  14163. searchedModules.add(target);
  14164. }
  14165. else {
  14166. searchedNamesAndModules.set(name, new Set([target]));
  14167. }
  14168. return target.getVariableForExportName(name, {
  14169. importerForSideEffects,
  14170. isExportAllSearch,
  14171. searchedNamesAndModules
  14172. });
  14173. }
  14174. function getAndExtendSideEffectModules(variable, module) {
  14175. const sideEffectModules = getOrCreate(module.sideEffectDependenciesByVariable, variable, (getNewSet));
  14176. let currentVariable = variable;
  14177. const referencedVariables = new Set([currentVariable]);
  14178. while (true) {
  14179. const importingModule = currentVariable.module;
  14180. currentVariable =
  14181. currentVariable instanceof ExportDefaultVariable
  14182. ? currentVariable.getDirectOriginalVariable()
  14183. : currentVariable instanceof SyntheticNamedExportVariable
  14184. ? currentVariable.syntheticNamespace
  14185. : null;
  14186. if (!currentVariable || referencedVariables.has(currentVariable)) {
  14187. break;
  14188. }
  14189. referencedVariables.add(currentVariable);
  14190. sideEffectModules.add(importingModule);
  14191. const originalSideEffects = importingModule.sideEffectDependenciesByVariable.get(currentVariable);
  14192. if (originalSideEffects) {
  14193. for (const module of originalSideEffects) {
  14194. sideEffectModules.add(module);
  14195. }
  14196. }
  14197. }
  14198. return sideEffectModules;
  14199. }
  14200. class Module {
  14201. constructor(graph, id, options, isEntry, moduleSideEffects, syntheticNamedExports, meta, assertions) {
  14202. this.graph = graph;
  14203. this.id = id;
  14204. this.options = options;
  14205. this.alternativeReexportModules = new Map();
  14206. this.chunkFileNames = new Set();
  14207. this.chunkNames = [];
  14208. this.cycles = new Set();
  14209. this.dependencies = new Set();
  14210. this.dynamicDependencies = new Set();
  14211. this.dynamicImporters = [];
  14212. this.dynamicImports = [];
  14213. this.execIndex = Infinity;
  14214. this.implicitlyLoadedAfter = new Set();
  14215. this.implicitlyLoadedBefore = new Set();
  14216. this.importDescriptions = new Map();
  14217. this.importMetas = [];
  14218. this.importedFromNotTreeshaken = false;
  14219. this.importers = [];
  14220. this.includedDynamicImporters = [];
  14221. this.includedImports = new Set();
  14222. this.isExecuted = false;
  14223. this.isUserDefinedEntryPoint = false;
  14224. this.needsExportShim = false;
  14225. this.sideEffectDependenciesByVariable = new Map();
  14226. this.sourcesWithAssertions = new Map();
  14227. this.allExportNames = null;
  14228. this.ast = null;
  14229. this.exportAllModules = [];
  14230. this.exportAllSources = new Set();
  14231. this.exportNamesByVariable = null;
  14232. this.exportShimVariable = new ExportShimVariable(this);
  14233. this.exports = new Map();
  14234. this.namespaceReexportsByName = new Map();
  14235. this.reexportDescriptions = new Map();
  14236. this.relevantDependencies = null;
  14237. this.syntheticExports = new Map();
  14238. this.syntheticNamespace = null;
  14239. this.transformDependencies = [];
  14240. this.transitiveReexports = null;
  14241. this.excludeFromSourcemap = /\0/.test(id);
  14242. this.context = options.moduleContext(id);
  14243. this.preserveSignature = this.options.preserveEntrySignatures;
  14244. // eslint-disable-next-line @typescript-eslint/no-this-alias
  14245. const module = this;
  14246. const { dynamicImports, dynamicImporters, exportAllSources, exports, implicitlyLoadedAfter, implicitlyLoadedBefore, importers, reexportDescriptions, sourcesWithAssertions } = this;
  14247. this.info = {
  14248. assertions,
  14249. ast: null,
  14250. code: null,
  14251. get dynamicallyImportedIdResolutions() {
  14252. return dynamicImports
  14253. .map(({ argument }) => typeof argument === 'string' && module.resolvedIds[argument])
  14254. .filter(Boolean);
  14255. },
  14256. get dynamicallyImportedIds() {
  14257. // We cannot use this.dynamicDependencies because this is needed before
  14258. // dynamicDependencies are populated
  14259. return dynamicImports.map(({ id }) => id).filter((id) => id != null);
  14260. },
  14261. get dynamicImporters() {
  14262. return dynamicImporters.sort();
  14263. },
  14264. get exportedBindings() {
  14265. const exportBindings = { '.': [...exports.keys()] };
  14266. for (const [name, { source }] of reexportDescriptions) {
  14267. (exportBindings[source] ?? (exportBindings[source] = [])).push(name);
  14268. }
  14269. for (const source of exportAllSources) {
  14270. (exportBindings[source] ?? (exportBindings[source] = [])).push('*');
  14271. }
  14272. return exportBindings;
  14273. },
  14274. get exports() {
  14275. return [
  14276. ...exports.keys(),
  14277. ...reexportDescriptions.keys(),
  14278. ...[...exportAllSources].map(() => '*')
  14279. ];
  14280. },
  14281. get hasDefaultExport() {
  14282. // This information is only valid after parsing
  14283. if (!module.ast) {
  14284. return null;
  14285. }
  14286. return module.exports.has('default') || reexportDescriptions.has('default');
  14287. },
  14288. get hasModuleSideEffects() {
  14289. warnDeprecation('Accessing ModuleInfo.hasModuleSideEffects from plugins is deprecated. Please use ModuleInfo.moduleSideEffects instead.', URL_THIS_GETMODULEINFO, true, options);
  14290. return this.moduleSideEffects;
  14291. },
  14292. id,
  14293. get implicitlyLoadedAfterOneOf() {
  14294. // eslint-disable-next-line unicorn/prefer-spread
  14295. return Array.from(implicitlyLoadedAfter, getId).sort();
  14296. },
  14297. get implicitlyLoadedBefore() {
  14298. // eslint-disable-next-line unicorn/prefer-spread
  14299. return Array.from(implicitlyLoadedBefore, getId).sort();
  14300. },
  14301. get importedIdResolutions() {
  14302. // eslint-disable-next-line unicorn/prefer-spread
  14303. return Array.from(sourcesWithAssertions.keys(), source => module.resolvedIds[source]).filter(Boolean);
  14304. },
  14305. get importedIds() {
  14306. // We cannot use this.dependencies because this is needed before
  14307. // dependencies are populated
  14308. // eslint-disable-next-line unicorn/prefer-spread
  14309. return Array.from(sourcesWithAssertions.keys(), source => module.resolvedIds[source]?.id).filter(Boolean);
  14310. },
  14311. get importers() {
  14312. return importers.sort();
  14313. },
  14314. isEntry,
  14315. isExternal: false,
  14316. get isIncluded() {
  14317. if (graph.phase !== BuildPhase.GENERATE) {
  14318. return null;
  14319. }
  14320. return module.isIncluded();
  14321. },
  14322. meta: { ...meta },
  14323. moduleSideEffects,
  14324. syntheticNamedExports
  14325. };
  14326. // Hide the deprecated key so that it only warns when accessed explicitly
  14327. // eslint-disable-next-line unicorn/consistent-destructuring
  14328. Object.defineProperty(this.info, 'hasModuleSideEffects', {
  14329. enumerable: false
  14330. });
  14331. }
  14332. basename() {
  14333. const base = node_path.basename(this.id);
  14334. const extension = node_path.extname(this.id);
  14335. return makeLegal(extension ? base.slice(0, -extension.length) : base);
  14336. }
  14337. bindReferences() {
  14338. this.ast.bind();
  14339. }
  14340. error(properties, pos) {
  14341. this.addLocationToLogProps(properties, pos);
  14342. return error(properties);
  14343. }
  14344. // sum up the length of all ast nodes that are included
  14345. estimateSize() {
  14346. let size = 0;
  14347. for (const node of this.ast.body) {
  14348. if (node.included) {
  14349. size += node.end - node.start;
  14350. }
  14351. }
  14352. return size;
  14353. }
  14354. getAllExportNames() {
  14355. if (this.allExportNames) {
  14356. return this.allExportNames;
  14357. }
  14358. this.allExportNames = new Set([...this.exports.keys(), ...this.reexportDescriptions.keys()]);
  14359. for (const module of this.exportAllModules) {
  14360. if (module instanceof ExternalModule) {
  14361. this.allExportNames.add(`*${module.id}`);
  14362. continue;
  14363. }
  14364. for (const name of module.getAllExportNames()) {
  14365. if (name !== 'default')
  14366. this.allExportNames.add(name);
  14367. }
  14368. }
  14369. // We do not count the synthetic namespace as a regular export to hide it
  14370. // from entry signatures and namespace objects
  14371. if (typeof this.info.syntheticNamedExports === 'string') {
  14372. this.allExportNames.delete(this.info.syntheticNamedExports);
  14373. }
  14374. return this.allExportNames;
  14375. }
  14376. getDependenciesToBeIncluded() {
  14377. if (this.relevantDependencies)
  14378. return this.relevantDependencies;
  14379. this.relevantDependencies = new Set();
  14380. const necessaryDependencies = new Set();
  14381. const alwaysCheckedDependencies = new Set();
  14382. const dependencyVariables = new Set(this.includedImports);
  14383. if (this.info.isEntry ||
  14384. this.includedDynamicImporters.length > 0 ||
  14385. this.namespace.included ||
  14386. this.implicitlyLoadedAfter.size > 0) {
  14387. for (const exportName of [...this.getReexports(), ...this.getExports()]) {
  14388. const [exportedVariable] = this.getVariableForExportName(exportName);
  14389. if (exportedVariable?.included) {
  14390. dependencyVariables.add(exportedVariable);
  14391. }
  14392. }
  14393. }
  14394. for (let variable of dependencyVariables) {
  14395. const sideEffectDependencies = this.sideEffectDependenciesByVariable.get(variable);
  14396. if (sideEffectDependencies) {
  14397. for (const module of sideEffectDependencies) {
  14398. alwaysCheckedDependencies.add(module);
  14399. }
  14400. }
  14401. if (variable instanceof SyntheticNamedExportVariable) {
  14402. variable = variable.getBaseVariable();
  14403. }
  14404. else if (variable instanceof ExportDefaultVariable) {
  14405. variable = variable.getOriginalVariable();
  14406. }
  14407. necessaryDependencies.add(variable.module);
  14408. }
  14409. if (!this.options.treeshake || this.info.moduleSideEffects === 'no-treeshake') {
  14410. for (const dependency of this.dependencies) {
  14411. this.relevantDependencies.add(dependency);
  14412. }
  14413. }
  14414. else {
  14415. this.addRelevantSideEffectDependencies(this.relevantDependencies, necessaryDependencies, alwaysCheckedDependencies);
  14416. }
  14417. for (const dependency of necessaryDependencies) {
  14418. this.relevantDependencies.add(dependency);
  14419. }
  14420. return this.relevantDependencies;
  14421. }
  14422. getExportNamesByVariable() {
  14423. if (this.exportNamesByVariable) {
  14424. return this.exportNamesByVariable;
  14425. }
  14426. const exportNamesByVariable = new Map();
  14427. for (const exportName of this.getAllExportNames()) {
  14428. let [tracedVariable] = this.getVariableForExportName(exportName);
  14429. if (tracedVariable instanceof ExportDefaultVariable) {
  14430. tracedVariable = tracedVariable.getOriginalVariable();
  14431. }
  14432. if (!tracedVariable ||
  14433. !(tracedVariable.included || tracedVariable instanceof ExternalVariable)) {
  14434. continue;
  14435. }
  14436. const existingExportNames = exportNamesByVariable.get(tracedVariable);
  14437. if (existingExportNames) {
  14438. existingExportNames.push(exportName);
  14439. }
  14440. else {
  14441. exportNamesByVariable.set(tracedVariable, [exportName]);
  14442. }
  14443. }
  14444. return (this.exportNamesByVariable = exportNamesByVariable);
  14445. }
  14446. getExports() {
  14447. return [...this.exports.keys()];
  14448. }
  14449. getReexports() {
  14450. if (this.transitiveReexports) {
  14451. return this.transitiveReexports;
  14452. }
  14453. // to avoid infinite recursion when using circular `export * from X`
  14454. this.transitiveReexports = [];
  14455. const reexports = new Set(this.reexportDescriptions.keys());
  14456. for (const module of this.exportAllModules) {
  14457. if (module instanceof ExternalModule) {
  14458. reexports.add(`*${module.id}`);
  14459. }
  14460. else {
  14461. for (const name of [...module.getReexports(), ...module.getExports()]) {
  14462. if (name !== 'default')
  14463. reexports.add(name);
  14464. }
  14465. }
  14466. }
  14467. return (this.transitiveReexports = [...reexports]);
  14468. }
  14469. getRenderedExports() {
  14470. // only direct exports are counted here, not reexports at all
  14471. const renderedExports = [];
  14472. const removedExports = [];
  14473. for (const exportName of this.exports.keys()) {
  14474. const [variable] = this.getVariableForExportName(exportName);
  14475. (variable && variable.included ? renderedExports : removedExports).push(exportName);
  14476. }
  14477. return { removedExports, renderedExports };
  14478. }
  14479. getSyntheticNamespace() {
  14480. if (this.syntheticNamespace === null) {
  14481. this.syntheticNamespace = undefined;
  14482. [this.syntheticNamespace] = this.getVariableForExportName(typeof this.info.syntheticNamedExports === 'string'
  14483. ? this.info.syntheticNamedExports
  14484. : 'default', { onlyExplicit: true });
  14485. }
  14486. if (!this.syntheticNamespace) {
  14487. return error(logSyntheticNamedExportsNeedNamespaceExport(this.id, this.info.syntheticNamedExports));
  14488. }
  14489. return this.syntheticNamespace;
  14490. }
  14491. getVariableForExportName(name, { importerForSideEffects, isExportAllSearch, onlyExplicit, searchedNamesAndModules } = EMPTY_OBJECT) {
  14492. if (name[0] === '*') {
  14493. if (name.length === 1) {
  14494. // export * from './other'
  14495. return [this.namespace];
  14496. }
  14497. // export * from 'external'
  14498. const module = this.graph.modulesById.get(name.slice(1));
  14499. return module.getVariableForExportName('*');
  14500. }
  14501. // export { foo } from './other'
  14502. const reexportDeclaration = this.reexportDescriptions.get(name);
  14503. if (reexportDeclaration) {
  14504. const [variable] = getVariableForExportNameRecursive(reexportDeclaration.module, reexportDeclaration.localName, importerForSideEffects, false, searchedNamesAndModules);
  14505. if (!variable) {
  14506. return this.error(logMissingExport(reexportDeclaration.localName, this.id, reexportDeclaration.module.id), reexportDeclaration.start);
  14507. }
  14508. if (importerForSideEffects) {
  14509. setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
  14510. if (this.info.moduleSideEffects) {
  14511. getOrCreate(importerForSideEffects.sideEffectDependenciesByVariable, variable, (getNewSet)).add(this);
  14512. }
  14513. }
  14514. return [variable];
  14515. }
  14516. const exportDeclaration = this.exports.get(name);
  14517. if (exportDeclaration) {
  14518. if (exportDeclaration === MISSING_EXPORT_SHIM_DESCRIPTION) {
  14519. return [this.exportShimVariable];
  14520. }
  14521. const name = exportDeclaration.localName;
  14522. const variable = this.traceVariable(name, {
  14523. importerForSideEffects,
  14524. searchedNamesAndModules
  14525. });
  14526. if (importerForSideEffects) {
  14527. setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
  14528. getOrCreate(importerForSideEffects.sideEffectDependenciesByVariable, variable, (getNewSet)).add(this);
  14529. }
  14530. return [variable];
  14531. }
  14532. if (onlyExplicit) {
  14533. return [null];
  14534. }
  14535. if (name !== 'default') {
  14536. const foundNamespaceReexport = this.namespaceReexportsByName.get(name) ??
  14537. this.getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules);
  14538. this.namespaceReexportsByName.set(name, foundNamespaceReexport);
  14539. if (foundNamespaceReexport[0]) {
  14540. return foundNamespaceReexport;
  14541. }
  14542. }
  14543. if (this.info.syntheticNamedExports) {
  14544. return [
  14545. getOrCreate(this.syntheticExports, name, () => new SyntheticNamedExportVariable(this.astContext, name, this.getSyntheticNamespace()))
  14546. ];
  14547. }
  14548. // we don't want to create shims when we are just
  14549. // probing export * modules for exports
  14550. if (!isExportAllSearch && this.options.shimMissingExports) {
  14551. this.shimMissingExport(name);
  14552. return [this.exportShimVariable];
  14553. }
  14554. return [null];
  14555. }
  14556. hasEffects() {
  14557. return this.info.moduleSideEffects === 'no-treeshake' || this.ast.hasCachedEffects();
  14558. }
  14559. include() {
  14560. const context = createInclusionContext();
  14561. if (this.ast.shouldBeIncluded(context))
  14562. this.ast.include(context, false);
  14563. }
  14564. includeAllExports(includeNamespaceMembers) {
  14565. if (!this.isExecuted) {
  14566. markModuleAndImpureDependenciesAsExecuted(this);
  14567. this.graph.needsTreeshakingPass = true;
  14568. }
  14569. for (const exportName of this.exports.keys()) {
  14570. if (includeNamespaceMembers || exportName !== this.info.syntheticNamedExports) {
  14571. const variable = this.getVariableForExportName(exportName)[0];
  14572. variable.deoptimizePath(UNKNOWN_PATH);
  14573. if (!variable.included) {
  14574. this.includeVariable(variable);
  14575. }
  14576. }
  14577. }
  14578. for (const name of this.getReexports()) {
  14579. const [variable] = this.getVariableForExportName(name);
  14580. if (variable) {
  14581. variable.deoptimizePath(UNKNOWN_PATH);
  14582. if (!variable.included) {
  14583. this.includeVariable(variable);
  14584. }
  14585. if (variable instanceof ExternalVariable) {
  14586. variable.module.reexported = true;
  14587. }
  14588. }
  14589. }
  14590. if (includeNamespaceMembers) {
  14591. this.namespace.setMergedNamespaces(this.includeAndGetAdditionalMergedNamespaces());
  14592. }
  14593. }
  14594. includeAllInBundle() {
  14595. this.ast.include(createInclusionContext(), true);
  14596. this.includeAllExports(false);
  14597. }
  14598. includeExportsByNames(names) {
  14599. if (!this.isExecuted) {
  14600. markModuleAndImpureDependenciesAsExecuted(this);
  14601. this.graph.needsTreeshakingPass = true;
  14602. }
  14603. let includeNamespaceMembers = false;
  14604. for (const name of names) {
  14605. const variable = this.getVariableForExportName(name)[0];
  14606. if (variable) {
  14607. variable.deoptimizePath(UNKNOWN_PATH);
  14608. if (!variable.included) {
  14609. this.includeVariable(variable);
  14610. }
  14611. }
  14612. if (!this.exports.has(name) && !this.reexportDescriptions.has(name)) {
  14613. includeNamespaceMembers = true;
  14614. }
  14615. }
  14616. if (includeNamespaceMembers) {
  14617. this.namespace.setMergedNamespaces(this.includeAndGetAdditionalMergedNamespaces());
  14618. }
  14619. }
  14620. isIncluded() {
  14621. // Modules where this.ast is missing have been loaded via this.load and are
  14622. // not yet fully processed, hence they cannot be included.
  14623. return (this.ast &&
  14624. (this.ast.included ||
  14625. this.namespace.included ||
  14626. this.importedFromNotTreeshaken ||
  14627. this.exportShimVariable.included));
  14628. }
  14629. linkImports() {
  14630. this.addModulesToImportDescriptions(this.importDescriptions);
  14631. this.addModulesToImportDescriptions(this.reexportDescriptions);
  14632. const externalExportAllModules = [];
  14633. for (const source of this.exportAllSources) {
  14634. const module = this.graph.modulesById.get(this.resolvedIds[source].id);
  14635. if (module instanceof ExternalModule) {
  14636. externalExportAllModules.push(module);
  14637. continue;
  14638. }
  14639. this.exportAllModules.push(module);
  14640. }
  14641. this.exportAllModules.push(...externalExportAllModules);
  14642. }
  14643. log(level, properties, pos) {
  14644. this.addLocationToLogProps(properties, pos);
  14645. this.options.onLog(level, properties);
  14646. }
  14647. render(options) {
  14648. const source = this.magicString.clone();
  14649. this.ast.render(source, options);
  14650. source.trim();
  14651. const { usesTopLevelAwait } = this.astContext;
  14652. if (usesTopLevelAwait && options.format !== 'es' && options.format !== 'system') {
  14653. return error(logInvalidFormatForTopLevelAwait(this.id, options.format));
  14654. }
  14655. return { source, usesTopLevelAwait };
  14656. }
  14657. setSource({ ast, code, customTransformCache, originalCode, originalSourcemap, resolvedIds, sourcemapChain, transformDependencies, transformFiles, ...moduleOptions }) {
  14658. timeStart('generate ast', 3);
  14659. this.info.code = code;
  14660. this.originalCode = originalCode;
  14661. // We need to call decodedSourcemap on the input in case they were hydrated from json in the cache and don't
  14662. // have the lazy evaluation cache configured. Right now this isn't enforced by the type system because the
  14663. // RollupCache stores `ExistingDecodedSourcemap` instead of `ExistingRawSourcemap`
  14664. this.originalSourcemap = decodedSourcemap(originalSourcemap);
  14665. this.sourcemapChain = sourcemapChain.map(mapOrMissing => mapOrMissing.missing ? mapOrMissing : decodedSourcemap(mapOrMissing));
  14666. // If coming from cache and this value is already fully decoded, we want to re-encode here to save memory.
  14667. resetSourcemapCache(this.originalSourcemap, this.sourcemapChain);
  14668. if (transformFiles) {
  14669. this.transformFiles = transformFiles;
  14670. }
  14671. this.transformDependencies = transformDependencies;
  14672. this.customTransformCache = customTransformCache;
  14673. this.updateOptions(moduleOptions);
  14674. const moduleAst = ast ?? this.tryParse();
  14675. timeEnd('generate ast', 3);
  14676. timeStart('analyze ast', 3);
  14677. this.resolvedIds = resolvedIds ?? Object.create(null);
  14678. // By default, `id` is the file name. Custom resolvers and loaders
  14679. // can change that, but it makes sense to use it for the source file name
  14680. const fileName = this.id;
  14681. this.magicString = new MagicString(code, {
  14682. filename: (this.excludeFromSourcemap ? null : fileName),
  14683. indentExclusionRanges: []
  14684. });
  14685. this.astContext = {
  14686. addDynamicImport: this.addDynamicImport.bind(this),
  14687. addExport: this.addExport.bind(this),
  14688. addImport: this.addImport.bind(this),
  14689. addImportMeta: this.addImportMeta.bind(this),
  14690. code,
  14691. deoptimizationTracker: this.graph.deoptimizationTracker,
  14692. error: this.error.bind(this),
  14693. fileName,
  14694. getExports: this.getExports.bind(this),
  14695. getModuleExecIndex: () => this.execIndex,
  14696. getModuleName: this.basename.bind(this),
  14697. getNodeConstructor: (name) => nodeConstructors[name] || nodeConstructors.UnknownNode,
  14698. getReexports: this.getReexports.bind(this),
  14699. importDescriptions: this.importDescriptions,
  14700. includeAllExports: () => this.includeAllExports(true),
  14701. includeDynamicImport: this.includeDynamicImport.bind(this),
  14702. includeVariableInModule: this.includeVariableInModule.bind(this),
  14703. log: this.log.bind(this),
  14704. magicString: this.magicString,
  14705. manualPureFunctions: this.graph.pureFunctions,
  14706. module: this,
  14707. moduleContext: this.context,
  14708. options: this.options,
  14709. requestTreeshakingPass: () => (this.graph.needsTreeshakingPass = true),
  14710. traceExport: (name) => this.getVariableForExportName(name)[0],
  14711. traceVariable: this.traceVariable.bind(this),
  14712. usesTopLevelAwait: false
  14713. };
  14714. this.scope = new ModuleScope(this.graph.scope, this.astContext);
  14715. this.namespace = new NamespaceVariable(this.astContext);
  14716. this.ast = new Program(moduleAst, { context: this.astContext, type: 'Module' }, this.scope);
  14717. // Assign AST directly if has existing one as there's no way to drop it from memory.
  14718. // If cache is enabled, also assign directly as otherwise it takes more CPU and memory to re-compute.
  14719. if (ast || this.options.cache !== false) {
  14720. this.info.ast = moduleAst;
  14721. }
  14722. else {
  14723. // Make lazy and apply LRU cache to not hog the memory
  14724. Object.defineProperty(this.info, 'ast', {
  14725. get: () => {
  14726. if (this.graph.astLru.has(fileName)) {
  14727. return this.graph.astLru.get(fileName);
  14728. }
  14729. else {
  14730. const parsedAst = this.tryParse();
  14731. this.graph.astLru.set(fileName, parsedAst);
  14732. return parsedAst;
  14733. }
  14734. }
  14735. });
  14736. }
  14737. timeEnd('analyze ast', 3);
  14738. }
  14739. toJSON() {
  14740. return {
  14741. assertions: this.info.assertions,
  14742. ast: this.info.ast,
  14743. code: this.info.code,
  14744. customTransformCache: this.customTransformCache,
  14745. // eslint-disable-next-line unicorn/prefer-spread
  14746. dependencies: Array.from(this.dependencies, getId),
  14747. id: this.id,
  14748. meta: this.info.meta,
  14749. moduleSideEffects: this.info.moduleSideEffects,
  14750. originalCode: this.originalCode,
  14751. originalSourcemap: this.originalSourcemap,
  14752. resolvedIds: this.resolvedIds,
  14753. sourcemapChain: this.sourcemapChain,
  14754. syntheticNamedExports: this.info.syntheticNamedExports,
  14755. transformDependencies: this.transformDependencies,
  14756. transformFiles: this.transformFiles
  14757. };
  14758. }
  14759. traceVariable(name, { importerForSideEffects, isExportAllSearch, searchedNamesAndModules } = EMPTY_OBJECT) {
  14760. const localVariable = this.scope.variables.get(name);
  14761. if (localVariable) {
  14762. return localVariable;
  14763. }
  14764. const importDescription = this.importDescriptions.get(name);
  14765. if (importDescription) {
  14766. const otherModule = importDescription.module;
  14767. if (otherModule instanceof Module && importDescription.name === '*') {
  14768. return otherModule.namespace;
  14769. }
  14770. const [declaration] = getVariableForExportNameRecursive(otherModule, importDescription.name, importerForSideEffects || this, isExportAllSearch, searchedNamesAndModules);
  14771. if (!declaration) {
  14772. return this.error(logMissingExport(importDescription.name, this.id, otherModule.id), importDescription.start);
  14773. }
  14774. return declaration;
  14775. }
  14776. return null;
  14777. }
  14778. updateOptions({ meta, moduleSideEffects, syntheticNamedExports }) {
  14779. if (moduleSideEffects != null) {
  14780. this.info.moduleSideEffects = moduleSideEffects;
  14781. }
  14782. if (syntheticNamedExports != null) {
  14783. this.info.syntheticNamedExports = syntheticNamedExports;
  14784. }
  14785. if (meta != null) {
  14786. Object.assign(this.info.meta, meta);
  14787. }
  14788. }
  14789. addDynamicImport(node) {
  14790. let argument = node.source;
  14791. if (argument instanceof TemplateLiteral) {
  14792. if (argument.quasis.length === 1 && argument.quasis[0].value.cooked) {
  14793. argument = argument.quasis[0].value.cooked;
  14794. }
  14795. }
  14796. else if (argument instanceof Literal && typeof argument.value === 'string') {
  14797. argument = argument.value;
  14798. }
  14799. this.dynamicImports.push({ argument, id: null, node, resolution: null });
  14800. }
  14801. addExport(node) {
  14802. if (node instanceof ExportDefaultDeclaration) {
  14803. // export default foo;
  14804. this.exports.set('default', {
  14805. identifier: node.variable.getAssignedVariableName(),
  14806. localName: 'default'
  14807. });
  14808. }
  14809. else if (node instanceof ExportAllDeclaration) {
  14810. const source = node.source.value;
  14811. this.addSource(source, node);
  14812. if (node.exported) {
  14813. // export * as name from './other'
  14814. const name = node.exported.name;
  14815. this.reexportDescriptions.set(name, {
  14816. localName: '*',
  14817. module: null,
  14818. source,
  14819. start: node.start
  14820. });
  14821. }
  14822. else {
  14823. // export * from './other'
  14824. this.exportAllSources.add(source);
  14825. }
  14826. }
  14827. else if (node.source instanceof Literal) {
  14828. // export { name } from './other'
  14829. const source = node.source.value;
  14830. this.addSource(source, node);
  14831. for (const { exported, local, start } of node.specifiers) {
  14832. const name = exported instanceof Literal ? exported.value : exported.name;
  14833. this.reexportDescriptions.set(name, {
  14834. localName: local instanceof Literal ? local.value : local.name,
  14835. module: null,
  14836. source,
  14837. start
  14838. });
  14839. }
  14840. }
  14841. else if (node.declaration) {
  14842. const declaration = node.declaration;
  14843. if (declaration instanceof VariableDeclaration) {
  14844. // export var { foo, bar } = ...
  14845. // export var foo = 1, bar = 2;
  14846. for (const declarator of declaration.declarations) {
  14847. for (const localName of extractAssignedNames(declarator.id)) {
  14848. this.exports.set(localName, { identifier: null, localName });
  14849. }
  14850. }
  14851. }
  14852. else {
  14853. // export function foo () {}
  14854. const localName = declaration.id.name;
  14855. this.exports.set(localName, { identifier: null, localName });
  14856. }
  14857. }
  14858. else {
  14859. // export { foo, bar, baz }
  14860. for (const { local, exported } of node.specifiers) {
  14861. // except for reexports, local must be an Identifier
  14862. const localName = local.name;
  14863. const exportedName = exported instanceof Identifier ? exported.name : exported.value;
  14864. this.exports.set(exportedName, { identifier: null, localName });
  14865. }
  14866. }
  14867. }
  14868. addImport(node) {
  14869. const source = node.source.value;
  14870. this.addSource(source, node);
  14871. for (const specifier of node.specifiers) {
  14872. const name = specifier instanceof ImportDefaultSpecifier
  14873. ? 'default'
  14874. : specifier instanceof ImportNamespaceSpecifier
  14875. ? '*'
  14876. : specifier.imported instanceof Identifier
  14877. ? specifier.imported.name
  14878. : specifier.imported.value;
  14879. this.importDescriptions.set(specifier.local.name, {
  14880. module: null,
  14881. name,
  14882. source,
  14883. start: specifier.start
  14884. });
  14885. }
  14886. }
  14887. addImportMeta(node) {
  14888. this.importMetas.push(node);
  14889. }
  14890. addLocationToLogProps(properties, pos) {
  14891. properties.id = this.id;
  14892. properties.pos = pos;
  14893. let code = this.info.code;
  14894. const location = locate(code, pos, { offsetLine: 1 });
  14895. if (location) {
  14896. let { column, line } = location;
  14897. try {
  14898. ({ column, line } = getOriginalLocation(this.sourcemapChain, { column, line }));
  14899. code = this.originalCode;
  14900. }
  14901. catch (error_) {
  14902. this.options.onLog(LOGLEVEL_WARN, logInvalidSourcemapForError(error_, this.id, column, line, pos));
  14903. }
  14904. augmentCodeLocation(properties, { column, line }, code, this.id);
  14905. }
  14906. }
  14907. addModulesToImportDescriptions(importDescription) {
  14908. for (const specifier of importDescription.values()) {
  14909. const { id } = this.resolvedIds[specifier.source];
  14910. specifier.module = this.graph.modulesById.get(id);
  14911. }
  14912. }
  14913. addRelevantSideEffectDependencies(relevantDependencies, necessaryDependencies, alwaysCheckedDependencies) {
  14914. const handledDependencies = new Set();
  14915. const addSideEffectDependencies = (possibleDependencies) => {
  14916. for (const dependency of possibleDependencies) {
  14917. if (handledDependencies.has(dependency)) {
  14918. continue;
  14919. }
  14920. handledDependencies.add(dependency);
  14921. if (necessaryDependencies.has(dependency)) {
  14922. relevantDependencies.add(dependency);
  14923. continue;
  14924. }
  14925. if (!(dependency.info.moduleSideEffects || alwaysCheckedDependencies.has(dependency))) {
  14926. continue;
  14927. }
  14928. if (dependency instanceof ExternalModule || dependency.hasEffects()) {
  14929. relevantDependencies.add(dependency);
  14930. continue;
  14931. }
  14932. addSideEffectDependencies(dependency.dependencies);
  14933. }
  14934. };
  14935. addSideEffectDependencies(this.dependencies);
  14936. addSideEffectDependencies(alwaysCheckedDependencies);
  14937. }
  14938. addSource(source, declaration) {
  14939. const parsedAssertions = getAssertionsFromImportExportDeclaration(declaration.assertions);
  14940. const existingAssertions = this.sourcesWithAssertions.get(source);
  14941. if (existingAssertions) {
  14942. if (doAssertionsDiffer(existingAssertions, parsedAssertions)) {
  14943. this.log(LOGLEVEL_WARN, logInconsistentImportAssertions(existingAssertions, parsedAssertions, source, this.id), declaration.start);
  14944. }
  14945. }
  14946. else {
  14947. this.sourcesWithAssertions.set(source, parsedAssertions);
  14948. }
  14949. }
  14950. getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules) {
  14951. let foundSyntheticDeclaration = null;
  14952. const foundInternalDeclarations = new Map();
  14953. const foundExternalDeclarations = new Set();
  14954. for (const module of this.exportAllModules) {
  14955. // Synthetic namespaces should not hide "regular" exports of the same name
  14956. if (module.info.syntheticNamedExports === name) {
  14957. continue;
  14958. }
  14959. const [variable, indirectExternal] = getVariableForExportNameRecursive(module, name, importerForSideEffects, true,
  14960. // We are creating a copy to handle the case where the same binding is
  14961. // imported through different namespace reexports gracefully
  14962. copyNameToModulesMap(searchedNamesAndModules));
  14963. if (module instanceof ExternalModule || indirectExternal) {
  14964. foundExternalDeclarations.add(variable);
  14965. }
  14966. else if (variable instanceof SyntheticNamedExportVariable) {
  14967. if (!foundSyntheticDeclaration) {
  14968. foundSyntheticDeclaration = variable;
  14969. }
  14970. }
  14971. else if (variable) {
  14972. foundInternalDeclarations.set(variable, module);
  14973. }
  14974. }
  14975. if (foundInternalDeclarations.size > 0) {
  14976. const foundDeclarationList = [...foundInternalDeclarations];
  14977. const usedDeclaration = foundDeclarationList[0][0];
  14978. if (foundDeclarationList.length === 1) {
  14979. return [usedDeclaration];
  14980. }
  14981. this.options.onLog(LOGLEVEL_WARN, logNamespaceConflict(name, this.id, foundDeclarationList.map(([, module]) => module.id)));
  14982. // TODO we are pretending it was not found while it should behave like "undefined"
  14983. return [null];
  14984. }
  14985. if (foundExternalDeclarations.size > 0) {
  14986. const foundDeclarationList = [...foundExternalDeclarations];
  14987. const usedDeclaration = foundDeclarationList[0];
  14988. if (foundDeclarationList.length > 1) {
  14989. this.options.onLog(LOGLEVEL_WARN, logAmbiguousExternalNamespaces(name, this.id, usedDeclaration.module.id, foundDeclarationList.map(declaration => declaration.module.id)));
  14990. }
  14991. return [usedDeclaration, true];
  14992. }
  14993. if (foundSyntheticDeclaration) {
  14994. return [foundSyntheticDeclaration];
  14995. }
  14996. return [null];
  14997. }
  14998. includeAndGetAdditionalMergedNamespaces() {
  14999. const externalNamespaces = new Set();
  15000. const syntheticNamespaces = new Set();
  15001. for (const module of [this, ...this.exportAllModules]) {
  15002. if (module instanceof ExternalModule) {
  15003. const [externalVariable] = module.getVariableForExportName('*');
  15004. externalVariable.include();
  15005. this.includedImports.add(externalVariable);
  15006. externalNamespaces.add(externalVariable);
  15007. }
  15008. else if (module.info.syntheticNamedExports) {
  15009. const syntheticNamespace = module.getSyntheticNamespace();
  15010. syntheticNamespace.include();
  15011. this.includedImports.add(syntheticNamespace);
  15012. syntheticNamespaces.add(syntheticNamespace);
  15013. }
  15014. }
  15015. return [...syntheticNamespaces, ...externalNamespaces];
  15016. }
  15017. includeDynamicImport(node) {
  15018. const resolution = this.dynamicImports.find(dynamicImport => dynamicImport.node === node).resolution;
  15019. if (resolution instanceof Module) {
  15020. resolution.includedDynamicImporters.push(this);
  15021. const importedNames = this.options.treeshake
  15022. ? node.getDeterministicImportedNames()
  15023. : undefined;
  15024. if (importedNames) {
  15025. resolution.includeExportsByNames(importedNames);
  15026. }
  15027. else {
  15028. resolution.includeAllExports(true);
  15029. }
  15030. }
  15031. }
  15032. includeVariable(variable) {
  15033. const variableModule = variable.module;
  15034. if (variable.included) {
  15035. if (variableModule instanceof Module && variableModule !== this) {
  15036. getAndExtendSideEffectModules(variable, this);
  15037. }
  15038. }
  15039. else {
  15040. variable.include();
  15041. this.graph.needsTreeshakingPass = true;
  15042. if (variableModule instanceof Module) {
  15043. if (!variableModule.isExecuted) {
  15044. markModuleAndImpureDependenciesAsExecuted(variableModule);
  15045. }
  15046. if (variableModule !== this) {
  15047. const sideEffectModules = getAndExtendSideEffectModules(variable, this);
  15048. for (const module of sideEffectModules) {
  15049. if (!module.isExecuted) {
  15050. markModuleAndImpureDependenciesAsExecuted(module);
  15051. }
  15052. }
  15053. }
  15054. }
  15055. }
  15056. }
  15057. includeVariableInModule(variable) {
  15058. this.includeVariable(variable);
  15059. const variableModule = variable.module;
  15060. if (variableModule && variableModule !== this) {
  15061. this.includedImports.add(variable);
  15062. }
  15063. }
  15064. shimMissingExport(name) {
  15065. this.options.onLog(LOGLEVEL_WARN, logShimmedExport(this.id, name));
  15066. this.exports.set(name, MISSING_EXPORT_SHIM_DESCRIPTION);
  15067. }
  15068. tryParse() {
  15069. try {
  15070. return this.graph.contextParse(this.info.code);
  15071. }
  15072. catch (error_) {
  15073. return this.error(logParseError(error_, this.id), error_.pos);
  15074. }
  15075. }
  15076. }
  15077. // if there is a cyclic import in the reexport chain, we should not
  15078. // import from the original module but from the cyclic module to not
  15079. // mess up execution order.
  15080. function setAlternativeExporterIfCyclic(variable, importer, reexporter) {
  15081. if (variable.module instanceof Module && variable.module !== reexporter) {
  15082. const exporterCycles = variable.module.cycles;
  15083. if (exporterCycles.size > 0) {
  15084. const importerCycles = reexporter.cycles;
  15085. for (const cycleSymbol of importerCycles) {
  15086. if (exporterCycles.has(cycleSymbol)) {
  15087. importer.alternativeReexportModules.set(variable, reexporter);
  15088. break;
  15089. }
  15090. }
  15091. }
  15092. }
  15093. }
  15094. const copyNameToModulesMap = (searchedNamesAndModules) => searchedNamesAndModules &&
  15095. // eslint-disable-next-line unicorn/prefer-spread
  15096. new Map(Array.from(searchedNamesAndModules, ([name, modules]) => [name, new Set(modules)]));
  15097. function removeJsExtension(name) {
  15098. return name.endsWith('.js') ? name.slice(0, -3) : name;
  15099. }
  15100. function getCompleteAmdId(options, chunkId) {
  15101. if (options.autoId) {
  15102. return `${options.basePath ? options.basePath + '/' : ''}${removeJsExtension(chunkId)}`;
  15103. }
  15104. return options.id ?? '';
  15105. }
  15106. function getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, mechanism = 'return ') {
  15107. const { _, getDirectReturnFunction, getFunctionIntro, getPropertyAccess, n, s } = snippets;
  15108. if (!namedExportsMode) {
  15109. return `${n}${n}${mechanism}${getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings, getPropertyAccess)};`;
  15110. }
  15111. let exportBlock = '';
  15112. for (const { defaultVariableName, importPath, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  15113. if (reexports && namedExportsMode) {
  15114. for (const specifier of reexports) {
  15115. if (specifier.reexported !== '*') {
  15116. const importName = getReexportedImportName(name, specifier.imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, importPath, externalLiveBindings, getPropertyAccess);
  15117. if (exportBlock)
  15118. exportBlock += n;
  15119. if (specifier.imported !== '*' && specifier.needsLiveBinding) {
  15120. const [left, right] = getDirectReturnFunction([], {
  15121. functionReturn: true,
  15122. lineBreakIndent: null,
  15123. name: null
  15124. });
  15125. exportBlock +=
  15126. `Object.defineProperty(exports,${_}'${specifier.reexported}',${_}{${n}` +
  15127. `${t}enumerable:${_}true,${n}` +
  15128. `${t}get:${_}${left}${importName}${right}${n}});`;
  15129. }
  15130. else {
  15131. exportBlock += `exports${getPropertyAccess(specifier.reexported)}${_}=${_}${importName};`;
  15132. }
  15133. }
  15134. }
  15135. }
  15136. }
  15137. for (const { exported, local } of exports) {
  15138. const lhs = `exports${getPropertyAccess(exported)}`;
  15139. const rhs = local;
  15140. if (lhs !== rhs) {
  15141. if (exportBlock)
  15142. exportBlock += n;
  15143. exportBlock += `${lhs}${_}=${_}${rhs};`;
  15144. }
  15145. }
  15146. for (const { name, reexports } of dependencies) {
  15147. if (reexports && namedExportsMode) {
  15148. for (const specifier of reexports) {
  15149. if (specifier.reexported === '*') {
  15150. if (exportBlock)
  15151. exportBlock += n;
  15152. const copyPropertyIfNecessary = `{${n}${t}if${_}(k${_}!==${_}'default'${_}&&${_}!Object.prototype.hasOwnProperty.call(exports,${_}k))${_}${getDefineProperty(name, specifier.needsLiveBinding, t, snippets)}${s}${n}}`;
  15153. exportBlock += `Object.keys(${name}).forEach(${getFunctionIntro(['k'], {
  15154. isAsync: false,
  15155. name: null
  15156. })}${copyPropertyIfNecessary});`;
  15157. }
  15158. }
  15159. }
  15160. }
  15161. if (exportBlock) {
  15162. return `${n}${n}${exportBlock}`;
  15163. }
  15164. return '';
  15165. }
  15166. function getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings, getPropertyAccess) {
  15167. if (exports.length > 0) {
  15168. return exports[0].local;
  15169. }
  15170. else {
  15171. for (const { defaultVariableName, importPath, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  15172. if (reexports) {
  15173. return getReexportedImportName(name, reexports[0].imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, importPath, externalLiveBindings, getPropertyAccess);
  15174. }
  15175. }
  15176. }
  15177. }
  15178. function getReexportedImportName(moduleVariableName, imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, moduleId, externalLiveBindings, getPropertyAccess) {
  15179. if (imported === 'default') {
  15180. if (!isChunk) {
  15181. const moduleInterop = interop(moduleId);
  15182. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  15183. ? defaultVariableName
  15184. : moduleVariableName;
  15185. return isDefaultAProperty(moduleInterop, externalLiveBindings)
  15186. ? `${variableName}${getPropertyAccess('default')}`
  15187. : variableName;
  15188. }
  15189. return depNamedExportsMode
  15190. ? `${moduleVariableName}${getPropertyAccess('default')}`
  15191. : moduleVariableName;
  15192. }
  15193. if (imported === '*') {
  15194. return (isChunk ? !depNamedExportsMode : namespaceInteropHelpersByInteropType[interop(moduleId)])
  15195. ? namespaceVariableName
  15196. : moduleVariableName;
  15197. }
  15198. return `${moduleVariableName}${getPropertyAccess(imported)}`;
  15199. }
  15200. function getEsModuleValue(getObject) {
  15201. return getObject([['value', 'true']], {
  15202. lineBreakIndent: null
  15203. });
  15204. }
  15205. function getNamespaceMarkers(hasNamedExports, addEsModule, addNamespaceToStringTag, { _, getObject }) {
  15206. if (hasNamedExports) {
  15207. if (addEsModule) {
  15208. if (addNamespaceToStringTag) {
  15209. return `Object.defineProperties(exports,${_}${getObject([
  15210. ['__esModule', getEsModuleValue(getObject)],
  15211. [null, `[Symbol.toStringTag]:${_}${getToStringTagValue(getObject)}`]
  15212. ], {
  15213. lineBreakIndent: null
  15214. })});`;
  15215. }
  15216. return `Object.defineProperty(exports,${_}'__esModule',${_}${getEsModuleValue(getObject)});`;
  15217. }
  15218. if (addNamespaceToStringTag) {
  15219. return `Object.defineProperty(exports,${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)});`;
  15220. }
  15221. }
  15222. return '';
  15223. }
  15224. const getDefineProperty = (name, needsLiveBinding, t, { _, getDirectReturnFunction, n }) => {
  15225. if (needsLiveBinding) {
  15226. const [left, right] = getDirectReturnFunction([], {
  15227. functionReturn: true,
  15228. lineBreakIndent: null,
  15229. name: null
  15230. });
  15231. return (`Object.defineProperty(exports,${_}k,${_}{${n}` +
  15232. `${t}${t}enumerable:${_}true,${n}` +
  15233. `${t}${t}get:${_}${left}${name}[k]${right}${n}${t}})`);
  15234. }
  15235. return `exports[k]${_}=${_}${name}[k]`;
  15236. };
  15237. function getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, indent, snippets) {
  15238. const { _, cnst, n } = snippets;
  15239. const neededInteropHelpers = new Set();
  15240. const interopStatements = [];
  15241. const addInteropStatement = (helperVariableName, helper, dependencyVariableName) => {
  15242. neededInteropHelpers.add(helper);
  15243. interopStatements.push(`${cnst} ${helperVariableName}${_}=${_}/*#__PURE__*/${helper}(${dependencyVariableName});`);
  15244. };
  15245. for (const { defaultVariableName, imports, importPath, isChunk, name, namedExportsMode, namespaceVariableName, reexports } of dependencies) {
  15246. if (isChunk) {
  15247. for (const { imported, reexported } of [
  15248. ...(imports || []),
  15249. ...(reexports || [])
  15250. ]) {
  15251. if (imported === '*' && reexported !== '*') {
  15252. if (!namedExportsMode) {
  15253. addInteropStatement(namespaceVariableName, INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE, name);
  15254. }
  15255. break;
  15256. }
  15257. }
  15258. }
  15259. else {
  15260. const moduleInterop = interop(importPath);
  15261. let hasDefault = false;
  15262. let hasNamespace = false;
  15263. for (const { imported, reexported } of [
  15264. ...(imports || []),
  15265. ...(reexports || [])
  15266. ]) {
  15267. let helper;
  15268. let variableName;
  15269. if (imported === 'default') {
  15270. if (!hasDefault) {
  15271. hasDefault = true;
  15272. if (defaultVariableName !== namespaceVariableName) {
  15273. variableName = defaultVariableName;
  15274. helper = defaultInteropHelpersByInteropType[moduleInterop];
  15275. }
  15276. }
  15277. }
  15278. else if (imported === '*' && reexported !== '*' && !hasNamespace) {
  15279. hasNamespace = true;
  15280. helper = namespaceInteropHelpersByInteropType[moduleInterop];
  15281. variableName = namespaceVariableName;
  15282. }
  15283. if (helper) {
  15284. addInteropStatement(variableName, helper, name);
  15285. }
  15286. }
  15287. }
  15288. }
  15289. return `${getHelpersBlock(neededInteropHelpers, accessedGlobals, indent, snippets, externalLiveBindings, freeze, namespaceToStringTag)}${interopStatements.length > 0 ? `${interopStatements.join(n)}${n}${n}` : ''}`;
  15290. }
  15291. function addJsExtension(name) {
  15292. return name.endsWith('.js') ? name : name + '.js';
  15293. }
  15294. // AMD resolution will only respect the AMD baseUrl if the .js extension is omitted.
  15295. // The assumption is that this makes sense for all relative ids:
  15296. // https://requirejs.org/docs/api.html#jsfiles
  15297. function updateExtensionForRelativeAmdId(id, forceJsExtensionForImports) {
  15298. if (id[0] !== '.') {
  15299. return id;
  15300. }
  15301. return forceJsExtensionForImports ? addJsExtension(id) : removeJsExtension(id);
  15302. }
  15303. const require$$0 = [
  15304. "assert",
  15305. "async_hooks",
  15306. "buffer",
  15307. "child_process",
  15308. "cluster",
  15309. "console",
  15310. "constants",
  15311. "crypto",
  15312. "dgram",
  15313. "diagnostics_channel",
  15314. "dns",
  15315. "domain",
  15316. "events",
  15317. "fs",
  15318. "http",
  15319. "http2",
  15320. "https",
  15321. "inspector",
  15322. "module",
  15323. "net",
  15324. "os",
  15325. "path",
  15326. "perf_hooks",
  15327. "process",
  15328. "punycode",
  15329. "querystring",
  15330. "readline",
  15331. "repl",
  15332. "stream",
  15333. "string_decoder",
  15334. "timers",
  15335. "tls",
  15336. "trace_events",
  15337. "tty",
  15338. "url",
  15339. "util",
  15340. "v8",
  15341. "vm",
  15342. "wasi",
  15343. "worker_threads",
  15344. "zlib"
  15345. ];
  15346. var _static = require$$0;
  15347. const builtinModules = /*@__PURE__*/getDefaultExportFromCjs(_static);
  15348. const nodeBuiltins = new Set([
  15349. ...builtinModules,
  15350. // TODO
  15351. // remove once builtin-modules includes PR: https://github.com/sindresorhus/builtin-modules/pull/17
  15352. 'assert/strict',
  15353. 'dns/promises',
  15354. 'fs/promises',
  15355. 'path/posix',
  15356. 'path/win32',
  15357. 'readline/promises',
  15358. 'stream/consumers',
  15359. 'stream/promises',
  15360. 'stream/web',
  15361. 'timers/promises',
  15362. 'util/types'
  15363. ]);
  15364. function warnOnBuiltins(log, dependencies) {
  15365. const externalBuiltins = dependencies
  15366. .map(({ importPath }) => importPath)
  15367. .filter(importPath => nodeBuiltins.has(importPath) || importPath.startsWith('node:'));
  15368. if (externalBuiltins.length === 0)
  15369. return;
  15370. log(LOGLEVEL_WARN, logMissingNodeBuiltins(externalBuiltins));
  15371. }
  15372. 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 }) {
  15373. warnOnBuiltins(log, dependencies);
  15374. const deps = dependencies.map(m => `'${updateExtensionForRelativeAmdId(m.importPath, amd.forceJsExtensionForImports)}'`);
  15375. const parameters = dependencies.map(m => m.name);
  15376. const { n, getNonArrowFunctionIntro, _ } = snippets;
  15377. if (namedExportsMode && hasExports) {
  15378. parameters.unshift(`exports`);
  15379. deps.unshift(`'exports'`);
  15380. }
  15381. if (accessedGlobals.has('require')) {
  15382. parameters.unshift('require');
  15383. deps.unshift(`'require'`);
  15384. }
  15385. if (accessedGlobals.has('module')) {
  15386. parameters.unshift('module');
  15387. deps.unshift(`'module'`);
  15388. }
  15389. const completeAmdId = getCompleteAmdId(amd, id);
  15390. const defineParameters = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
  15391. (deps.length > 0 ? `[${deps.join(`,${_}`)}],${_}` : ``);
  15392. const useStrict = strict ? `${_}'use strict';` : '';
  15393. magicString.prepend(`${intro}${getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets)}`);
  15394. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings);
  15395. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && (esModule === true || (esModule === 'if-default-prop' && hasDefaultExport)), isModuleFacade && namespaceToStringTag, snippets);
  15396. if (namespaceMarkers) {
  15397. namespaceMarkers = n + n + namespaceMarkers;
  15398. }
  15399. magicString
  15400. .append(`${exportBlock}${namespaceMarkers}${outro}`)
  15401. .indent(t)
  15402. // factory function should be wrapped by parentheses to avoid lazy parsing,
  15403. // cf. https://v8.dev/blog/preparser#pife
  15404. .prepend(`${amd.define}(${defineParameters}(${getNonArrowFunctionIntro(parameters, {
  15405. isAsync: false,
  15406. name: null
  15407. })}{${useStrict}${n}${n}`)
  15408. .append(`${n}${n}}));`);
  15409. }
  15410. function cjs(magicString, { accessedGlobals, dependencies, exports, hasDefaultExport, hasExports, indent: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, outro, snippets }, { compact, esModule, externalLiveBindings, freeze, interop, namespaceToStringTag, strict }) {
  15411. const { _, n } = snippets;
  15412. const useStrict = strict ? `'use strict';${n}${n}` : '';
  15413. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && (esModule === true || (esModule === 'if-default-prop' && hasDefaultExport)), isModuleFacade && namespaceToStringTag, snippets);
  15414. if (namespaceMarkers) {
  15415. namespaceMarkers += n + n;
  15416. }
  15417. const importBlock = getImportBlock$1(dependencies, snippets, compact);
  15418. const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets);
  15419. magicString.prepend(`${useStrict}${intro}${namespaceMarkers}${importBlock}${interopBlock}`);
  15420. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, `module.exports${_}=${_}`);
  15421. magicString.append(`${exportBlock}${outro}`);
  15422. }
  15423. function getImportBlock$1(dependencies, { _, cnst, n }, compact) {
  15424. let importBlock = '';
  15425. let definingVariable = false;
  15426. for (const { importPath, name, reexports, imports } of dependencies) {
  15427. if (!reexports && !imports) {
  15428. if (importBlock) {
  15429. importBlock += compact && !definingVariable ? ',' : `;${n}`;
  15430. }
  15431. definingVariable = false;
  15432. importBlock += `require('${importPath}')`;
  15433. }
  15434. else {
  15435. importBlock += compact && definingVariable ? ',' : `${importBlock ? `;${n}` : ''}${cnst} `;
  15436. definingVariable = true;
  15437. importBlock += `${name}${_}=${_}require('${importPath}')`;
  15438. }
  15439. }
  15440. if (importBlock) {
  15441. return `${importBlock};${n}${n}`;
  15442. }
  15443. return '';
  15444. }
  15445. function es(magicString, { accessedGlobals, indent: t, intro, outro, dependencies, exports, snippets }, { externalLiveBindings, freeze, namespaceToStringTag }) {
  15446. const { n } = snippets;
  15447. const importBlock = getImportBlock(dependencies, snippets);
  15448. if (importBlock.length > 0)
  15449. intro += importBlock.join(n) + n + n;
  15450. intro += getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, namespaceToStringTag);
  15451. if (intro)
  15452. magicString.prepend(intro);
  15453. const exportBlock = getExportBlock(exports, snippets);
  15454. if (exportBlock.length > 0)
  15455. magicString.append(n + n + exportBlock.join(n).trim());
  15456. if (outro)
  15457. magicString.append(outro);
  15458. magicString.trim();
  15459. }
  15460. function getImportBlock(dependencies, { _ }) {
  15461. const importBlock = [];
  15462. for (const { importPath, reexports, imports, name, assertions } of dependencies) {
  15463. const assertion = assertions ? `${_}assert${_}${assertions}` : '';
  15464. const pathWithAssertion = `'${importPath}'${assertion};`;
  15465. if (!reexports && !imports) {
  15466. importBlock.push(`import${_}${pathWithAssertion}`);
  15467. continue;
  15468. }
  15469. if (imports) {
  15470. let defaultImport = null;
  15471. let starImport = null;
  15472. const importedNames = [];
  15473. for (const specifier of imports) {
  15474. if (specifier.imported === 'default') {
  15475. defaultImport = specifier;
  15476. }
  15477. else if (specifier.imported === '*') {
  15478. starImport = specifier;
  15479. }
  15480. else {
  15481. importedNames.push(specifier);
  15482. }
  15483. }
  15484. if (starImport) {
  15485. importBlock.push(`import${_}*${_}as ${starImport.local} from${_}${pathWithAssertion}`);
  15486. }
  15487. if (defaultImport && importedNames.length === 0) {
  15488. importBlock.push(`import ${defaultImport.local} from${_}${pathWithAssertion}`);
  15489. }
  15490. else if (importedNames.length > 0) {
  15491. importBlock.push(`import ${defaultImport ? `${defaultImport.local},${_}` : ''}{${_}${importedNames
  15492. .map(specifier => specifier.imported === specifier.local
  15493. ? specifier.imported
  15494. : `${specifier.imported} as ${specifier.local}`)
  15495. .join(`,${_}`)}${_}}${_}from${_}${pathWithAssertion}`);
  15496. }
  15497. }
  15498. if (reexports) {
  15499. let starExport = null;
  15500. const namespaceReexports = [];
  15501. const namedReexports = [];
  15502. for (const specifier of reexports) {
  15503. if (specifier.reexported === '*') {
  15504. starExport = specifier;
  15505. }
  15506. else if (specifier.imported === '*') {
  15507. namespaceReexports.push(specifier);
  15508. }
  15509. else {
  15510. namedReexports.push(specifier);
  15511. }
  15512. }
  15513. if (starExport) {
  15514. importBlock.push(`export${_}*${_}from${_}${pathWithAssertion}`);
  15515. }
  15516. if (namespaceReexports.length > 0) {
  15517. if (!imports ||
  15518. !imports.some(specifier => specifier.imported === '*' && specifier.local === name)) {
  15519. importBlock.push(`import${_}*${_}as ${name} from${_}${pathWithAssertion}`);
  15520. }
  15521. for (const specifier of namespaceReexports) {
  15522. importBlock.push(`export${_}{${_}${name === specifier.reexported ? name : `${name} as ${specifier.reexported}`} };`);
  15523. }
  15524. }
  15525. if (namedReexports.length > 0) {
  15526. importBlock.push(`export${_}{${_}${namedReexports
  15527. .map(specifier => specifier.imported === specifier.reexported
  15528. ? specifier.imported
  15529. : `${specifier.imported} as ${specifier.reexported}`)
  15530. .join(`,${_}`)}${_}}${_}from${_}${pathWithAssertion}`);
  15531. }
  15532. }
  15533. }
  15534. return importBlock;
  15535. }
  15536. function getExportBlock(exports, { _, cnst }) {
  15537. const exportBlock = [];
  15538. const exportDeclaration = [];
  15539. for (const specifier of exports) {
  15540. if (specifier.expression) {
  15541. exportBlock.push(`${cnst} ${specifier.local}${_}=${_}${specifier.expression};`);
  15542. }
  15543. exportDeclaration.push(specifier.exported === specifier.local
  15544. ? specifier.local
  15545. : `${specifier.local} as ${specifier.exported}`);
  15546. }
  15547. if (exportDeclaration.length > 0) {
  15548. exportBlock.push(`export${_}{${_}${exportDeclaration.join(`,${_}`)}${_}};`);
  15549. }
  15550. return exportBlock;
  15551. }
  15552. const keypath = (keypath, getPropertyAccess) => keypath.split('.').map(getPropertyAccess).join('');
  15553. function setupNamespace(name, root, globals, { _, getPropertyAccess, s }, compact) {
  15554. const parts = name.split('.');
  15555. parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
  15556. parts.pop();
  15557. let propertyPath = root;
  15558. return (parts
  15559. .map(part => {
  15560. propertyPath += getPropertyAccess(part);
  15561. return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}${s}`;
  15562. })
  15563. .join(compact ? ',' : '\n') + (compact && parts.length > 0 ? ';' : '\n'));
  15564. }
  15565. function assignToDeepVariable(deepName, root, globals, assignment, { _, getPropertyAccess }) {
  15566. const parts = deepName.split('.');
  15567. parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
  15568. const last = parts.pop();
  15569. let propertyPath = root;
  15570. let deepAssignment = [
  15571. ...parts.map(part => {
  15572. propertyPath += getPropertyAccess(part);
  15573. return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}`;
  15574. }),
  15575. `${propertyPath}${getPropertyAccess(last)}`
  15576. ].join(`,${_}`) + `${_}=${_}${assignment}`;
  15577. if (parts.length > 0) {
  15578. deepAssignment = `(${deepAssignment})`;
  15579. }
  15580. return deepAssignment;
  15581. }
  15582. function trimEmptyImports(dependencies) {
  15583. let index = dependencies.length;
  15584. while (index--) {
  15585. const { imports, reexports } = dependencies[index];
  15586. if (imports || reexports) {
  15587. return dependencies.slice(0, index + 1);
  15588. }
  15589. }
  15590. return [];
  15591. }
  15592. 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 }) {
  15593. const { _, getNonArrowFunctionIntro, getPropertyAccess, n } = snippets;
  15594. const isNamespaced = name && name.includes('.');
  15595. const useVariableAssignment = !extend && !isNamespaced;
  15596. if (name && useVariableAssignment && !isLegal(name)) {
  15597. return error(logIllegalIdentifierAsName(name));
  15598. }
  15599. warnOnBuiltins(log, dependencies);
  15600. const external = trimEmptyImports(dependencies);
  15601. const deps = external.map(dep => dep.globalName || 'null');
  15602. const parameters = external.map(m => m.name);
  15603. if (hasExports && !name) {
  15604. log(LOGLEVEL_WARN, logMissingNameOptionForIifeExport());
  15605. }
  15606. if (namedExportsMode && hasExports) {
  15607. if (extend) {
  15608. deps.unshift(`this${keypath(name, getPropertyAccess)}${_}=${_}this${keypath(name, getPropertyAccess)}${_}||${_}{}`);
  15609. parameters.unshift('exports');
  15610. }
  15611. else {
  15612. deps.unshift('{}');
  15613. parameters.unshift('exports');
  15614. }
  15615. }
  15616. const useStrict = strict ? `${t}'use strict';${n}` : '';
  15617. const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets);
  15618. magicString.prepend(`${intro}${interopBlock}`);
  15619. let wrapperIntro = `(${getNonArrowFunctionIntro(parameters, {
  15620. isAsync: false,
  15621. name: null
  15622. })}{${n}${useStrict}${n}`;
  15623. if (hasExports) {
  15624. if (name && !(extend && namedExportsMode)) {
  15625. wrapperIntro =
  15626. (useVariableAssignment ? `var ${name}` : `this${keypath(name, getPropertyAccess)}`) +
  15627. `${_}=${_}${wrapperIntro}`;
  15628. }
  15629. if (isNamespaced) {
  15630. wrapperIntro = setupNamespace(name, 'this', globals, snippets, compact) + wrapperIntro;
  15631. }
  15632. }
  15633. let wrapperOutro = `${n}${n}})(${deps.join(`,${_}`)});`;
  15634. if (hasExports && !extend && namedExportsMode) {
  15635. wrapperOutro = `${n}${n}${t}return exports;${wrapperOutro}`;
  15636. }
  15637. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings);
  15638. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule === true || (esModule === 'if-default-prop' && hasDefaultExport), namespaceToStringTag, snippets);
  15639. if (namespaceMarkers) {
  15640. namespaceMarkers = n + n + namespaceMarkers;
  15641. }
  15642. magicString
  15643. .append(`${exportBlock}${namespaceMarkers}${outro}`)
  15644. .indent(t)
  15645. .prepend(wrapperIntro)
  15646. .append(wrapperOutro);
  15647. }
  15648. function system(magicString, { accessedGlobals, dependencies, exports, hasExports, indent: t, intro, snippets, outro, usesTopLevelAwait }, { externalLiveBindings, freeze, name, namespaceToStringTag, strict, systemNullSetters }) {
  15649. const { _, getFunctionIntro, getNonArrowFunctionIntro, n, s } = snippets;
  15650. const { importBindings, setters, starExcludes } = analyzeDependencies(dependencies, exports, t, snippets);
  15651. const registeredName = name ? `'${name}',${_}` : '';
  15652. const wrapperParameters = accessedGlobals.has('module')
  15653. ? ['exports', 'module']
  15654. : hasExports
  15655. ? ['exports']
  15656. : [];
  15657. // factory function should be wrapped by parentheses to avoid lazy parsing,
  15658. // cf. https://v8.dev/blog/preparser#pife
  15659. let wrapperStart = `System.register(${registeredName}[` +
  15660. dependencies.map(({ importPath }) => `'${importPath}'`).join(`,${_}`) +
  15661. `],${_}(${getNonArrowFunctionIntro(wrapperParameters, {
  15662. isAsync: false,
  15663. name: null
  15664. })}{${n}${t}${strict ? "'use strict';" : ''}` +
  15665. getStarExcludesBlock(starExcludes, t, snippets) +
  15666. getImportBindingsBlock(importBindings, t, snippets) +
  15667. `${n}${t}return${_}{${setters.length > 0
  15668. ? `${n}${t}${t}setters:${_}[${setters
  15669. .map(setter => setter
  15670. ? `${getFunctionIntro(['module'], {
  15671. isAsync: false,
  15672. name: null
  15673. })}{${n}${t}${t}${t}${setter}${n}${t}${t}}`
  15674. : systemNullSetters
  15675. ? `null`
  15676. : `${getFunctionIntro([], { isAsync: false, name: null })}{}`)
  15677. .join(`,${_}`)}],`
  15678. : ''}${n}`;
  15679. wrapperStart += `${t}${t}execute:${_}(${getNonArrowFunctionIntro([], {
  15680. isAsync: usesTopLevelAwait,
  15681. name: null
  15682. })}{${n}${n}`;
  15683. const wrapperEnd = `${t}${t}})${n}${t}}${s}${n}}));`;
  15684. magicString
  15685. .prepend(intro +
  15686. getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, namespaceToStringTag) +
  15687. getHoistedExportsBlock(exports, t, snippets))
  15688. .append(`${outro}${n}${n}` +
  15689. getSyntheticExportsBlock(exports, t, snippets) +
  15690. getMissingExportsBlock(exports, t, snippets))
  15691. .indent(`${t}${t}${t}`)
  15692. .append(wrapperEnd)
  15693. .prepend(wrapperStart);
  15694. }
  15695. function analyzeDependencies(dependencies, exports, t, { _, cnst, getObject, getPropertyAccess, n }) {
  15696. const importBindings = [];
  15697. const setters = [];
  15698. let starExcludes = null;
  15699. for (const { imports, reexports } of dependencies) {
  15700. const setter = [];
  15701. if (imports) {
  15702. for (const specifier of imports) {
  15703. importBindings.push(specifier.local);
  15704. if (specifier.imported === '*') {
  15705. setter.push(`${specifier.local}${_}=${_}module;`);
  15706. }
  15707. else {
  15708. setter.push(`${specifier.local}${_}=${_}module${getPropertyAccess(specifier.imported)};`);
  15709. }
  15710. }
  15711. }
  15712. if (reexports) {
  15713. const reexportedNames = [];
  15714. let hasStarReexport = false;
  15715. for (const { imported, reexported } of reexports) {
  15716. if (reexported === '*') {
  15717. hasStarReexport = true;
  15718. }
  15719. else {
  15720. reexportedNames.push([
  15721. reexported,
  15722. imported === '*' ? 'module' : `module${getPropertyAccess(imported)}`
  15723. ]);
  15724. }
  15725. }
  15726. if (reexportedNames.length > 1 || hasStarReexport) {
  15727. const exportMapping = getObject(reexportedNames, { lineBreakIndent: null });
  15728. if (hasStarReexport) {
  15729. if (!starExcludes) {
  15730. starExcludes = getStarExcludes({ dependencies, exports });
  15731. }
  15732. setter.push(`${cnst} setter${_}=${_}${exportMapping};`, `for${_}(${cnst} name in module)${_}{`, `${t}if${_}(!_starExcludes[name])${_}setter[name]${_}=${_}module[name];`, '}', 'exports(setter);');
  15733. }
  15734. else {
  15735. setter.push(`exports(${exportMapping});`);
  15736. }
  15737. }
  15738. else {
  15739. const [key, value] = reexportedNames[0];
  15740. setter.push(`exports('${key}',${_}${value});`);
  15741. }
  15742. }
  15743. setters.push(setter.join(`${n}${t}${t}${t}`));
  15744. }
  15745. return { importBindings, setters, starExcludes };
  15746. }
  15747. const getStarExcludes = ({ dependencies, exports }) => {
  15748. const starExcludes = new Set(exports.map(expt => expt.exported));
  15749. starExcludes.add('default');
  15750. for (const { reexports } of dependencies) {
  15751. if (reexports) {
  15752. for (const reexport of reexports) {
  15753. if (reexport.reexported !== '*')
  15754. starExcludes.add(reexport.reexported);
  15755. }
  15756. }
  15757. }
  15758. return starExcludes;
  15759. };
  15760. const getStarExcludesBlock = (starExcludes, t, { _, cnst, getObject, n }) => starExcludes
  15761. ? `${n}${t}${cnst} _starExcludes${_}=${_}${getObject([...starExcludes].map(property => [property, '1']), { lineBreakIndent: { base: t, t } })};`
  15762. : '';
  15763. const getImportBindingsBlock = (importBindings, t, { _, n }) => (importBindings.length > 0 ? `${n}${t}var ${importBindings.join(`,${_}`)};` : '');
  15764. const getHoistedExportsBlock = (exports, t, snippets) => getExportsBlock(exports.filter(expt => expt.hoisted).map(expt => ({ name: expt.exported, value: expt.local })), t, snippets);
  15765. function getExportsBlock(exports, t, { _, n }) {
  15766. if (exports.length === 0) {
  15767. return '';
  15768. }
  15769. if (exports.length === 1) {
  15770. return `exports('${exports[0].name}',${_}${exports[0].value});${n}${n}`;
  15771. }
  15772. return (`exports({${n}` +
  15773. exports.map(({ name, value }) => `${t}${name}:${_}${value}`).join(`,${n}`) +
  15774. `${n}});${n}${n}`);
  15775. }
  15776. const getSyntheticExportsBlock = (exports, t, snippets) => getExportsBlock(exports
  15777. .filter(expt => expt.expression)
  15778. .map(expt => ({ name: expt.exported, value: expt.local })), t, snippets);
  15779. const getMissingExportsBlock = (exports, t, snippets) => getExportsBlock(exports
  15780. .filter(expt => expt.local === MISSING_EXPORT_SHIM_VARIABLE)
  15781. .map(expt => ({ name: expt.exported, value: MISSING_EXPORT_SHIM_VARIABLE })), t, snippets);
  15782. function globalProperty(name, globalVariable, getPropertyAccess) {
  15783. if (!name)
  15784. return 'null';
  15785. return `${globalVariable}${keypath(name, getPropertyAccess)}`;
  15786. }
  15787. function safeAccess(name, globalVariable, { _, getPropertyAccess }) {
  15788. let propertyPath = globalVariable;
  15789. return name
  15790. .split('.')
  15791. .map(part => (propertyPath += getPropertyAccess(part)))
  15792. .join(`${_}&&${_}`);
  15793. }
  15794. 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 }) {
  15795. const { _, cnst, getFunctionIntro, getNonArrowFunctionIntro, getPropertyAccess, n, s } = snippets;
  15796. const factoryVariable = compact ? 'f' : 'factory';
  15797. const globalVariable = compact ? 'g' : 'global';
  15798. if (hasExports && !name) {
  15799. return error(logMissingNameOptionForUmdExport());
  15800. }
  15801. warnOnBuiltins(log, dependencies);
  15802. const amdDeps = dependencies.map(m => `'${updateExtensionForRelativeAmdId(m.importPath, amd.forceJsExtensionForImports)}'`);
  15803. const cjsDeps = dependencies.map(m => `require('${m.importPath}')`);
  15804. const trimmedImports = trimEmptyImports(dependencies);
  15805. const globalDeps = trimmedImports.map(module => globalProperty(module.globalName, globalVariable, getPropertyAccess));
  15806. const factoryParameters = trimmedImports.map(m => m.name);
  15807. if (namedExportsMode && (hasExports || noConflict)) {
  15808. amdDeps.unshift(`'exports'`);
  15809. cjsDeps.unshift(`exports`);
  15810. globalDeps.unshift(assignToDeepVariable(name, globalVariable, globals, `${extend ? `${globalProperty(name, globalVariable, getPropertyAccess)}${_}||${_}` : ''}{}`, snippets));
  15811. factoryParameters.unshift('exports');
  15812. }
  15813. const completeAmdId = getCompleteAmdId(amd, id);
  15814. const amdParameters = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
  15815. (amdDeps.length > 0 ? `[${amdDeps.join(`,${_}`)}],${_}` : ``);
  15816. const define = amd.define;
  15817. const cjsExport = !namedExportsMode && hasExports ? `module.exports${_}=${_}` : ``;
  15818. const useStrict = strict ? `${_}'use strict';${n}` : ``;
  15819. let iifeExport;
  15820. if (noConflict) {
  15821. const noConflictExportsVariable = compact ? 'e' : 'exports';
  15822. let factory;
  15823. if (!namedExportsMode && hasExports) {
  15824. factory = `${cnst} ${noConflictExportsVariable}${_}=${_}${assignToDeepVariable(name, globalVariable, globals, `${factoryVariable}(${globalDeps.join(`,${_}`)})`, snippets)};`;
  15825. }
  15826. else {
  15827. const module = globalDeps.shift();
  15828. factory =
  15829. `${cnst} ${noConflictExportsVariable}${_}=${_}${module};${n}` +
  15830. `${t}${t}${factoryVariable}(${[noConflictExportsVariable, ...globalDeps].join(`,${_}`)});`;
  15831. }
  15832. iifeExport =
  15833. `(${getFunctionIntro([], { isAsync: false, name: null })}{${n}` +
  15834. `${t}${t}${cnst} current${_}=${_}${safeAccess(name, globalVariable, snippets)};${n}` +
  15835. `${t}${t}${factory}${n}` +
  15836. `${t}${t}${noConflictExportsVariable}.noConflict${_}=${_}${getFunctionIntro([], {
  15837. isAsync: false,
  15838. name: null
  15839. })}{${_}` +
  15840. `${globalProperty(name, globalVariable, getPropertyAccess)}${_}=${_}current;${_}return ${noConflictExportsVariable}${s}${_}};${n}` +
  15841. `${t}})()`;
  15842. }
  15843. else {
  15844. iifeExport = `${factoryVariable}(${globalDeps.join(`,${_}`)})`;
  15845. if (!namedExportsMode && hasExports) {
  15846. iifeExport = assignToDeepVariable(name, globalVariable, globals, iifeExport, snippets);
  15847. }
  15848. }
  15849. const iifeNeedsGlobal = hasExports || (noConflict && namedExportsMode) || globalDeps.length > 0;
  15850. const wrapperParameters = [factoryVariable];
  15851. if (iifeNeedsGlobal) {
  15852. wrapperParameters.unshift(globalVariable);
  15853. }
  15854. const globalArgument = iifeNeedsGlobal ? `this,${_}` : '';
  15855. const iifeStart = iifeNeedsGlobal
  15856. ? `(${globalVariable}${_}=${_}typeof globalThis${_}!==${_}'undefined'${_}?${_}globalThis${_}:${_}${globalVariable}${_}||${_}self,${_}`
  15857. : '';
  15858. const iifeEnd = iifeNeedsGlobal ? ')' : '';
  15859. const cjsIntro = iifeNeedsGlobal
  15860. ? `${t}typeof exports${_}===${_}'object'${_}&&${_}typeof module${_}!==${_}'undefined'${_}?` +
  15861. `${_}${cjsExport}${factoryVariable}(${cjsDeps.join(`,${_}`)})${_}:${n}`
  15862. : '';
  15863. const wrapperIntro = `(${getNonArrowFunctionIntro(wrapperParameters, { isAsync: false, name: null })}{${n}` +
  15864. cjsIntro +
  15865. `${t}typeof ${define}${_}===${_}'function'${_}&&${_}${define}.amd${_}?${_}${define}(${amdParameters}${factoryVariable})${_}:${n}` +
  15866. `${t}${iifeStart}${iifeExport}${iifeEnd};${n}` +
  15867. // factory function should be wrapped by parentheses to avoid lazy parsing,
  15868. // cf. https://v8.dev/blog/preparser#pife
  15869. `})(${globalArgument}(${getNonArrowFunctionIntro(factoryParameters, {
  15870. isAsync: false,
  15871. name: null
  15872. })}{${useStrict}${n}`;
  15873. const wrapperOutro = n + n + '}));';
  15874. magicString.prepend(`${intro}${getInteropBlock(dependencies, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, t, snippets)}`);
  15875. const exportBlock = getExportBlock$1(exports, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings);
  15876. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule === true || (esModule === 'if-default-prop' && hasDefaultExport), namespaceToStringTag, snippets);
  15877. if (namespaceMarkers) {
  15878. namespaceMarkers = n + n + namespaceMarkers;
  15879. }
  15880. magicString
  15881. .append(`${exportBlock}${namespaceMarkers}${outro}`)
  15882. .trim()
  15883. .indent(t)
  15884. .append(wrapperOutro)
  15885. .prepend(wrapperIntro);
  15886. }
  15887. const finalisers = { amd, cjs, es, iife, system, umd };
  15888. const concatSeparator = (out, next) => (next ? `${out}\n${next}` : out);
  15889. const concatDblSeparator = (out, next) => (next ? `${out}\n\n${next}` : out);
  15890. async function createAddons(options, outputPluginDriver, chunk) {
  15891. try {
  15892. let [banner, footer, intro, outro] = await Promise.all([
  15893. outputPluginDriver.hookReduceValue('banner', options.banner(chunk), [chunk], concatSeparator),
  15894. outputPluginDriver.hookReduceValue('footer', options.footer(chunk), [chunk], concatSeparator),
  15895. outputPluginDriver.hookReduceValue('intro', options.intro(chunk), [chunk], concatDblSeparator),
  15896. outputPluginDriver.hookReduceValue('outro', options.outro(chunk), [chunk], concatDblSeparator)
  15897. ]);
  15898. if (intro)
  15899. intro += '\n\n';
  15900. if (outro)
  15901. outro = `\n\n${outro}`;
  15902. if (banner)
  15903. banner += '\n';
  15904. if (footer)
  15905. footer = '\n' + footer;
  15906. return { banner, footer, intro, outro };
  15907. }
  15908. catch (error_) {
  15909. return error(logAddonNotGenerated(error_.message, error_.hook, error_.plugin));
  15910. }
  15911. }
  15912. const DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT = {
  15913. amd: deconflictImportsOther,
  15914. cjs: deconflictImportsOther,
  15915. es: deconflictImportsEsmOrSystem,
  15916. iife: deconflictImportsOther,
  15917. system: deconflictImportsEsmOrSystem,
  15918. umd: deconflictImportsOther
  15919. };
  15920. function deconflictChunk(modules, dependenciesToBeDeconflicted, imports, usedNames, format, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports, exportNamesByVariable, accessedGlobalsByScope, includedNamespaces) {
  15921. const reversedModules = [...modules].reverse();
  15922. for (const module of reversedModules) {
  15923. module.scope.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
  15924. }
  15925. deconflictTopLevelVariables(usedNames, reversedModules, includedNamespaces);
  15926. DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT[format](usedNames, imports, dependenciesToBeDeconflicted, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports);
  15927. for (const module of reversedModules) {
  15928. module.scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  15929. }
  15930. }
  15931. function deconflictImportsEsmOrSystem(usedNames, imports, dependenciesToBeDeconflicted, _interop, preserveModules, _externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports) {
  15932. // This is needed for namespace reexports
  15933. for (const dependency of dependenciesToBeDeconflicted.dependencies) {
  15934. if (preserveModules || dependency instanceof ExternalChunk) {
  15935. dependency.variableName = getSafeName(dependency.suggestedVariableName, usedNames, null);
  15936. }
  15937. }
  15938. for (const variable of imports) {
  15939. const module = variable.module;
  15940. const name = variable.name;
  15941. if (variable.isNamespace && (preserveModules || module instanceof ExternalModule)) {
  15942. variable.setRenderNames(null, (module instanceof ExternalModule
  15943. ? externalChunkByModule.get(module)
  15944. : chunkByModule.get(module)).variableName);
  15945. }
  15946. else if (module instanceof ExternalModule && name === 'default') {
  15947. variable.setRenderNames(null, getSafeName([...module.exportedVariables].some(([exportedVariable, exportedName]) => exportedName === '*' && exportedVariable.included)
  15948. ? module.suggestedVariableName + '__default'
  15949. : module.suggestedVariableName, usedNames, variable.forbiddenNames));
  15950. }
  15951. else {
  15952. variable.setRenderNames(null, getSafeName(name, usedNames, variable.forbiddenNames));
  15953. }
  15954. }
  15955. for (const variable of syntheticExports) {
  15956. variable.setRenderNames(null, getSafeName(variable.name, usedNames, variable.forbiddenNames));
  15957. }
  15958. }
  15959. function deconflictImportsOther(usedNames, imports, { deconflictedDefault, deconflictedNamespace, dependencies }, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule) {
  15960. for (const chunk of dependencies) {
  15961. chunk.variableName = getSafeName(chunk.suggestedVariableName, usedNames, null);
  15962. }
  15963. for (const chunk of deconflictedNamespace) {
  15964. chunk.namespaceVariableName = getSafeName(`${chunk.suggestedVariableName}__namespace`, usedNames, null);
  15965. }
  15966. for (const externalModule of deconflictedDefault) {
  15967. externalModule.defaultVariableName =
  15968. deconflictedNamespace.has(externalModule) &&
  15969. canDefaultBeTakenFromNamespace(interop(externalModule.id), externalLiveBindings)
  15970. ? externalModule.namespaceVariableName
  15971. : getSafeName(`${externalModule.suggestedVariableName}__default`, usedNames, null);
  15972. }
  15973. for (const variable of imports) {
  15974. const module = variable.module;
  15975. if (module instanceof ExternalModule) {
  15976. const chunk = externalChunkByModule.get(module);
  15977. const name = variable.name;
  15978. if (name === 'default') {
  15979. const moduleInterop = interop(module.id);
  15980. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  15981. ? chunk.defaultVariableName
  15982. : chunk.variableName;
  15983. if (isDefaultAProperty(moduleInterop, externalLiveBindings)) {
  15984. variable.setRenderNames(variableName, 'default');
  15985. }
  15986. else {
  15987. variable.setRenderNames(null, variableName);
  15988. }
  15989. }
  15990. else if (name === '*') {
  15991. variable.setRenderNames(null, namespaceInteropHelpersByInteropType[interop(module.id)]
  15992. ? chunk.namespaceVariableName
  15993. : chunk.variableName);
  15994. }
  15995. else {
  15996. // if the second parameter is `null`, it uses its "name" for the property name
  15997. variable.setRenderNames(chunk.variableName, null);
  15998. }
  15999. }
  16000. else {
  16001. const chunk = chunkByModule.get(module);
  16002. if (preserveModules && variable.isNamespace) {
  16003. variable.setRenderNames(null, chunk.exportMode === 'default' ? chunk.namespaceVariableName : chunk.variableName);
  16004. }
  16005. else if (chunk.exportMode === 'default') {
  16006. variable.setRenderNames(null, chunk.variableName);
  16007. }
  16008. else {
  16009. variable.setRenderNames(chunk.variableName, chunk.getVariableExportName(variable));
  16010. }
  16011. }
  16012. }
  16013. }
  16014. function deconflictTopLevelVariables(usedNames, modules, includedNamespaces) {
  16015. for (const module of modules) {
  16016. for (const variable of module.scope.variables.values()) {
  16017. if (variable.included &&
  16018. // this will only happen for exports in some formats
  16019. !(variable.renderBaseName ||
  16020. (variable instanceof ExportDefaultVariable && variable.getOriginalVariable() !== variable))) {
  16021. variable.setRenderNames(null, getSafeName(variable.name, usedNames, variable.forbiddenNames));
  16022. }
  16023. }
  16024. if (includedNamespaces.has(module)) {
  16025. const namespace = module.namespace;
  16026. namespace.setRenderNames(null, getSafeName(namespace.name, usedNames, namespace.forbiddenNames));
  16027. }
  16028. }
  16029. }
  16030. function assignExportsToMangledNames(exports, exportsByName, exportNamesByVariable) {
  16031. let nameIndex = 0;
  16032. for (const variable of exports) {
  16033. let [exportName] = variable.name;
  16034. if (exportsByName.has(exportName)) {
  16035. do {
  16036. exportName = toBase64(++nameIndex);
  16037. // skip past leading number identifiers
  16038. if (exportName.charCodeAt(0) === 49 /* '1' */) {
  16039. nameIndex += 9 * 64 ** (exportName.length - 1);
  16040. exportName = toBase64(nameIndex);
  16041. }
  16042. } while (RESERVED_NAMES$1.has(exportName) || exportsByName.has(exportName));
  16043. }
  16044. exportsByName.set(exportName, variable);
  16045. exportNamesByVariable.set(variable, [exportName]);
  16046. }
  16047. }
  16048. function assignExportsToNames(exports, exportsByName, exportNamesByVariable) {
  16049. for (const variable of exports) {
  16050. let nameIndex = 0;
  16051. let exportName = variable.name;
  16052. while (exportsByName.has(exportName)) {
  16053. exportName = variable.name + '$' + ++nameIndex;
  16054. }
  16055. exportsByName.set(exportName, variable);
  16056. exportNamesByVariable.set(variable, [exportName]);
  16057. }
  16058. }
  16059. function getExportMode(chunk, { exports: exportMode, name, format }, facadeModuleId, log) {
  16060. const exportKeys = chunk.getExportNames();
  16061. if (exportMode === 'default') {
  16062. if (exportKeys.length !== 1 || exportKeys[0] !== 'default') {
  16063. return error(logIncompatibleExportOptionValue('default', exportKeys, facadeModuleId));
  16064. }
  16065. }
  16066. else if (exportMode === 'none' && exportKeys.length > 0) {
  16067. return error(logIncompatibleExportOptionValue('none', exportKeys, facadeModuleId));
  16068. }
  16069. if (exportMode === 'auto') {
  16070. if (exportKeys.length === 0) {
  16071. exportMode = 'none';
  16072. }
  16073. else if (exportKeys.length === 1 && exportKeys[0] === 'default') {
  16074. exportMode = 'default';
  16075. }
  16076. else {
  16077. if (format !== 'es' && format !== 'system' && exportKeys.includes('default')) {
  16078. log(LOGLEVEL_WARN, logMixedExport(facadeModuleId, name));
  16079. }
  16080. exportMode = 'named';
  16081. }
  16082. }
  16083. return exportMode;
  16084. }
  16085. function guessIndentString(code) {
  16086. const lines = code.split('\n');
  16087. const tabbed = lines.filter(line => /^\t+/.test(line));
  16088. const spaced = lines.filter(line => /^ {2,}/.test(line));
  16089. if (tabbed.length === 0 && spaced.length === 0) {
  16090. return null;
  16091. }
  16092. // More lines tabbed than spaced? Assume tabs, and
  16093. // default to tabs in the case of a tie (or nothing
  16094. // to go on)
  16095. if (tabbed.length >= spaced.length) {
  16096. return '\t';
  16097. }
  16098. // Otherwise, we need to guess the multiple
  16099. const min = spaced.reduce((previous, current) => {
  16100. const numberSpaces = /^ +/.exec(current)[0].length;
  16101. return Math.min(numberSpaces, previous);
  16102. }, Infinity);
  16103. return ' '.repeat(min);
  16104. }
  16105. function getIndentString(modules, options) {
  16106. if (options.indent !== true)
  16107. return options.indent;
  16108. for (const module of modules) {
  16109. const indent = guessIndentString(module.originalCode);
  16110. if (indent !== null)
  16111. return indent;
  16112. }
  16113. return '\t';
  16114. }
  16115. function getStaticDependencies(chunk, orderedModules, chunkByModule, externalChunkByModule) {
  16116. const staticDependencyBlocks = [];
  16117. const handledDependencies = new Set();
  16118. for (let modulePos = orderedModules.length - 1; modulePos >= 0; modulePos--) {
  16119. const module = orderedModules[modulePos];
  16120. if (!handledDependencies.has(module)) {
  16121. const staticDependencies = [];
  16122. addStaticDependencies(module, staticDependencies, handledDependencies, chunk, chunkByModule, externalChunkByModule);
  16123. staticDependencyBlocks.unshift(staticDependencies);
  16124. }
  16125. }
  16126. const dependencies = new Set();
  16127. for (const block of staticDependencyBlocks) {
  16128. for (const dependency of block) {
  16129. dependencies.add(dependency);
  16130. }
  16131. }
  16132. return dependencies;
  16133. }
  16134. function addStaticDependencies(module, staticDependencies, handledModules, chunk, chunkByModule, externalChunkByModule) {
  16135. const dependencies = module.getDependenciesToBeIncluded();
  16136. for (const dependency of dependencies) {
  16137. if (dependency instanceof ExternalModule) {
  16138. staticDependencies.push(externalChunkByModule.get(dependency));
  16139. continue;
  16140. }
  16141. const dependencyChunk = chunkByModule.get(dependency);
  16142. if (dependencyChunk !== chunk) {
  16143. staticDependencies.push(dependencyChunk);
  16144. continue;
  16145. }
  16146. if (!handledModules.has(dependency)) {
  16147. handledModules.add(dependency);
  16148. addStaticDependencies(dependency, staticDependencies, handledModules, chunk, chunkByModule, externalChunkByModule);
  16149. }
  16150. }
  16151. }
  16152. const NON_ASSET_EXTENSIONS = new Set([
  16153. '.js',
  16154. '.jsx',
  16155. '.ts',
  16156. '.tsx',
  16157. '.mjs',
  16158. '.mts',
  16159. '.cjs',
  16160. '.cts'
  16161. ]);
  16162. function getGlobalName(chunk, globals, hasExports, log) {
  16163. const globalName = typeof globals === 'function' ? globals(chunk.id) : globals[chunk.id];
  16164. if (globalName) {
  16165. return globalName;
  16166. }
  16167. if (hasExports) {
  16168. log(LOGLEVEL_WARN, logMissingGlobalName(chunk.id, chunk.variableName));
  16169. return chunk.variableName;
  16170. }
  16171. }
  16172. class Chunk {
  16173. constructor(orderedModules, inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, manualChunkAlias, getPlaceholder, bundle, inputBase, snippets) {
  16174. this.orderedModules = orderedModules;
  16175. this.inputOptions = inputOptions;
  16176. this.outputOptions = outputOptions;
  16177. this.unsetOptions = unsetOptions;
  16178. this.pluginDriver = pluginDriver;
  16179. this.modulesById = modulesById;
  16180. this.chunkByModule = chunkByModule;
  16181. this.externalChunkByModule = externalChunkByModule;
  16182. this.facadeChunkByModule = facadeChunkByModule;
  16183. this.includedNamespaces = includedNamespaces;
  16184. this.manualChunkAlias = manualChunkAlias;
  16185. this.getPlaceholder = getPlaceholder;
  16186. this.bundle = bundle;
  16187. this.inputBase = inputBase;
  16188. this.snippets = snippets;
  16189. this.entryModules = [];
  16190. this.exportMode = 'named';
  16191. this.facadeModule = null;
  16192. this.namespaceVariableName = '';
  16193. this.variableName = '';
  16194. this.accessedGlobalsByScope = new Map();
  16195. this.dependencies = new Set();
  16196. this.dynamicEntryModules = [];
  16197. this.dynamicName = null;
  16198. this.exportNamesByVariable = new Map();
  16199. this.exports = new Set();
  16200. this.exportsByName = new Map();
  16201. this.fileName = null;
  16202. this.implicitEntryModules = [];
  16203. this.implicitlyLoadedBefore = new Set();
  16204. this.imports = new Set();
  16205. this.includedDynamicImports = null;
  16206. this.includedReexportsByModule = new Map();
  16207. // This may be updated in the constructor
  16208. this.isEmpty = true;
  16209. this.name = null;
  16210. this.needsExportsShim = false;
  16211. this.preRenderedChunkInfo = null;
  16212. this.preliminaryFileName = null;
  16213. this.preliminarySourcemapFileName = null;
  16214. this.renderedChunkInfo = null;
  16215. this.renderedDependencies = null;
  16216. this.renderedModules = Object.create(null);
  16217. this.sortedExportNames = null;
  16218. this.strictFacade = false;
  16219. this.execIndex = orderedModules.length > 0 ? orderedModules[0].execIndex : Infinity;
  16220. const chunkModules = new Set(orderedModules);
  16221. for (const module of orderedModules) {
  16222. chunkByModule.set(module, this);
  16223. if (module.namespace.included && !outputOptions.preserveModules) {
  16224. includedNamespaces.add(module);
  16225. }
  16226. if (this.isEmpty && module.isIncluded()) {
  16227. this.isEmpty = false;
  16228. }
  16229. if (module.info.isEntry || outputOptions.preserveModules) {
  16230. this.entryModules.push(module);
  16231. }
  16232. for (const importer of module.includedDynamicImporters) {
  16233. if (!chunkModules.has(importer)) {
  16234. this.dynamicEntryModules.push(module);
  16235. // Modules with synthetic exports need an artificial namespace for dynamic imports
  16236. if (module.info.syntheticNamedExports) {
  16237. includedNamespaces.add(module);
  16238. this.exports.add(module.namespace);
  16239. }
  16240. }
  16241. }
  16242. if (module.implicitlyLoadedAfter.size > 0) {
  16243. this.implicitEntryModules.push(module);
  16244. }
  16245. }
  16246. this.suggestedVariableName = makeLegal(this.generateVariableName());
  16247. }
  16248. static generateFacade(inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, facadedModule, facadeName, getPlaceholder, bundle, inputBase, snippets) {
  16249. const chunk = new Chunk([], inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, null, getPlaceholder, bundle, inputBase, snippets);
  16250. chunk.assignFacadeName(facadeName, facadedModule);
  16251. if (!facadeChunkByModule.has(facadedModule)) {
  16252. facadeChunkByModule.set(facadedModule, chunk);
  16253. }
  16254. for (const dependency of facadedModule.getDependenciesToBeIncluded()) {
  16255. chunk.dependencies.add(dependency instanceof Module
  16256. ? chunkByModule.get(dependency)
  16257. : externalChunkByModule.get(dependency));
  16258. }
  16259. if (!chunk.dependencies.has(chunkByModule.get(facadedModule)) &&
  16260. facadedModule.info.moduleSideEffects &&
  16261. facadedModule.hasEffects()) {
  16262. chunk.dependencies.add(chunkByModule.get(facadedModule));
  16263. }
  16264. chunk.ensureReexportsAreAvailableForModule(facadedModule);
  16265. chunk.facadeModule = facadedModule;
  16266. chunk.strictFacade = true;
  16267. return chunk;
  16268. }
  16269. canModuleBeFacade(module, exposedVariables) {
  16270. const moduleExportNamesByVariable = module.getExportNamesByVariable();
  16271. // All exports of this chunk need to be exposed by the candidate module
  16272. for (const exposedVariable of this.exports) {
  16273. if (!moduleExportNamesByVariable.has(exposedVariable)) {
  16274. return false;
  16275. }
  16276. }
  16277. // Additionally, we need to expose namespaces of dynamic entries that are not the facade module and exports from other entry modules
  16278. for (const exposedVariable of exposedVariables) {
  16279. if (!(exposedVariable.module === module ||
  16280. moduleExportNamesByVariable.has(exposedVariable) ||
  16281. (exposedVariable instanceof SyntheticNamedExportVariable &&
  16282. moduleExportNamesByVariable.has(exposedVariable.getBaseVariable())))) {
  16283. return false;
  16284. }
  16285. }
  16286. return true;
  16287. }
  16288. finalizeChunk(code, map, sourcemapFileName, hashesByPlaceholder) {
  16289. const renderedChunkInfo = this.getRenderedChunkInfo();
  16290. const finalize = (code) => replacePlaceholders(code, hashesByPlaceholder);
  16291. const preliminaryFileName = renderedChunkInfo.fileName;
  16292. const fileName = (this.fileName = finalize(preliminaryFileName));
  16293. return {
  16294. ...renderedChunkInfo,
  16295. code,
  16296. dynamicImports: renderedChunkInfo.dynamicImports.map(finalize),
  16297. fileName,
  16298. implicitlyLoadedBefore: renderedChunkInfo.implicitlyLoadedBefore.map(finalize),
  16299. importedBindings: Object.fromEntries(Object.entries(renderedChunkInfo.importedBindings).map(([fileName, bindings]) => [
  16300. finalize(fileName),
  16301. bindings
  16302. ])),
  16303. imports: renderedChunkInfo.imports.map(finalize),
  16304. map,
  16305. preliminaryFileName,
  16306. referencedFiles: renderedChunkInfo.referencedFiles.map(finalize),
  16307. sourcemapFileName
  16308. };
  16309. }
  16310. generateExports() {
  16311. this.sortedExportNames = null;
  16312. const remainingExports = new Set(this.exports);
  16313. if (this.facadeModule !== null &&
  16314. (this.facadeModule.preserveSignature !== false || this.strictFacade)) {
  16315. const exportNamesByVariable = this.facadeModule.getExportNamesByVariable();
  16316. for (const [variable, exportNames] of exportNamesByVariable) {
  16317. this.exportNamesByVariable.set(variable, [...exportNames]);
  16318. for (const exportName of exportNames) {
  16319. this.exportsByName.set(exportName, variable);
  16320. }
  16321. remainingExports.delete(variable);
  16322. }
  16323. }
  16324. if (this.outputOptions.minifyInternalExports) {
  16325. assignExportsToMangledNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  16326. }
  16327. else {
  16328. assignExportsToNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  16329. }
  16330. if (this.outputOptions.preserveModules || (this.facadeModule && this.facadeModule.info.isEntry))
  16331. this.exportMode = getExportMode(this, this.outputOptions, this.facadeModule.id, this.inputOptions.onLog);
  16332. }
  16333. generateFacades() {
  16334. const facades = [];
  16335. const entryModules = new Set([...this.entryModules, ...this.implicitEntryModules]);
  16336. const exposedVariables = new Set(this.dynamicEntryModules.map(({ namespace }) => namespace));
  16337. for (const module of entryModules) {
  16338. if (module.preserveSignature) {
  16339. for (const exportedVariable of module.getExportNamesByVariable().keys()) {
  16340. // We need to expose all entry exports from this chunk
  16341. if (this.chunkByModule.get(exportedVariable.module) === this) {
  16342. exposedVariables.add(exportedVariable);
  16343. }
  16344. }
  16345. }
  16346. }
  16347. for (const module of entryModules) {
  16348. // eslint-disable-next-line unicorn/prefer-spread
  16349. const requiredFacades = Array.from(new Set(module.chunkNames.filter(({ isUserDefined }) => isUserDefined).map(({ name }) => name)),
  16350. // mapping must run after Set 'name' dedupe
  16351. name => ({
  16352. name
  16353. }));
  16354. if (requiredFacades.length === 0 && module.isUserDefinedEntryPoint) {
  16355. requiredFacades.push({});
  16356. }
  16357. // eslint-disable-next-line unicorn/prefer-spread
  16358. requiredFacades.push(...Array.from(module.chunkFileNames, fileName => ({ fileName })));
  16359. if (requiredFacades.length === 0) {
  16360. requiredFacades.push({});
  16361. }
  16362. if (!this.facadeModule) {
  16363. const needsStrictFacade = !this.outputOptions.preserveModules &&
  16364. (module.preserveSignature === 'strict' ||
  16365. (module.preserveSignature === 'exports-only' &&
  16366. module.getExportNamesByVariable().size > 0));
  16367. if (!needsStrictFacade || this.canModuleBeFacade(module, exposedVariables)) {
  16368. this.facadeModule = module;
  16369. this.facadeChunkByModule.set(module, this);
  16370. if (module.preserveSignature) {
  16371. this.strictFacade = needsStrictFacade;
  16372. }
  16373. this.assignFacadeName(requiredFacades.shift(), module, this.outputOptions.preserveModules);
  16374. }
  16375. }
  16376. for (const facadeName of requiredFacades) {
  16377. 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));
  16378. }
  16379. }
  16380. for (const module of this.dynamicEntryModules) {
  16381. if (module.info.syntheticNamedExports)
  16382. continue;
  16383. if (!this.facadeModule && this.canModuleBeFacade(module, exposedVariables)) {
  16384. this.facadeModule = module;
  16385. this.facadeChunkByModule.set(module, this);
  16386. this.strictFacade = true;
  16387. this.dynamicName = getChunkNameFromModule(module);
  16388. }
  16389. else if (this.facadeModule === module &&
  16390. !this.strictFacade &&
  16391. this.canModuleBeFacade(module, exposedVariables)) {
  16392. this.strictFacade = true;
  16393. }
  16394. else if (!this.facadeChunkByModule.get(module)?.strictFacade) {
  16395. this.includedNamespaces.add(module);
  16396. this.exports.add(module.namespace);
  16397. }
  16398. }
  16399. if (!this.outputOptions.preserveModules) {
  16400. this.addNecessaryImportsForFacades();
  16401. }
  16402. return facades;
  16403. }
  16404. getChunkName() {
  16405. return (this.name ?? (this.name = this.outputOptions.sanitizeFileName(this.getFallbackChunkName())));
  16406. }
  16407. getExportNames() {
  16408. return (this.sortedExportNames ?? (this.sortedExportNames = [...this.exportsByName.keys()].sort()));
  16409. }
  16410. getFileName() {
  16411. return this.fileName || this.getPreliminaryFileName().fileName;
  16412. }
  16413. getImportPath(importer) {
  16414. return escapeId(getImportPath(importer, this.getFileName(), this.outputOptions.format === 'amd' && !this.outputOptions.amd.forceJsExtensionForImports, true));
  16415. }
  16416. getPreliminaryFileName() {
  16417. if (this.preliminaryFileName) {
  16418. return this.preliminaryFileName;
  16419. }
  16420. let fileName;
  16421. let hashPlaceholder = null;
  16422. const { chunkFileNames, entryFileNames, file, format, preserveModules } = this.outputOptions;
  16423. if (file) {
  16424. fileName = node_path.basename(file);
  16425. }
  16426. else if (this.fileName === null) {
  16427. const [pattern, patternName] = preserveModules || this.facadeModule?.isUserDefinedEntryPoint
  16428. ? [entryFileNames, 'output.entryFileNames']
  16429. : [chunkFileNames, 'output.chunkFileNames'];
  16430. fileName = renderNamePattern(typeof pattern === 'function' ? pattern(this.getPreRenderedChunkInfo()) : pattern, patternName, {
  16431. format: () => format,
  16432. hash: size => hashPlaceholder || (hashPlaceholder = this.getPlaceholder(patternName, size)),
  16433. name: () => this.getChunkName()
  16434. });
  16435. if (!hashPlaceholder) {
  16436. fileName = makeUnique(fileName, this.bundle);
  16437. }
  16438. }
  16439. else {
  16440. fileName = this.fileName;
  16441. }
  16442. if (!hashPlaceholder) {
  16443. this.bundle[fileName] = FILE_PLACEHOLDER;
  16444. }
  16445. // Caching is essential to not conflict with the file name reservation above
  16446. return (this.preliminaryFileName = { fileName, hashPlaceholder });
  16447. }
  16448. getPreliminarySourcemapFileName() {
  16449. if (this.preliminarySourcemapFileName) {
  16450. return this.preliminarySourcemapFileName;
  16451. }
  16452. let sourcemapFileName = null;
  16453. let hashPlaceholder = null;
  16454. const { sourcemapFileNames, format } = this.outputOptions;
  16455. if (sourcemapFileNames) {
  16456. const [pattern, patternName] = [sourcemapFileNames, 'output.sourcemapFileNames'];
  16457. sourcemapFileName = renderNamePattern(typeof pattern === 'function' ? pattern(this.getPreRenderedChunkInfo()) : pattern, patternName, {
  16458. chunkhash: () => this.getPreliminaryFileName().hashPlaceholder || '',
  16459. format: () => format,
  16460. hash: size => hashPlaceholder || (hashPlaceholder = this.getPlaceholder(patternName, size)),
  16461. name: () => this.getChunkName()
  16462. });
  16463. if (!hashPlaceholder) {
  16464. sourcemapFileName = makeUnique(sourcemapFileName, this.bundle);
  16465. }
  16466. }
  16467. else {
  16468. return null;
  16469. }
  16470. return (this.preliminarySourcemapFileName = { fileName: sourcemapFileName, hashPlaceholder });
  16471. }
  16472. getRenderedChunkInfo() {
  16473. if (this.renderedChunkInfo) {
  16474. return this.renderedChunkInfo;
  16475. }
  16476. return (this.renderedChunkInfo = {
  16477. ...this.getPreRenderedChunkInfo(),
  16478. dynamicImports: this.getDynamicDependencies().map(resolveFileName),
  16479. fileName: this.getFileName(),
  16480. // eslint-disable-next-line unicorn/prefer-spread
  16481. implicitlyLoadedBefore: Array.from(this.implicitlyLoadedBefore, resolveFileName),
  16482. importedBindings: getImportedBindingsPerDependency(this.getRenderedDependencies(), resolveFileName),
  16483. // eslint-disable-next-line unicorn/prefer-spread
  16484. imports: Array.from(this.dependencies, resolveFileName),
  16485. modules: this.renderedModules,
  16486. referencedFiles: this.getReferencedFiles()
  16487. });
  16488. }
  16489. getVariableExportName(variable) {
  16490. if (this.outputOptions.preserveModules && variable instanceof NamespaceVariable) {
  16491. return '*';
  16492. }
  16493. return this.exportNamesByVariable.get(variable)[0];
  16494. }
  16495. link() {
  16496. this.dependencies = getStaticDependencies(this, this.orderedModules, this.chunkByModule, this.externalChunkByModule);
  16497. for (const module of this.orderedModules) {
  16498. this.addImplicitlyLoadedBeforeFromModule(module);
  16499. this.setUpChunkImportsAndExportsForModule(module);
  16500. }
  16501. }
  16502. async render() {
  16503. const { dependencies, exportMode, facadeModule, inputOptions: { onLog }, outputOptions, pluginDriver, snippets } = this;
  16504. const { format, hoistTransitiveImports, preserveModules } = outputOptions;
  16505. // for static and dynamic entry points, add transitive dependencies to this
  16506. // chunk's dependencies to avoid loading latency
  16507. if (hoistTransitiveImports && !preserveModules && facadeModule !== null) {
  16508. for (const dep of dependencies) {
  16509. if (dep instanceof Chunk)
  16510. this.inlineChunkDependencies(dep);
  16511. }
  16512. }
  16513. const preliminaryFileName = this.getPreliminaryFileName();
  16514. const preliminarySourcemapFileName = this.getPreliminarySourcemapFileName();
  16515. const { accessedGlobals, indent, magicString, renderedSource, usedModules, usesTopLevelAwait } = this.renderModules(preliminaryFileName.fileName);
  16516. const renderedDependencies = [...this.getRenderedDependencies().values()];
  16517. const renderedExports = exportMode === 'none' ? [] : this.getChunkExportDeclarations(format);
  16518. let hasExports = renderedExports.length > 0;
  16519. let hasDefaultExport = false;
  16520. for (const renderedDependence of renderedDependencies) {
  16521. const { reexports } = renderedDependence;
  16522. if (reexports?.length) {
  16523. hasExports = true;
  16524. if (!hasDefaultExport && reexports.some(reexport => reexport.reexported === 'default')) {
  16525. hasDefaultExport = true;
  16526. }
  16527. if (format === 'es') {
  16528. renderedDependence.reexports = reexports.filter(
  16529. // eslint-disable-next-line unicorn/prefer-array-some
  16530. ({ reexported }) => !renderedExports.find(({ exported }) => exported === reexported));
  16531. }
  16532. }
  16533. }
  16534. if (!hasDefaultExport) {
  16535. for (const { exported } of renderedExports) {
  16536. if (exported === 'default') {
  16537. hasDefaultExport = true;
  16538. break;
  16539. }
  16540. }
  16541. }
  16542. const { intro, outro, banner, footer } = await createAddons(outputOptions, pluginDriver, this.getRenderedChunkInfo());
  16543. finalisers[format](renderedSource, {
  16544. accessedGlobals,
  16545. dependencies: renderedDependencies,
  16546. exports: renderedExports,
  16547. hasDefaultExport,
  16548. hasExports,
  16549. id: preliminaryFileName.fileName,
  16550. indent,
  16551. intro,
  16552. isEntryFacade: preserveModules || (facadeModule !== null && facadeModule.info.isEntry),
  16553. isModuleFacade: facadeModule !== null,
  16554. log: onLog,
  16555. namedExportsMode: exportMode !== 'default',
  16556. outro,
  16557. snippets,
  16558. usesTopLevelAwait
  16559. }, outputOptions);
  16560. if (banner)
  16561. magicString.prepend(banner);
  16562. if (footer)
  16563. magicString.append(footer);
  16564. return {
  16565. chunk: this,
  16566. magicString,
  16567. preliminaryFileName,
  16568. preliminarySourcemapFileName,
  16569. usedModules
  16570. };
  16571. }
  16572. addImplicitlyLoadedBeforeFromModule(baseModule) {
  16573. const { chunkByModule, implicitlyLoadedBefore } = this;
  16574. for (const module of baseModule.implicitlyLoadedBefore) {
  16575. const chunk = chunkByModule.get(module);
  16576. if (chunk && chunk !== this) {
  16577. implicitlyLoadedBefore.add(chunk);
  16578. }
  16579. }
  16580. }
  16581. addNecessaryImportsForFacades() {
  16582. for (const [module, variables] of this.includedReexportsByModule) {
  16583. if (this.includedNamespaces.has(module)) {
  16584. for (const variable of variables) {
  16585. this.imports.add(variable);
  16586. }
  16587. }
  16588. }
  16589. }
  16590. assignFacadeName({ fileName, name }, facadedModule, preservePath) {
  16591. if (fileName) {
  16592. this.fileName = fileName;
  16593. }
  16594. else {
  16595. this.name = this.outputOptions.sanitizeFileName(name ||
  16596. (preservePath
  16597. ? this.getPreserveModulesChunkNameFromModule(facadedModule)
  16598. : getChunkNameFromModule(facadedModule)));
  16599. }
  16600. }
  16601. checkCircularDependencyImport(variable, importingModule) {
  16602. const variableModule = variable.module;
  16603. if (variableModule instanceof Module) {
  16604. const exportChunk = this.chunkByModule.get(variableModule);
  16605. let alternativeReexportModule;
  16606. do {
  16607. alternativeReexportModule = importingModule.alternativeReexportModules.get(variable);
  16608. if (alternativeReexportModule) {
  16609. const exportingChunk = this.chunkByModule.get(alternativeReexportModule);
  16610. if (exportingChunk !== exportChunk) {
  16611. this.inputOptions.onLog(LOGLEVEL_WARN, logCyclicCrossChunkReexport(
  16612. // Namespaces do not have an export name
  16613. variableModule.getExportNamesByVariable().get(variable)?.[0] || '*', variableModule.id, alternativeReexportModule.id, importingModule.id, this.outputOptions.preserveModules));
  16614. }
  16615. importingModule = alternativeReexportModule;
  16616. }
  16617. } while (alternativeReexportModule);
  16618. }
  16619. }
  16620. ensureReexportsAreAvailableForModule(module) {
  16621. const includedReexports = [];
  16622. const map = module.getExportNamesByVariable();
  16623. for (const exportedVariable of map.keys()) {
  16624. const isSynthetic = exportedVariable instanceof SyntheticNamedExportVariable;
  16625. const importedVariable = isSynthetic ? exportedVariable.getBaseVariable() : exportedVariable;
  16626. this.checkCircularDependencyImport(importedVariable, module);
  16627. // When preserving modules, we do not create namespace objects but directly
  16628. // use the actual namespaces, which would be broken by this logic.
  16629. if (!(importedVariable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
  16630. const exportingModule = importedVariable.module;
  16631. if (exportingModule instanceof Module) {
  16632. const chunk = this.chunkByModule.get(exportingModule);
  16633. if (chunk && chunk !== this) {
  16634. chunk.exports.add(importedVariable);
  16635. includedReexports.push(importedVariable);
  16636. if (isSynthetic) {
  16637. this.imports.add(importedVariable);
  16638. }
  16639. }
  16640. }
  16641. }
  16642. }
  16643. if (includedReexports.length > 0) {
  16644. this.includedReexportsByModule.set(module, includedReexports);
  16645. }
  16646. }
  16647. generateVariableName() {
  16648. if (this.manualChunkAlias) {
  16649. return this.manualChunkAlias;
  16650. }
  16651. const moduleForNaming = this.entryModules[0] ||
  16652. this.implicitEntryModules[0] ||
  16653. this.dynamicEntryModules[0] ||
  16654. this.orderedModules[this.orderedModules.length - 1];
  16655. if (moduleForNaming) {
  16656. return getChunkNameFromModule(moduleForNaming);
  16657. }
  16658. return 'chunk';
  16659. }
  16660. getChunkExportDeclarations(format) {
  16661. const exports = [];
  16662. for (const exportName of this.getExportNames()) {
  16663. if (exportName[0] === '*')
  16664. continue;
  16665. const variable = this.exportsByName.get(exportName);
  16666. if (!(variable instanceof SyntheticNamedExportVariable)) {
  16667. const module = variable.module;
  16668. if (module) {
  16669. const chunk = this.chunkByModule.get(module);
  16670. if (chunk !== this) {
  16671. if (!chunk || format !== 'es') {
  16672. continue;
  16673. }
  16674. const chunkDep = this.renderedDependencies.get(chunk);
  16675. if (!chunkDep) {
  16676. continue;
  16677. }
  16678. const { imports, reexports } = chunkDep;
  16679. const importedByReexported = reexports?.find(({ reexported }) => reexported === exportName);
  16680. const isImported = imports?.find(({ imported }) => imported === importedByReexported?.imported);
  16681. if (!isImported) {
  16682. continue;
  16683. }
  16684. }
  16685. }
  16686. }
  16687. let expression = null;
  16688. let hoisted = false;
  16689. let local = variable.getName(this.snippets.getPropertyAccess);
  16690. if (variable instanceof LocalVariable) {
  16691. for (const declaration of variable.declarations) {
  16692. if (declaration.parent instanceof FunctionDeclaration ||
  16693. (declaration instanceof ExportDefaultDeclaration &&
  16694. declaration.declaration instanceof FunctionDeclaration)) {
  16695. hoisted = true;
  16696. break;
  16697. }
  16698. }
  16699. }
  16700. else if (variable instanceof SyntheticNamedExportVariable) {
  16701. expression = local;
  16702. if (format === 'es') {
  16703. local = variable.renderName;
  16704. }
  16705. }
  16706. exports.push({
  16707. exported: exportName,
  16708. expression,
  16709. hoisted,
  16710. local
  16711. });
  16712. }
  16713. return exports;
  16714. }
  16715. getDependenciesToBeDeconflicted(addNonNamespacesAndInteropHelpers, addDependenciesWithoutBindings, interop) {
  16716. const dependencies = new Set();
  16717. const deconflictedDefault = new Set();
  16718. const deconflictedNamespace = new Set();
  16719. for (const variable of [...this.exportNamesByVariable.keys(), ...this.imports]) {
  16720. if (addNonNamespacesAndInteropHelpers || variable.isNamespace) {
  16721. const module = variable.module;
  16722. if (module instanceof ExternalModule) {
  16723. const chunk = this.externalChunkByModule.get(module);
  16724. dependencies.add(chunk);
  16725. if (addNonNamespacesAndInteropHelpers) {
  16726. if (variable.name === 'default') {
  16727. if (defaultInteropHelpersByInteropType[interop(module.id)]) {
  16728. deconflictedDefault.add(chunk);
  16729. }
  16730. }
  16731. else if (variable.name === '*' &&
  16732. namespaceInteropHelpersByInteropType[interop(module.id)]) {
  16733. deconflictedNamespace.add(chunk);
  16734. }
  16735. }
  16736. }
  16737. else {
  16738. const chunk = this.chunkByModule.get(module);
  16739. if (chunk !== this) {
  16740. dependencies.add(chunk);
  16741. if (addNonNamespacesAndInteropHelpers &&
  16742. chunk.exportMode === 'default' &&
  16743. variable.isNamespace) {
  16744. deconflictedNamespace.add(chunk);
  16745. }
  16746. }
  16747. }
  16748. }
  16749. }
  16750. if (addDependenciesWithoutBindings) {
  16751. for (const dependency of this.dependencies) {
  16752. dependencies.add(dependency);
  16753. }
  16754. }
  16755. return { deconflictedDefault, deconflictedNamespace, dependencies };
  16756. }
  16757. getDynamicDependencies() {
  16758. return this.getIncludedDynamicImports()
  16759. .map(resolvedDynamicImport => resolvedDynamicImport.facadeChunk ||
  16760. resolvedDynamicImport.chunk ||
  16761. resolvedDynamicImport.externalChunk ||
  16762. resolvedDynamicImport.resolution)
  16763. .filter((resolution) => resolution !== this &&
  16764. (resolution instanceof Chunk || resolution instanceof ExternalChunk));
  16765. }
  16766. getDynamicImportStringAndAssertions(resolution, fileName) {
  16767. if (resolution instanceof ExternalModule) {
  16768. const chunk = this.externalChunkByModule.get(resolution);
  16769. return [`'${chunk.getImportPath(fileName)}'`, chunk.getImportAssertions(this.snippets)];
  16770. }
  16771. return [
  16772. resolution || '',
  16773. (this.outputOptions.format === 'es' && this.outputOptions.externalImportAssertions) || null
  16774. ];
  16775. }
  16776. getFallbackChunkName() {
  16777. if (this.manualChunkAlias) {
  16778. return this.manualChunkAlias;
  16779. }
  16780. if (this.dynamicName) {
  16781. return this.dynamicName;
  16782. }
  16783. if (this.fileName) {
  16784. return getAliasName(this.fileName);
  16785. }
  16786. return getAliasName(this.orderedModules[this.orderedModules.length - 1].id);
  16787. }
  16788. getImportSpecifiers() {
  16789. const { interop } = this.outputOptions;
  16790. const importsByDependency = new Map();
  16791. for (const variable of this.imports) {
  16792. const module = variable.module;
  16793. let dependency;
  16794. let imported;
  16795. if (module instanceof ExternalModule) {
  16796. dependency = this.externalChunkByModule.get(module);
  16797. imported = variable.name;
  16798. if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
  16799. return error(logUnexpectedNamedImport(module.id, imported, false));
  16800. }
  16801. }
  16802. else {
  16803. dependency = this.chunkByModule.get(module);
  16804. imported = dependency.getVariableExportName(variable);
  16805. }
  16806. getOrCreate(importsByDependency, dependency, getNewArray).push({
  16807. imported,
  16808. local: variable.getName(this.snippets.getPropertyAccess)
  16809. });
  16810. }
  16811. return importsByDependency;
  16812. }
  16813. getIncludedDynamicImports() {
  16814. if (this.includedDynamicImports) {
  16815. return this.includedDynamicImports;
  16816. }
  16817. const includedDynamicImports = [];
  16818. for (const module of this.orderedModules) {
  16819. for (const { node, resolution } of module.dynamicImports) {
  16820. if (!node.included) {
  16821. continue;
  16822. }
  16823. includedDynamicImports.push(resolution instanceof Module
  16824. ? {
  16825. chunk: this.chunkByModule.get(resolution),
  16826. externalChunk: null,
  16827. facadeChunk: this.facadeChunkByModule.get(resolution),
  16828. node,
  16829. resolution
  16830. }
  16831. : resolution instanceof ExternalModule
  16832. ? {
  16833. chunk: null,
  16834. externalChunk: this.externalChunkByModule.get(resolution),
  16835. facadeChunk: null,
  16836. node,
  16837. resolution
  16838. }
  16839. : { chunk: null, externalChunk: null, facadeChunk: null, node, resolution });
  16840. }
  16841. }
  16842. return (this.includedDynamicImports = includedDynamicImports);
  16843. }
  16844. getPreRenderedChunkInfo() {
  16845. if (this.preRenderedChunkInfo) {
  16846. return this.preRenderedChunkInfo;
  16847. }
  16848. const { dynamicEntryModules, facadeModule, implicitEntryModules, orderedModules } = this;
  16849. return (this.preRenderedChunkInfo = {
  16850. exports: this.getExportNames(),
  16851. facadeModuleId: facadeModule && facadeModule.id,
  16852. isDynamicEntry: dynamicEntryModules.length > 0,
  16853. isEntry: !!facadeModule?.info.isEntry,
  16854. isImplicitEntry: implicitEntryModules.length > 0,
  16855. moduleIds: orderedModules.map(({ id }) => id),
  16856. name: this.getChunkName(),
  16857. type: 'chunk'
  16858. });
  16859. }
  16860. getPreserveModulesChunkNameFromModule(module) {
  16861. const predefinedChunkName = getPredefinedChunkNameFromModule(module);
  16862. if (predefinedChunkName)
  16863. return predefinedChunkName;
  16864. const { preserveModulesRoot, sanitizeFileName } = this.outputOptions;
  16865. const sanitizedId = sanitizeFileName(normalize(module.id.split(QUERY_HASH_REGEX, 1)[0]));
  16866. const extensionName = node_path.extname(sanitizedId);
  16867. const idWithoutExtension = NON_ASSET_EXTENSIONS.has(extensionName)
  16868. ? sanitizedId.slice(0, -extensionName.length)
  16869. : sanitizedId;
  16870. if (isAbsolute(idWithoutExtension)) {
  16871. return preserveModulesRoot && node_path.resolve(idWithoutExtension).startsWith(preserveModulesRoot)
  16872. ? idWithoutExtension.slice(preserveModulesRoot.length).replace(/^[/\\]/, '')
  16873. : relative(this.inputBase, idWithoutExtension);
  16874. }
  16875. else {
  16876. return `_virtual/${node_path.basename(idWithoutExtension)}`;
  16877. }
  16878. }
  16879. getReexportSpecifiers() {
  16880. const { externalLiveBindings, interop } = this.outputOptions;
  16881. const reexportSpecifiers = new Map();
  16882. for (let exportName of this.getExportNames()) {
  16883. let dependency;
  16884. let imported;
  16885. let needsLiveBinding = false;
  16886. if (exportName[0] === '*') {
  16887. const id = exportName.slice(1);
  16888. if (interop(id) === 'defaultOnly') {
  16889. this.inputOptions.onLog(LOGLEVEL_WARN, logUnexpectedNamespaceReexport(id));
  16890. }
  16891. needsLiveBinding = externalLiveBindings;
  16892. dependency = this.externalChunkByModule.get(this.modulesById.get(id));
  16893. imported = exportName = '*';
  16894. }
  16895. else {
  16896. const variable = this.exportsByName.get(exportName);
  16897. if (variable instanceof SyntheticNamedExportVariable)
  16898. continue;
  16899. const module = variable.module;
  16900. if (module instanceof Module) {
  16901. dependency = this.chunkByModule.get(module);
  16902. if (dependency === this)
  16903. continue;
  16904. imported = dependency.getVariableExportName(variable);
  16905. needsLiveBinding = variable.isReassigned;
  16906. }
  16907. else {
  16908. dependency = this.externalChunkByModule.get(module);
  16909. imported = variable.name;
  16910. if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
  16911. return error(logUnexpectedNamedImport(module.id, imported, true));
  16912. }
  16913. needsLiveBinding =
  16914. externalLiveBindings &&
  16915. (imported !== 'default' || isDefaultAProperty(interop(module.id), true));
  16916. }
  16917. }
  16918. getOrCreate(reexportSpecifiers, dependency, getNewArray).push({
  16919. imported,
  16920. needsLiveBinding,
  16921. reexported: exportName
  16922. });
  16923. }
  16924. return reexportSpecifiers;
  16925. }
  16926. getReferencedFiles() {
  16927. const referencedFiles = new Set();
  16928. for (const module of this.orderedModules) {
  16929. for (const meta of module.importMetas) {
  16930. const fileName = meta.getReferencedFileName(this.pluginDriver);
  16931. if (fileName) {
  16932. referencedFiles.add(fileName);
  16933. }
  16934. }
  16935. }
  16936. return [...referencedFiles];
  16937. }
  16938. getRenderedDependencies() {
  16939. if (this.renderedDependencies) {
  16940. return this.renderedDependencies;
  16941. }
  16942. const importSpecifiers = this.getImportSpecifiers();
  16943. const reexportSpecifiers = this.getReexportSpecifiers();
  16944. const renderedDependencies = new Map();
  16945. const fileName = this.getFileName();
  16946. for (const dep of this.dependencies) {
  16947. const imports = importSpecifiers.get(dep) || null;
  16948. const reexports = reexportSpecifiers.get(dep) || null;
  16949. const namedExportsMode = dep instanceof ExternalChunk || dep.exportMode !== 'default';
  16950. const importPath = dep.getImportPath(fileName);
  16951. renderedDependencies.set(dep, {
  16952. assertions: dep instanceof ExternalChunk ? dep.getImportAssertions(this.snippets) : null,
  16953. defaultVariableName: dep.defaultVariableName,
  16954. globalName: dep instanceof ExternalChunk &&
  16955. (this.outputOptions.format === 'umd' || this.outputOptions.format === 'iife') &&
  16956. getGlobalName(dep, this.outputOptions.globals, (imports || reexports) !== null, this.inputOptions.onLog),
  16957. importPath,
  16958. imports,
  16959. isChunk: dep instanceof Chunk,
  16960. name: dep.variableName,
  16961. namedExportsMode,
  16962. namespaceVariableName: dep.namespaceVariableName,
  16963. reexports
  16964. });
  16965. }
  16966. return (this.renderedDependencies = renderedDependencies);
  16967. }
  16968. inlineChunkDependencies(chunk) {
  16969. for (const dep of chunk.dependencies) {
  16970. if (this.dependencies.has(dep))
  16971. continue;
  16972. this.dependencies.add(dep);
  16973. if (dep instanceof Chunk) {
  16974. this.inlineChunkDependencies(dep);
  16975. }
  16976. }
  16977. }
  16978. // This method changes properties on the AST before rendering and must not be async
  16979. renderModules(fileName) {
  16980. const { accessedGlobalsByScope, dependencies, exportNamesByVariable, includedNamespaces, inputOptions: { onLog }, isEmpty, orderedModules, outputOptions, pluginDriver, renderedModules, snippets } = this;
  16981. const { compact, dynamicImportFunction, format, freeze, namespaceToStringTag } = outputOptions;
  16982. const { _, cnst, n } = snippets;
  16983. this.setDynamicImportResolutions(fileName);
  16984. this.setImportMetaResolutions(fileName);
  16985. this.setIdentifierRenderResolutions();
  16986. const magicString = new Bundle$1({ separator: `${n}${n}` });
  16987. const indent = getIndentString(orderedModules, outputOptions);
  16988. const usedModules = [];
  16989. let hoistedSource = '';
  16990. const accessedGlobals = new Set();
  16991. const renderedModuleSources = new Map();
  16992. const renderOptions = {
  16993. accessedDocumentCurrentScript: false,
  16994. dynamicImportFunction,
  16995. exportNamesByVariable,
  16996. format,
  16997. freeze,
  16998. indent,
  16999. namespaceToStringTag,
  17000. pluginDriver,
  17001. snippets,
  17002. useOriginalName: null
  17003. };
  17004. let usesTopLevelAwait = false;
  17005. for (const module of orderedModules) {
  17006. let renderedLength = 0;
  17007. let source;
  17008. if (module.isIncluded() || includedNamespaces.has(module)) {
  17009. const rendered = module.render(renderOptions);
  17010. if (!renderOptions.accessedDocumentCurrentScript &&
  17011. formatsMaybeAccessDocumentCurrentScript.includes(format)) {
  17012. // eslint-disable-next-line unicorn/consistent-destructuring
  17013. this.accessedGlobalsByScope.get(module.scope)?.delete(DOCUMENT_CURRENT_SCRIPT);
  17014. }
  17015. renderOptions.accessedDocumentCurrentScript = false;
  17016. ({ source } = rendered);
  17017. usesTopLevelAwait || (usesTopLevelAwait = rendered.usesTopLevelAwait);
  17018. renderedLength = source.length();
  17019. if (renderedLength) {
  17020. if (compact && source.lastLine().includes('//'))
  17021. source.append('\n');
  17022. renderedModuleSources.set(module, source);
  17023. magicString.addSource(source);
  17024. usedModules.push(module);
  17025. }
  17026. const namespace = module.namespace;
  17027. if (includedNamespaces.has(module)) {
  17028. const rendered = namespace.renderBlock(renderOptions);
  17029. if (namespace.renderFirst())
  17030. hoistedSource += n + rendered;
  17031. else
  17032. magicString.addSource(new MagicString(rendered));
  17033. }
  17034. const accessedGlobalVariables = accessedGlobalsByScope.get(module.scope);
  17035. if (accessedGlobalVariables) {
  17036. for (const name of accessedGlobalVariables) {
  17037. accessedGlobals.add(name);
  17038. }
  17039. }
  17040. }
  17041. const { renderedExports, removedExports } = module.getRenderedExports();
  17042. renderedModules[module.id] = {
  17043. get code() {
  17044. return source?.toString() ?? null;
  17045. },
  17046. originalLength: module.originalCode.length,
  17047. removedExports,
  17048. renderedExports,
  17049. renderedLength
  17050. };
  17051. }
  17052. if (hoistedSource)
  17053. magicString.prepend(hoistedSource + n + n);
  17054. // eslint-disable-next-line unicorn/consistent-destructuring
  17055. if (this.needsExportsShim) {
  17056. magicString.prepend(`${n}${cnst} ${MISSING_EXPORT_SHIM_VARIABLE}${_}=${_}void 0;${n}${n}`);
  17057. }
  17058. const renderedSource = compact ? magicString : magicString.trim();
  17059. if (isEmpty && this.getExportNames().length === 0 && dependencies.size === 0) {
  17060. onLog(LOGLEVEL_WARN, logEmptyChunk(this.getChunkName()));
  17061. }
  17062. return { accessedGlobals, indent, magicString, renderedSource, usedModules, usesTopLevelAwait };
  17063. }
  17064. setDynamicImportResolutions(fileName) {
  17065. const { accessedGlobalsByScope, outputOptions, pluginDriver, snippets } = this;
  17066. for (const resolvedDynamicImport of this.getIncludedDynamicImports()) {
  17067. if (resolvedDynamicImport.chunk) {
  17068. const { chunk, facadeChunk, node, resolution } = resolvedDynamicImport;
  17069. if (chunk === this) {
  17070. node.setInternalResolution(resolution.namespace);
  17071. }
  17072. else {
  17073. node.setExternalResolution((facadeChunk || chunk).exportMode, resolution, outputOptions, snippets, pluginDriver, accessedGlobalsByScope, `'${(facadeChunk || chunk).getImportPath(fileName)}'`, !facadeChunk?.strictFacade && chunk.exportNamesByVariable.get(resolution.namespace)[0], null);
  17074. }
  17075. }
  17076. else {
  17077. const { node, resolution } = resolvedDynamicImport;
  17078. const [resolutionString, assertions] = this.getDynamicImportStringAndAssertions(resolution, fileName);
  17079. node.setExternalResolution('external', resolution, outputOptions, snippets, pluginDriver, accessedGlobalsByScope, resolutionString, false, assertions);
  17080. }
  17081. }
  17082. }
  17083. setIdentifierRenderResolutions() {
  17084. const { format, interop, namespaceToStringTag, preserveModules, externalLiveBindings } = this.outputOptions;
  17085. const syntheticExports = new Set();
  17086. for (const exportName of this.getExportNames()) {
  17087. const exportVariable = this.exportsByName.get(exportName);
  17088. if (format !== 'es' &&
  17089. format !== 'system' &&
  17090. exportVariable.isReassigned &&
  17091. !exportVariable.isId) {
  17092. exportVariable.setRenderNames('exports', exportName);
  17093. }
  17094. else if (exportVariable instanceof SyntheticNamedExportVariable) {
  17095. syntheticExports.add(exportVariable);
  17096. }
  17097. else {
  17098. exportVariable.setRenderNames(null, null);
  17099. }
  17100. }
  17101. for (const module of this.orderedModules) {
  17102. if (module.needsExportShim) {
  17103. this.needsExportsShim = true;
  17104. break;
  17105. }
  17106. }
  17107. const usedNames = new Set(['Object', 'Promise']);
  17108. if (this.needsExportsShim) {
  17109. usedNames.add(MISSING_EXPORT_SHIM_VARIABLE);
  17110. }
  17111. if (namespaceToStringTag) {
  17112. usedNames.add('Symbol');
  17113. }
  17114. switch (format) {
  17115. case 'system': {
  17116. usedNames.add('module').add('exports');
  17117. break;
  17118. }
  17119. case 'es': {
  17120. break;
  17121. }
  17122. case 'cjs': {
  17123. usedNames.add('module').add('require').add('__filename').add('__dirname');
  17124. }
  17125. // fallthrough
  17126. default: {
  17127. usedNames.add('exports');
  17128. for (const helper of HELPER_NAMES) {
  17129. usedNames.add(helper);
  17130. }
  17131. }
  17132. }
  17133. 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);
  17134. }
  17135. setImportMetaResolutions(fileName) {
  17136. const { accessedGlobalsByScope, includedNamespaces, orderedModules, outputOptions: { format } } = this;
  17137. for (const module of orderedModules) {
  17138. for (const importMeta of module.importMetas) {
  17139. importMeta.setResolution(format, accessedGlobalsByScope, fileName);
  17140. }
  17141. if (includedNamespaces.has(module)) {
  17142. module.namespace.prepare(accessedGlobalsByScope);
  17143. }
  17144. }
  17145. }
  17146. setUpChunkImportsAndExportsForModule(module) {
  17147. const moduleImports = new Set(module.includedImports);
  17148. // when we are not preserving modules, we need to make all namespace variables available for
  17149. // rendering the namespace object
  17150. if (!this.outputOptions.preserveModules && this.includedNamespaces.has(module)) {
  17151. const memberVariables = module.namespace.getMemberVariables();
  17152. for (const variable of Object.values(memberVariables)) {
  17153. if (variable.included) {
  17154. moduleImports.add(variable);
  17155. }
  17156. }
  17157. }
  17158. for (let variable of moduleImports) {
  17159. if (variable instanceof ExportDefaultVariable) {
  17160. variable = variable.getOriginalVariable();
  17161. }
  17162. if (variable instanceof SyntheticNamedExportVariable) {
  17163. variable = variable.getBaseVariable();
  17164. }
  17165. const chunk = this.chunkByModule.get(variable.module);
  17166. if (chunk !== this) {
  17167. this.imports.add(variable);
  17168. if (variable.module instanceof Module) {
  17169. this.checkCircularDependencyImport(variable, module);
  17170. // When preserving modules, we do not create namespace objects but directly
  17171. // use the actual namespaces, which would be broken by this logic.
  17172. if (!(variable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
  17173. chunk.exports.add(variable);
  17174. }
  17175. }
  17176. }
  17177. }
  17178. if (this.includedNamespaces.has(module) ||
  17179. (module.info.isEntry && module.preserveSignature !== false) ||
  17180. module.includedDynamicImporters.some(importer => this.chunkByModule.get(importer) !== this)) {
  17181. this.ensureReexportsAreAvailableForModule(module);
  17182. }
  17183. for (const { node, resolution } of module.dynamicImports) {
  17184. if (node.included &&
  17185. resolution instanceof Module &&
  17186. this.chunkByModule.get(resolution) === this &&
  17187. !this.includedNamespaces.has(resolution)) {
  17188. this.includedNamespaces.add(resolution);
  17189. this.ensureReexportsAreAvailableForModule(resolution);
  17190. }
  17191. }
  17192. }
  17193. }
  17194. function getChunkNameFromModule(module) {
  17195. return getPredefinedChunkNameFromModule(module) ?? getAliasName(module.id);
  17196. }
  17197. function getPredefinedChunkNameFromModule(module) {
  17198. return (module.chunkNames.find(({ isUserDefined }) => isUserDefined)?.name ?? module.chunkNames[0]?.name);
  17199. }
  17200. function getImportedBindingsPerDependency(renderedDependencies, resolveFileName) {
  17201. const importedBindingsPerDependency = {};
  17202. for (const [dependency, declaration] of renderedDependencies) {
  17203. const specifiers = new Set();
  17204. if (declaration.imports) {
  17205. for (const { imported } of declaration.imports) {
  17206. specifiers.add(imported);
  17207. }
  17208. }
  17209. if (declaration.reexports) {
  17210. for (const { imported } of declaration.reexports) {
  17211. specifiers.add(imported);
  17212. }
  17213. }
  17214. importedBindingsPerDependency[resolveFileName(dependency)] = [...specifiers];
  17215. }
  17216. return importedBindingsPerDependency;
  17217. }
  17218. const QUERY_HASH_REGEX = /[#?]/;
  17219. const resolveFileName = (dependency) => dependency.getFileName();
  17220. /**
  17221. * Concatenate a number of iterables to a new iterable without fully evaluating
  17222. * their iterators. Useful when e.g. working with large sets or lists and when
  17223. * there is a chance that the iterators will not be fully exhausted.
  17224. */
  17225. function* concatLazy(iterables) {
  17226. for (const iterable of iterables) {
  17227. yield* iterable;
  17228. }
  17229. }
  17230. /**
  17231. * At its core, the algorithm first starts from each static or dynamic entry
  17232. * point and then assigns that entry point to all modules than can be reached
  17233. * via static imports. We call this the *dependent entry points* of that
  17234. * module.
  17235. *
  17236. * Then we group all modules with the same dependent entry points into chunks
  17237. * as those modules will always be loaded together.
  17238. *
  17239. * One non-trivial optimization we can apply is that dynamic entries are
  17240. * different from static entries in so far as when a dynamic import occurs,
  17241. * some
  17242. * modules are already in memory. If some of these modules are also
  17243. * dependencies
  17244. * of the dynamic entry, then it does not make sense to create a separate chunk
  17245. * for them. Instead, the dynamic import target can load them from the
  17246. * importing
  17247. * chunk.
  17248. *
  17249. * With regard to chunking, if B is implicitly loaded after A, then this can be
  17250. * handled the same way as if there was a dynamic import A => B.
  17251. *
  17252. * Example:
  17253. * Assume A -> B (A imports B), A => C (A dynamically imports C) and C -> B.
  17254. * Then the initial algorithm would assign A into the A chunk, C into the C
  17255. * chunk and B into the AC chunk, i.e. the chunk with the dependent entry
  17256. * points
  17257. * A and C.
  17258. * However we know that C can only be loaded from A, so A and its dependency B
  17259. * must already be in memory when C is loaded. So it is enough to create only
  17260. * two chunks A containing [AB] and C containing [C].
  17261. *
  17262. * So we do not assign the dynamic entry C as dependent entry point to modules
  17263. * that are already loaded.
  17264. *
  17265. * In a more complex example, let us assume that we have entry points X and Y.
  17266. * Further, let us assume
  17267. * X -> A, X -> B, X -> C,
  17268. * Y -> A, Y -> B,
  17269. * A => D,
  17270. * D -> B, D -> C
  17271. * So without dynamic import optimization, the dependent entry points are
  17272. * A: XY, B: DXY, C: DX, D: D, X: X, Y: Y,
  17273. * so we would for now create six chunks.
  17274. *
  17275. * Now D is loaded only after A is loaded. But A is loaded if either X is
  17276. * loaded
  17277. * or Y is loaded. So the modules that are already in memory when D is loaded
  17278. * are the intersection of all modules that X depends on with all modules that
  17279. * Y
  17280. * depends on, which in this case are the modules A and B.
  17281. * We could also say they are all modules that have both X and Y as dependent
  17282. * entry points.
  17283. *
  17284. * So we can remove D as dependent entry point from A and B, which means they
  17285. * both now have only XY as dependent entry points and can be merged into the
  17286. * same chunk.
  17287. *
  17288. * Now let us extend this to the most general case where we have several
  17289. * dynamic
  17290. * importers for one dynamic entry point.
  17291. *
  17292. * In the most general form, it works like this:
  17293. * For each dynamic entry point, we have a number of dynamic importers, which
  17294. * are the modules importing it. Using the previous ideas, we can determine
  17295. * the modules already in memory for each dynamic importer by looking for all
  17296. * modules that have all the dependent entry points of the dynamic importer as
  17297. * dependent entry points.
  17298. * So the modules that are guaranteed to be in memory when the dynamic entry
  17299. * point is loaded are the intersection of the modules already in memory for
  17300. * each dynamic importer.
  17301. *
  17302. * Assuming that A => D and B => D and A has dependent entry points XY and B
  17303. * has
  17304. * dependent entry points YZ, then the modules guaranteed to be in memory are
  17305. * all modules that have at least XYZ as dependent entry points.
  17306. * We call XYZ the *dynamically dependent entry points* of D.
  17307. *
  17308. * Now there is one last case to consider: If one of the dynamically dependent
  17309. * entries is itself a dynamic entry, then any module is in memory that either
  17310. * is a dependency of that dynamic entry or again has the dynamic dependent
  17311. * entries of that dynamic entry as dependent entry points.
  17312. *
  17313. * A naive algorithm for this proved to be costly as it contained an O(n^3)
  17314. * complexity with regard to dynamic entries that blew up for very large
  17315. * projects.
  17316. *
  17317. * If we have an efficient way to do Set operations, an alternative approach
  17318. * would be to instead collect already loaded modules per dynamic entry. And as
  17319. * all chunks from the initial grouping would behave the same, we can instead
  17320. * collect already loaded chunks for a performance improvement.
  17321. *
  17322. * To do that efficiently, need
  17323. * - a Map of dynamic imports per dynamic entry, which contains all dynamic
  17324. * imports that can be triggered by a dynamic entry
  17325. * - a Map of static dependencies per entry
  17326. * - a Map of already loaded chunks per entry that we initially populate with
  17327. * empty Sets for static entries and Sets containing all entries for dynamic
  17328. * entries
  17329. *
  17330. * For efficient operations, we assign each entry a numerical index and
  17331. * represent Sets of Chunks as BigInt values where each chunk corresponds to a
  17332. * bit index. Then thw last two maps can be represented as arrays of BigInt
  17333. * values.
  17334. *
  17335. * Then we iterate through each dynamic entry. We set the already loaded modules
  17336. * to the intersection of the previously already loaded modules with the union
  17337. * of the already loaded modules of that chunk with its static dependencies.
  17338. *
  17339. * If the already loaded modules changed, then we use the Map of dynamic imports
  17340. * per dynamic entry to marks all dynamic entry dependencies as "dirty" and put
  17341. * them back into the iteration. As an additional optimization, we note for
  17342. * each dynamic entry which dynamic dependent entries have changed and only
  17343. * intersect those entries again on subsequent interations.
  17344. *
  17345. * Then we remove the dynamic entries from the list of dependent entries for
  17346. * those chunks that are already loaded for that dynamic entry and create
  17347. * another round of chunks.
  17348. */
  17349. function getChunkAssignments(entries, manualChunkAliasByEntry, minChunkSize, log) {
  17350. const { chunkDefinitions, modulesInManualChunks } = getChunkDefinitionsFromManualChunks(manualChunkAliasByEntry);
  17351. const { allEntries, dependentEntriesByModule, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry } = analyzeModuleGraph(entries);
  17352. // Each chunk is identified by its position in this array
  17353. const initialChunks = getChunksFromDependentEntries(getModulesWithDependentEntries(dependentEntriesByModule, modulesInManualChunks));
  17354. // This mutates initialChunks but also clears
  17355. // dynamicallyDependentEntriesByDynamicEntry as side effect
  17356. removeUnnecessaryDependentEntries(initialChunks, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry, allEntries);
  17357. chunkDefinitions.push(...getOptimizedChunks(getChunksFromDependentEntries(initialChunks), allEntries.length, minChunkSize, log).map(({ modules }) => ({
  17358. alias: null,
  17359. modules
  17360. })));
  17361. return chunkDefinitions;
  17362. }
  17363. function getChunkDefinitionsFromManualChunks(manualChunkAliasByEntry) {
  17364. const chunkDefinitions = [];
  17365. const modulesInManualChunks = new Set(manualChunkAliasByEntry.keys());
  17366. const manualChunkModulesByAlias = Object.create(null);
  17367. for (const [entry, alias] of manualChunkAliasByEntry) {
  17368. addStaticDependenciesToManualChunk(entry, (manualChunkModulesByAlias[alias] || (manualChunkModulesByAlias[alias] = [])), modulesInManualChunks);
  17369. }
  17370. for (const [alias, modules] of Object.entries(manualChunkModulesByAlias)) {
  17371. chunkDefinitions.push({ alias, modules });
  17372. }
  17373. return { chunkDefinitions, modulesInManualChunks };
  17374. }
  17375. function addStaticDependenciesToManualChunk(entry, manualChunkModules, modulesInManualChunks) {
  17376. const modulesToHandle = new Set([entry]);
  17377. for (const module of modulesToHandle) {
  17378. modulesInManualChunks.add(module);
  17379. manualChunkModules.push(module);
  17380. for (const dependency of module.dependencies) {
  17381. if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
  17382. modulesToHandle.add(dependency);
  17383. }
  17384. }
  17385. }
  17386. }
  17387. function analyzeModuleGraph(entries) {
  17388. const dynamicEntryModules = new Set();
  17389. const dependentEntriesByModule = new Map();
  17390. const dynamicImportModulesByEntry = [];
  17391. const allEntriesSet = new Set(entries);
  17392. let entryIndex = 0;
  17393. for (const currentEntry of allEntriesSet) {
  17394. const dynamicImportsForCurrentEntry = new Set();
  17395. dynamicImportModulesByEntry.push(dynamicImportsForCurrentEntry);
  17396. const modulesToHandle = new Set([currentEntry]);
  17397. for (const module of modulesToHandle) {
  17398. getOrCreate(dependentEntriesByModule, module, (getNewSet)).add(entryIndex);
  17399. for (const dependency of module.getDependenciesToBeIncluded()) {
  17400. if (!(dependency instanceof ExternalModule)) {
  17401. modulesToHandle.add(dependency);
  17402. }
  17403. }
  17404. for (const { resolution } of module.dynamicImports) {
  17405. if (resolution instanceof Module &&
  17406. resolution.includedDynamicImporters.length > 0 &&
  17407. !allEntriesSet.has(resolution)) {
  17408. dynamicEntryModules.add(resolution);
  17409. allEntriesSet.add(resolution);
  17410. dynamicImportsForCurrentEntry.add(resolution);
  17411. }
  17412. }
  17413. for (const dependency of module.implicitlyLoadedBefore) {
  17414. if (!allEntriesSet.has(dependency)) {
  17415. dynamicEntryModules.add(dependency);
  17416. allEntriesSet.add(dependency);
  17417. }
  17418. }
  17419. }
  17420. entryIndex++;
  17421. }
  17422. const allEntries = [...allEntriesSet];
  17423. const { dynamicEntries, dynamicImportsByEntry } = getDynamicEntries(allEntries, dynamicEntryModules, dynamicImportModulesByEntry);
  17424. return {
  17425. allEntries,
  17426. dependentEntriesByModule,
  17427. dynamicallyDependentEntriesByDynamicEntry: getDynamicallyDependentEntriesByDynamicEntry(dependentEntriesByModule, dynamicEntries, allEntries),
  17428. dynamicImportsByEntry
  17429. };
  17430. }
  17431. function getDynamicEntries(allEntries, dynamicEntryModules, dynamicImportModulesByEntry) {
  17432. const entryIndexByModule = new Map();
  17433. const dynamicEntries = new Set();
  17434. for (const [entryIndex, entry] of allEntries.entries()) {
  17435. entryIndexByModule.set(entry, entryIndex);
  17436. if (dynamicEntryModules.has(entry)) {
  17437. dynamicEntries.add(entryIndex);
  17438. }
  17439. }
  17440. const dynamicImportsByEntry = [];
  17441. for (const dynamicImportModules of dynamicImportModulesByEntry) {
  17442. const dynamicImports = new Set();
  17443. for (const dynamicEntry of dynamicImportModules) {
  17444. dynamicImports.add(entryIndexByModule.get(dynamicEntry));
  17445. }
  17446. dynamicImportsByEntry.push(dynamicImports);
  17447. }
  17448. return { dynamicEntries, dynamicImportsByEntry };
  17449. }
  17450. function getDynamicallyDependentEntriesByDynamicEntry(dependentEntriesByModule, dynamicEntries, allEntries) {
  17451. const dynamicallyDependentEntriesByDynamicEntry = new Map();
  17452. for (const dynamicEntryIndex of dynamicEntries) {
  17453. const dynamicallyDependentEntries = getOrCreate(dynamicallyDependentEntriesByDynamicEntry, dynamicEntryIndex, (getNewSet));
  17454. const dynamicEntry = allEntries[dynamicEntryIndex];
  17455. for (const importer of concatLazy([
  17456. dynamicEntry.includedDynamicImporters,
  17457. dynamicEntry.implicitlyLoadedAfter
  17458. ])) {
  17459. for (const entry of dependentEntriesByModule.get(importer)) {
  17460. dynamicallyDependentEntries.add(entry);
  17461. }
  17462. }
  17463. }
  17464. return dynamicallyDependentEntriesByDynamicEntry;
  17465. }
  17466. function getChunksFromDependentEntries(modulesWithDependentEntries) {
  17467. var _a;
  17468. const chunkModules = Object.create(null);
  17469. for (const { dependentEntries, modules } of modulesWithDependentEntries) {
  17470. let chunkSignature = 0n;
  17471. for (const entryIndex of dependentEntries) {
  17472. chunkSignature |= 1n << BigInt(entryIndex);
  17473. }
  17474. (chunkModules[_a = String(chunkSignature)] || (chunkModules[_a] = {
  17475. dependentEntries: new Set(dependentEntries),
  17476. modules: []
  17477. })).modules.push(...modules);
  17478. }
  17479. return Object.values(chunkModules);
  17480. }
  17481. function* getModulesWithDependentEntries(dependentEntriesByModule, modulesInManualChunks) {
  17482. for (const [module, dependentEntries] of dependentEntriesByModule) {
  17483. if (!modulesInManualChunks.has(module)) {
  17484. yield { dependentEntries, modules: [module] };
  17485. }
  17486. }
  17487. }
  17488. /**
  17489. * This removes all unnecessary dynamic entries from the dependenEntries in its
  17490. * first argument. It will also consume its second argument, so if
  17491. * dynamicallyDependentEntriesByDynamicEntry is ever needed after this, we
  17492. * should make a copy.
  17493. */
  17494. function removeUnnecessaryDependentEntries(chunks, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry, allEntries) {
  17495. // The indices correspond to the indices in allEntries. The chunks correspond
  17496. // to bits in the bigint values where chunk 0 is the lowest bit.
  17497. const staticDependenciesPerEntry = allEntries.map(() => 0n);
  17498. const alreadyLoadedChunksPerEntry = allEntries.map((_entry, entryIndex) => dynamicallyDependentEntriesByDynamicEntry.has(entryIndex) ? -1n : 0n);
  17499. // This toggles the bits for each chunk that is a dependency of an entry
  17500. let chunkMask = 1n;
  17501. for (const { dependentEntries } of chunks) {
  17502. for (const entryIndex of dependentEntries) {
  17503. staticDependenciesPerEntry[entryIndex] |= chunkMask;
  17504. }
  17505. chunkMask <<= 1n;
  17506. }
  17507. // Warning: This will consume dynamicallyDependentEntriesByDynamicEntry.
  17508. // If we no longer want this, we should make a copy here.
  17509. const updatedDynamicallyDependentEntriesByDynamicEntry = dynamicallyDependentEntriesByDynamicEntry;
  17510. for (const [dynamicEntryIndex, updatedDynamicallyDependentEntries] of updatedDynamicallyDependentEntriesByDynamicEntry) {
  17511. updatedDynamicallyDependentEntriesByDynamicEntry.delete(dynamicEntryIndex);
  17512. const previousLoadedModules = alreadyLoadedChunksPerEntry[dynamicEntryIndex];
  17513. let newLoadedModules = previousLoadedModules;
  17514. for (const entryIndex of updatedDynamicallyDependentEntries) {
  17515. newLoadedModules &=
  17516. staticDependenciesPerEntry[entryIndex] | alreadyLoadedChunksPerEntry[entryIndex];
  17517. }
  17518. if (newLoadedModules !== previousLoadedModules) {
  17519. alreadyLoadedChunksPerEntry[dynamicEntryIndex] = newLoadedModules;
  17520. for (const dynamicImport of dynamicImportsByEntry[dynamicEntryIndex]) {
  17521. getOrCreate(updatedDynamicallyDependentEntriesByDynamicEntry, dynamicImport, (getNewSet)).add(dynamicEntryIndex);
  17522. }
  17523. }
  17524. }
  17525. // Remove entries from dependent entries if a chunk is already loaded without
  17526. // that entry.
  17527. chunkMask = 1n;
  17528. for (const { dependentEntries } of chunks) {
  17529. for (const entryIndex of dependentEntries) {
  17530. if ((alreadyLoadedChunksPerEntry[entryIndex] & chunkMask) === chunkMask) {
  17531. dependentEntries.delete(entryIndex);
  17532. }
  17533. }
  17534. chunkMask <<= 1n;
  17535. }
  17536. }
  17537. /**
  17538. * This function tries to get rid of small chunks by merging them with other
  17539. * chunks.
  17540. *
  17541. * We can only merge chunks safely if after the merge, loading any entry point
  17542. * in any allowed order will not trigger side effects that should not have been
  17543. * triggered. While side effects are usually things like global function calls,
  17544. * global variable mutations or potentially thrown errors, details do not
  17545. * matter here, and we just discern chunks without side effects (pure chunks)
  17546. * from other chunks.
  17547. *
  17548. * As a first step, we assign each pre-generated chunk with side effects a
  17549. * label. I.e. we have side effect "A" if the non-pure chunk "A" is loaded.
  17550. *
  17551. * Now to determine the side effects of loading a chunk, one also has to take
  17552. * the side effects of its dependencies into account. So if A depends on B
  17553. * (A -> B) and both have side effects, loading A triggers effects AB.
  17554. *
  17555. * Now from the previous step we know that each chunk is uniquely determine by
  17556. * the entry points that depend on it and cause it to load, which we will call
  17557. * its dependent entry points.
  17558. *
  17559. * E.g. if X -> A and Y -> A, then the dependent entry points of A are XY.
  17560. * Starting from that idea, we can determine a set of chunks—and thus a set
  17561. * of side effects—that must have been triggered if a certain chunk has been
  17562. * loaded. Basically, it is the intersection of all chunks loaded by the
  17563. * dependent entry points of a given chunk. We call the corresponding side
  17564. * effects the correlated side effects of that chunk.
  17565. *
  17566. * Example:
  17567. * X -> ABC, Y -> ADE, A-> F, B -> D
  17568. * Then taking dependencies into account, X -> ABCDF, Y -> ADEF
  17569. * The intersection is ADF. So we know that when A is loaded, D and F must also
  17570. * be in memory even though neither D nor A is a dependency of the other.
  17571. * If all have side effects, we call ADF the correlated side effects of A. The
  17572. * correlated side effects need to remain constant when merging chunks.
  17573. *
  17574. * In contrast, we have the dependency side effects of A, which represents
  17575. * the side effects we trigger if we directly load A. In this example, the
  17576. * dependency side effects are AF.
  17577. * For entry chunks, dependency and correlated side effects are the same.
  17578. *
  17579. * With these concepts, merging chunks is allowed if the correlated side
  17580. * effects of each entry do not change. Thus, we are allowed to merge two
  17581. * chunks if
  17582. *
  17583. * a) the dependency side effects of each chunk are a subset of the correlated
  17584. * side effects of the other chunk, so no additional side effects are
  17585. * triggered for any entry, or
  17586. * b) The dependent entry points of chunk A are a subset of the dependent entry
  17587. * points of chunk B while the dependency side effects of A are a subset of
  17588. * the correlated side effects of B. Because in that scenario, whenever A is
  17589. * loaded, B is loaded as well. But there are cases when B is loaded where A
  17590. * is not loaded. So if we merge the chunks, all dependency side effects of
  17591. * A will be added to the correlated side effects of B, and as the latter is
  17592. * not allowed to change, the former need to be a subset of the latter.
  17593. *
  17594. * Another consideration when merging small chunks into other chunks is to
  17595. * avoid
  17596. * that too much additional code is loaded. This is achieved when the dependent
  17597. * entries of the small chunk are a subset of the dependent entries of the
  17598. * other
  17599. * chunk. Because then when the small chunk is loaded, the other chunk was
  17600. * loaded/in memory anyway, so at most when the other chunk is loaded, the
  17601. * additional size of the small chunk is loaded unnecessarily.
  17602. *
  17603. * So the algorithm performs merges in two passes:
  17604. *
  17605. * 1. First we try to merge small chunks A only into other chunks B if the
  17606. * dependent entries of A are a subset of the dependent entries of B and the
  17607. * dependency side effects of A are a subset of the correlated side effects
  17608. * of B.
  17609. * 2. Only then for all remaining small chunks, we look for arbitrary merges
  17610. * following the rule (a), starting with the smallest chunks to look for
  17611. * possible merge targets.
  17612. */
  17613. function getOptimizedChunks(initialChunks, numberOfEntries, minChunkSize, log) {
  17614. timeStart('optimize chunks', 3);
  17615. const chunkPartition = getPartitionedChunks(initialChunks, numberOfEntries, minChunkSize);
  17616. if (!chunkPartition) {
  17617. timeEnd('optimize chunks', 3);
  17618. return initialChunks; // the actual modules
  17619. }
  17620. minChunkSize > 1 &&
  17621. log('info', logOptimizeChunkStatus(initialChunks.length, chunkPartition.small.size, 'Initially'));
  17622. mergeChunks(chunkPartition, minChunkSize);
  17623. minChunkSize > 1 &&
  17624. log('info', logOptimizeChunkStatus(chunkPartition.small.size + chunkPartition.big.size, chunkPartition.small.size, 'After merging chunks'));
  17625. timeEnd('optimize chunks', 3);
  17626. return [...chunkPartition.small, ...chunkPartition.big];
  17627. }
  17628. function getPartitionedChunks(initialChunks, numberOfEntries, minChunkSize) {
  17629. const smallChunks = [];
  17630. const bigChunks = [];
  17631. const chunkByModule = new Map();
  17632. const sizeByAtom = [];
  17633. let sideEffectAtoms = 0n;
  17634. let containedAtoms = 1n;
  17635. for (const { dependentEntries, modules } of initialChunks) {
  17636. const chunkDescription = {
  17637. containedAtoms,
  17638. correlatedAtoms: 0n,
  17639. dependencies: new Set(),
  17640. dependentChunks: new Set(),
  17641. dependentEntries,
  17642. modules,
  17643. pure: true,
  17644. size: 0
  17645. };
  17646. let size = 0;
  17647. let pure = true;
  17648. for (const module of modules) {
  17649. chunkByModule.set(module, chunkDescription);
  17650. // Unfortunately, we cannot take tree-shaking into account here because
  17651. // rendering did not happen yet, but we can detect empty modules
  17652. if (module.isIncluded()) {
  17653. pure && (pure = !module.hasEffects());
  17654. // we use a trivial size for the default minChunkSize to improve
  17655. // performance
  17656. size += minChunkSize > 1 ? module.estimateSize() : 1;
  17657. }
  17658. }
  17659. chunkDescription.pure = pure;
  17660. chunkDescription.size = size;
  17661. sizeByAtom.push(size);
  17662. if (!pure) {
  17663. sideEffectAtoms |= containedAtoms;
  17664. }
  17665. (size < minChunkSize ? smallChunks : bigChunks).push(chunkDescription);
  17666. containedAtoms <<= 1n;
  17667. }
  17668. // If there are no small chunks, we will not optimize
  17669. if (smallChunks.length === 0) {
  17670. return null;
  17671. }
  17672. sideEffectAtoms |= addChunkDependenciesAndAtomsAndGetSideEffectAtoms([bigChunks, smallChunks], chunkByModule, numberOfEntries, containedAtoms);
  17673. return {
  17674. big: new Set(bigChunks),
  17675. sideEffectAtoms,
  17676. sizeByAtom,
  17677. small: new Set(smallChunks)
  17678. };
  17679. }
  17680. function mergeChunks(chunkPartition, minChunkSize) {
  17681. const { small } = chunkPartition;
  17682. for (const mergedChunk of small) {
  17683. const bestTargetChunk = findBestMergeTarget(mergedChunk, chunkPartition,
  17684. // In the default case, we do not accept size increases
  17685. minChunkSize <= 1 ? 1 : Infinity);
  17686. if (bestTargetChunk) {
  17687. const { containedAtoms, correlatedAtoms, modules, pure, size } = mergedChunk;
  17688. small.delete(mergedChunk);
  17689. getChunksInPartition(bestTargetChunk, minChunkSize, chunkPartition).delete(bestTargetChunk);
  17690. bestTargetChunk.modules.push(...modules);
  17691. bestTargetChunk.size += size;
  17692. bestTargetChunk.pure && (bestTargetChunk.pure = pure);
  17693. const { dependencies, dependentChunks, dependentEntries } = bestTargetChunk;
  17694. bestTargetChunk.correlatedAtoms &= correlatedAtoms;
  17695. bestTargetChunk.containedAtoms |= containedAtoms;
  17696. for (const entry of mergedChunk.dependentEntries) {
  17697. dependentEntries.add(entry);
  17698. }
  17699. for (const dependency of mergedChunk.dependencies) {
  17700. dependencies.add(dependency);
  17701. dependency.dependentChunks.delete(mergedChunk);
  17702. dependency.dependentChunks.add(bestTargetChunk);
  17703. }
  17704. for (const dependentChunk of mergedChunk.dependentChunks) {
  17705. dependentChunks.add(dependentChunk);
  17706. dependentChunk.dependencies.delete(mergedChunk);
  17707. dependentChunk.dependencies.add(bestTargetChunk);
  17708. }
  17709. dependencies.delete(bestTargetChunk);
  17710. dependentChunks.delete(bestTargetChunk);
  17711. getChunksInPartition(bestTargetChunk, minChunkSize, chunkPartition).add(bestTargetChunk);
  17712. }
  17713. }
  17714. }
  17715. function addChunkDependenciesAndAtomsAndGetSideEffectAtoms(chunkLists, chunkByModule, numberOfEntries, nextAtomSignature) {
  17716. const signatureByExternalModule = new Map();
  17717. let sideEffectAtoms = 0n;
  17718. const atomsByEntry = [];
  17719. for (let index = 0; index < numberOfEntries; index++) {
  17720. atomsByEntry.push(0n);
  17721. }
  17722. for (const chunks of chunkLists) {
  17723. chunks.sort(compareChunkSize);
  17724. for (const chunk of chunks) {
  17725. const { dependencies, dependentEntries, modules } = chunk;
  17726. for (const module of modules) {
  17727. for (const dependency of module.getDependenciesToBeIncluded()) {
  17728. if (dependency instanceof ExternalModule) {
  17729. if (dependency.info.moduleSideEffects) {
  17730. chunk.containedAtoms |= getOrCreate(signatureByExternalModule, dependency, () => {
  17731. const signature = nextAtomSignature;
  17732. nextAtomSignature <<= 1n;
  17733. sideEffectAtoms |= signature;
  17734. return signature;
  17735. });
  17736. }
  17737. }
  17738. else {
  17739. const dependencyChunk = chunkByModule.get(dependency);
  17740. if (dependencyChunk && dependencyChunk !== chunk) {
  17741. dependencies.add(dependencyChunk);
  17742. dependencyChunk.dependentChunks.add(chunk);
  17743. }
  17744. }
  17745. }
  17746. }
  17747. const { containedAtoms } = chunk;
  17748. for (const entryIndex of dependentEntries) {
  17749. atomsByEntry[entryIndex] |= containedAtoms;
  17750. }
  17751. }
  17752. }
  17753. for (const chunks of chunkLists) {
  17754. for (const chunk of chunks) {
  17755. const { dependentEntries } = chunk;
  17756. // Correlated atoms are the intersection of all entry atoms
  17757. chunk.correlatedAtoms = -1n;
  17758. for (const entryIndex of dependentEntries) {
  17759. chunk.correlatedAtoms &= atomsByEntry[entryIndex];
  17760. }
  17761. }
  17762. }
  17763. return sideEffectAtoms;
  17764. }
  17765. function findBestMergeTarget(mergedChunk, { big, sideEffectAtoms, sizeByAtom, small }, smallestAdditionalSize) {
  17766. let bestTargetChunk = null;
  17767. // In the default case, we do not accept size increases
  17768. for (const targetChunk of concatLazy([small, big])) {
  17769. if (mergedChunk === targetChunk)
  17770. continue;
  17771. const additionalSizeAfterMerge = getAdditionalSizeAfterMerge(mergedChunk, targetChunk, smallestAdditionalSize, sideEffectAtoms, sizeByAtom);
  17772. if (additionalSizeAfterMerge < smallestAdditionalSize) {
  17773. bestTargetChunk = targetChunk;
  17774. if (additionalSizeAfterMerge === 0)
  17775. break;
  17776. smallestAdditionalSize = additionalSizeAfterMerge;
  17777. }
  17778. }
  17779. return bestTargetChunk;
  17780. }
  17781. function getChunksInPartition(chunk, minChunkSize, chunkPartition) {
  17782. return chunk.size < minChunkSize ? chunkPartition.small : chunkPartition.big;
  17783. }
  17784. function compareChunkSize({ size: sizeA }, { size: sizeB }) {
  17785. return sizeA - sizeB;
  17786. }
  17787. /**
  17788. * Determine the additional unused code size that would be added by merging the
  17789. * two chunks. This is not an exact measurement but rather an upper bound. If
  17790. * the merge produces cycles or adds non-correlated side effects, `Infinity`
  17791. * is returned.
  17792. * Merging will not produce cycles if none of the direct non-merged
  17793. * dependencies of a chunk have the other chunk as a transitive dependency.
  17794. */
  17795. function getAdditionalSizeAfterMerge(mergedChunk, targetChunk,
  17796. // The maximum additional unused code size allowed to be added by the merge,
  17797. // taking dependencies into account, needs to be below this number
  17798. currentAdditionalSize, sideEffectAtoms, sizeByAtom) {
  17799. const firstSize = getAdditionalSizeIfNoTransitiveDependencyOrNonCorrelatedSideEffect(mergedChunk, targetChunk, currentAdditionalSize, sideEffectAtoms, sizeByAtom);
  17800. return firstSize < currentAdditionalSize
  17801. ? firstSize +
  17802. getAdditionalSizeIfNoTransitiveDependencyOrNonCorrelatedSideEffect(targetChunk, mergedChunk, currentAdditionalSize - firstSize, sideEffectAtoms, sizeByAtom)
  17803. : Infinity;
  17804. }
  17805. function getAdditionalSizeIfNoTransitiveDependencyOrNonCorrelatedSideEffect(dependentChunk, dependencyChunk, currentAdditionalSize, sideEffectAtoms, sizeByAtom) {
  17806. const { correlatedAtoms } = dependencyChunk;
  17807. let dependencyAtoms = dependentChunk.containedAtoms;
  17808. const dependentContainedSideEffects = dependencyAtoms & sideEffectAtoms;
  17809. if ((correlatedAtoms & dependentContainedSideEffects) !== dependentContainedSideEffects) {
  17810. return Infinity;
  17811. }
  17812. const chunksToCheck = new Set(dependentChunk.dependencies);
  17813. for (const { dependencies, containedAtoms } of chunksToCheck) {
  17814. dependencyAtoms |= containedAtoms;
  17815. const containedSideEffects = containedAtoms & sideEffectAtoms;
  17816. if ((correlatedAtoms & containedSideEffects) !== containedSideEffects) {
  17817. return Infinity;
  17818. }
  17819. for (const dependency of dependencies) {
  17820. if (dependency === dependencyChunk) {
  17821. return Infinity;
  17822. }
  17823. chunksToCheck.add(dependency);
  17824. }
  17825. }
  17826. return getAtomsSizeIfBelowLimit(dependencyAtoms & ~correlatedAtoms, currentAdditionalSize, sizeByAtom);
  17827. }
  17828. function getAtomsSizeIfBelowLimit(atoms, currentAdditionalSize, sizeByAtom) {
  17829. let size = 0;
  17830. let atomIndex = 0;
  17831. let atomSignature = 1n;
  17832. const { length } = sizeByAtom;
  17833. for (; atomIndex < length; atomIndex++) {
  17834. if ((atoms & atomSignature) === atomSignature) {
  17835. size += sizeByAtom[atomIndex];
  17836. }
  17837. atomSignature <<= 1n;
  17838. if (size >= currentAdditionalSize) {
  17839. return Infinity;
  17840. }
  17841. }
  17842. return size;
  17843. }
  17844. // ported from https://github.com/substack/node-commondir
  17845. function commondir(files) {
  17846. if (files.length === 0)
  17847. return '/';
  17848. if (files.length === 1)
  17849. return node_path.dirname(files[0]);
  17850. const commonSegments = files.slice(1).reduce((commonSegments, file) => {
  17851. const pathSegements = file.split(/\/+|\\+/);
  17852. let index;
  17853. for (index = 0; commonSegments[index] === pathSegements[index] &&
  17854. index < Math.min(commonSegments.length, pathSegements.length); index++)
  17855. ;
  17856. return commonSegments.slice(0, index);
  17857. }, files[0].split(/\/+|\\+/));
  17858. // Windows correctly handles paths with forward-slashes
  17859. return commonSegments.length > 1 ? commonSegments.join('/') : '/';
  17860. }
  17861. const compareExecIndex = (unitA, unitB) => unitA.execIndex > unitB.execIndex ? 1 : -1;
  17862. function sortByExecutionOrder(units) {
  17863. units.sort(compareExecIndex);
  17864. }
  17865. function analyseModuleExecution(entryModules) {
  17866. let nextExecIndex = 0;
  17867. const cyclePaths = [];
  17868. const analysedModules = new Set();
  17869. const dynamicImports = new Set();
  17870. const parents = new Map();
  17871. const orderedModules = [];
  17872. const analyseModule = (module) => {
  17873. if (module instanceof Module) {
  17874. for (const dependency of module.dependencies) {
  17875. if (parents.has(dependency)) {
  17876. if (!analysedModules.has(dependency)) {
  17877. cyclePaths.push(getCyclePath(dependency, module, parents));
  17878. }
  17879. continue;
  17880. }
  17881. parents.set(dependency, module);
  17882. analyseModule(dependency);
  17883. }
  17884. for (const dependency of module.implicitlyLoadedBefore) {
  17885. dynamicImports.add(dependency);
  17886. }
  17887. for (const { resolution } of module.dynamicImports) {
  17888. if (resolution instanceof Module) {
  17889. dynamicImports.add(resolution);
  17890. }
  17891. }
  17892. orderedModules.push(module);
  17893. }
  17894. module.execIndex = nextExecIndex++;
  17895. analysedModules.add(module);
  17896. };
  17897. for (const currentEntry of entryModules) {
  17898. if (!parents.has(currentEntry)) {
  17899. parents.set(currentEntry, null);
  17900. analyseModule(currentEntry);
  17901. }
  17902. }
  17903. for (const currentEntry of dynamicImports) {
  17904. if (!parents.has(currentEntry)) {
  17905. parents.set(currentEntry, null);
  17906. analyseModule(currentEntry);
  17907. }
  17908. }
  17909. return { cyclePaths, orderedModules };
  17910. }
  17911. function getCyclePath(module, parent, parents) {
  17912. const cycleSymbol = Symbol(module.id);
  17913. const path = [module.id];
  17914. let nextModule = parent;
  17915. module.cycles.add(cycleSymbol);
  17916. while (nextModule !== module) {
  17917. nextModule.cycles.add(cycleSymbol);
  17918. path.push(nextModule.id);
  17919. nextModule = parents.get(nextModule);
  17920. }
  17921. path.push(path[0]);
  17922. path.reverse();
  17923. return path;
  17924. }
  17925. function getGenerateCodeSnippets({ compact, generatedCode: { arrowFunctions, constBindings, objectShorthand, reservedNamesAsProps } }) {
  17926. const { _, n, s } = compact ? { _: '', n: '', s: '' } : { _: ' ', n: '\n', s: ';' };
  17927. const cnst = constBindings ? 'const' : 'var';
  17928. const getNonArrowFunctionIntro = (parameters, { isAsync, name }) => `${isAsync ? `async ` : ''}function${name ? ` ${name}` : ''}${_}(${parameters.join(`,${_}`)})${_}`;
  17929. const getFunctionIntro = arrowFunctions
  17930. ? (parameters, { isAsync, name }) => {
  17931. const singleParameter = parameters.length === 1;
  17932. const asyncString = isAsync ? `async${singleParameter ? ' ' : _}` : '';
  17933. return `${name ? `${cnst} ${name}${_}=${_}` : ''}${asyncString}${singleParameter ? parameters[0] : `(${parameters.join(`,${_}`)})`}${_}=>${_}`;
  17934. }
  17935. : getNonArrowFunctionIntro;
  17936. const getDirectReturnFunction = (parameters, { functionReturn, lineBreakIndent, name }) => [
  17937. `${getFunctionIntro(parameters, {
  17938. isAsync: false,
  17939. name
  17940. })}${arrowFunctions
  17941. ? lineBreakIndent
  17942. ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}`
  17943. : ''
  17944. : `{${lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _}${functionReturn ? 'return ' : ''}`}`,
  17945. arrowFunctions
  17946. ? `${name ? ';' : ''}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : ''}`
  17947. : `${s}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`
  17948. ];
  17949. const isValidPropertyName = reservedNamesAsProps
  17950. ? (name) => validPropertyName.test(name)
  17951. : (name) => !RESERVED_NAMES$1.has(name) && validPropertyName.test(name);
  17952. return {
  17953. _,
  17954. cnst,
  17955. getDirectReturnFunction,
  17956. getDirectReturnIifeLeft: (parameters, returned, { needsArrowReturnParens, needsWrappedFunction }) => {
  17957. const [left, right] = getDirectReturnFunction(parameters, {
  17958. functionReturn: true,
  17959. lineBreakIndent: null,
  17960. name: null
  17961. });
  17962. return `${wrapIfNeeded(`${left}${wrapIfNeeded(returned, arrowFunctions && needsArrowReturnParens)}${right}`, arrowFunctions || needsWrappedFunction)}(`;
  17963. },
  17964. getFunctionIntro,
  17965. getNonArrowFunctionIntro,
  17966. getObject(fields, { lineBreakIndent }) {
  17967. const prefix = lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _;
  17968. return `{${fields
  17969. .map(([key, value]) => {
  17970. if (key === null)
  17971. return `${prefix}${value}`;
  17972. const needsQuotes = !isValidPropertyName(key);
  17973. return key === value && objectShorthand && !needsQuotes
  17974. ? prefix + key
  17975. : `${prefix}${needsQuotes ? `'${key}'` : key}:${_}${value}`;
  17976. })
  17977. .join(`,`)}${fields.length === 0 ? '' : lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`;
  17978. },
  17979. getPropertyAccess: (name) => isValidPropertyName(name) ? `.${name}` : `[${JSON.stringify(name)}]`,
  17980. n,
  17981. s
  17982. };
  17983. }
  17984. const wrapIfNeeded = (code, needsParens) => needsParens ? `(${code})` : code;
  17985. const validPropertyName = /^(?!\d)[\w$]+$/;
  17986. class Source {
  17987. constructor(filename, content) {
  17988. this.isOriginal = true;
  17989. this.filename = filename;
  17990. this.content = content;
  17991. }
  17992. traceSegment(line, column, name) {
  17993. return { column, line, name, source: this };
  17994. }
  17995. }
  17996. class Link {
  17997. constructor(map, sources) {
  17998. this.sources = sources;
  17999. this.names = map.names;
  18000. this.mappings = map.mappings;
  18001. }
  18002. traceMappings() {
  18003. const sources = [];
  18004. const sourceIndexMap = new Map();
  18005. const sourcesContent = [];
  18006. const names = [];
  18007. const nameIndexMap = new Map();
  18008. const mappings = [];
  18009. for (const line of this.mappings) {
  18010. const tracedLine = [];
  18011. for (const segment of line) {
  18012. if (segment.length === 1)
  18013. continue;
  18014. const source = this.sources[segment[1]];
  18015. if (!source)
  18016. continue;
  18017. const traced = source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : '');
  18018. if (traced) {
  18019. const { column, line, name, source: { content, filename } } = traced;
  18020. let sourceIndex = sourceIndexMap.get(filename);
  18021. if (sourceIndex === undefined) {
  18022. sourceIndex = sources.length;
  18023. sources.push(filename);
  18024. sourceIndexMap.set(filename, sourceIndex);
  18025. sourcesContent[sourceIndex] = content;
  18026. }
  18027. else if (sourcesContent[sourceIndex] == null) {
  18028. sourcesContent[sourceIndex] = content;
  18029. }
  18030. else if (content != null && sourcesContent[sourceIndex] !== content) {
  18031. return error(logConflictingSourcemapSources(filename));
  18032. }
  18033. const tracedSegment = [segment[0], sourceIndex, line, column];
  18034. if (name) {
  18035. let nameIndex = nameIndexMap.get(name);
  18036. if (nameIndex === undefined) {
  18037. nameIndex = names.length;
  18038. names.push(name);
  18039. nameIndexMap.set(name, nameIndex);
  18040. }
  18041. tracedSegment[4] = nameIndex;
  18042. }
  18043. tracedLine.push(tracedSegment);
  18044. }
  18045. }
  18046. mappings.push(tracedLine);
  18047. }
  18048. return { mappings, names, sources, sourcesContent };
  18049. }
  18050. traceSegment(line, column, name) {
  18051. const segments = this.mappings[line];
  18052. if (!segments)
  18053. return null;
  18054. // binary search through segments for the given column
  18055. let searchStart = 0;
  18056. let searchEnd = segments.length - 1;
  18057. while (searchStart <= searchEnd) {
  18058. const m = (searchStart + searchEnd) >> 1;
  18059. const segment = segments[m];
  18060. // If a sourcemap does not have sufficient resolution to contain a
  18061. // necessary mapping, e.g. because it only contains line information, we
  18062. // use the best approximation we could find
  18063. if (segment[0] === column || searchStart === searchEnd) {
  18064. if (segment.length == 1)
  18065. return null;
  18066. const source = this.sources[segment[1]];
  18067. if (!source)
  18068. return null;
  18069. return source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : name);
  18070. }
  18071. if (segment[0] > column) {
  18072. searchEnd = m - 1;
  18073. }
  18074. else {
  18075. searchStart = m + 1;
  18076. }
  18077. }
  18078. return null;
  18079. }
  18080. }
  18081. function getLinkMap(log) {
  18082. return function linkMap(source, map) {
  18083. if (!map.missing) {
  18084. return new Link(map, [source]);
  18085. }
  18086. log(LOGLEVEL_WARN, logSourcemapBroken(map.plugin));
  18087. return new Link({
  18088. mappings: [],
  18089. names: []
  18090. }, [source]);
  18091. };
  18092. }
  18093. function getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, linkMap) {
  18094. let source;
  18095. if (originalSourcemap) {
  18096. const sources = originalSourcemap.sources;
  18097. const sourcesContent = originalSourcemap.sourcesContent || [];
  18098. const directory = node_path.dirname(id) || '.';
  18099. const sourceRoot = originalSourcemap.sourceRoot || '.';
  18100. const baseSources = sources.map((source, index) => new Source(node_path.resolve(directory, sourceRoot, source), sourcesContent[index]));
  18101. source = new Link(originalSourcemap, baseSources);
  18102. }
  18103. else {
  18104. source = new Source(id, originalCode);
  18105. }
  18106. return sourcemapChain.reduce(linkMap, source);
  18107. }
  18108. function collapseSourcemaps(file, map, modules, bundleSourcemapChain, excludeContent, log) {
  18109. const linkMap = getLinkMap(log);
  18110. const moduleSources = modules
  18111. .filter(module => !module.excludeFromSourcemap)
  18112. .map(module => getCollapsedSourcemap(module.id, module.originalCode, module.originalSourcemap, module.sourcemapChain, linkMap));
  18113. const link = new Link(map, moduleSources);
  18114. const source = bundleSourcemapChain.reduce(linkMap, link);
  18115. let { sources, sourcesContent, names, mappings } = source.traceMappings();
  18116. if (file) {
  18117. const directory = node_path.dirname(file);
  18118. sources = sources.map((source) => node_path.relative(directory, source));
  18119. file = node_path.basename(file);
  18120. }
  18121. sourcesContent = (excludeContent ? null : sourcesContent);
  18122. for (const module of modules) {
  18123. resetSourcemapCache(module.originalSourcemap, module.sourcemapChain);
  18124. }
  18125. return new SourceMap({ file, mappings, names, sources, sourcesContent });
  18126. }
  18127. function collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, log) {
  18128. if (sourcemapChain.length === 0) {
  18129. return originalSourcemap;
  18130. }
  18131. const source = getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, getLinkMap(log));
  18132. const map = source.traceMappings();
  18133. return decodedSourcemap({ version: 3, ...map });
  18134. }
  18135. async function renderChunks(chunks, bundle, pluginDriver, outputOptions, log) {
  18136. timeStart('render chunks', 2);
  18137. reserveEntryChunksInBundle(chunks);
  18138. const renderedChunks = await Promise.all(chunks.map(chunk => chunk.render()));
  18139. timeEnd('render chunks', 2);
  18140. timeStart('transform chunks', 2);
  18141. const chunkGraph = getChunkGraph(chunks);
  18142. const { initialHashesByPlaceholder, nonHashedChunksWithPlaceholders, renderedChunksByPlaceholder, hashDependenciesByPlaceholder } = await transformChunksAndGenerateContentHashes(renderedChunks, chunkGraph, outputOptions, pluginDriver, log);
  18143. const hashesByPlaceholder = generateFinalHashes(renderedChunksByPlaceholder, hashDependenciesByPlaceholder, initialHashesByPlaceholder, bundle);
  18144. addChunksToBundle(renderedChunksByPlaceholder, hashesByPlaceholder, bundle, nonHashedChunksWithPlaceholders, pluginDriver, outputOptions);
  18145. timeEnd('transform chunks', 2);
  18146. }
  18147. function reserveEntryChunksInBundle(chunks) {
  18148. for (const chunk of chunks) {
  18149. if (chunk.facadeModule && chunk.facadeModule.isUserDefinedEntryPoint) {
  18150. // reserves name in bundle as side effect if it does not contain a hash
  18151. chunk.getPreliminaryFileName();
  18152. }
  18153. }
  18154. }
  18155. function getChunkGraph(chunks) {
  18156. return Object.fromEntries(chunks.map(chunk => {
  18157. const renderedChunkInfo = chunk.getRenderedChunkInfo();
  18158. return [renderedChunkInfo.fileName, renderedChunkInfo];
  18159. }));
  18160. }
  18161. async function transformChunk(magicString, fileName, usedModules, chunkGraph, options, outputPluginDriver, log) {
  18162. let map = null;
  18163. const sourcemapChain = [];
  18164. let code = await outputPluginDriver.hookReduceArg0('renderChunk', [magicString.toString(), chunkGraph[fileName], options, { chunks: chunkGraph }], (code, result, plugin) => {
  18165. if (result == null)
  18166. return code;
  18167. if (typeof result === 'string')
  18168. result = {
  18169. code: result,
  18170. map: undefined
  18171. };
  18172. // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning
  18173. if (result.map !== null) {
  18174. const map = decodedSourcemap(result.map);
  18175. sourcemapChain.push(map || { missing: true, plugin: plugin.name });
  18176. }
  18177. return result.code;
  18178. });
  18179. const { compact, dir, file, sourcemap, sourcemapExcludeSources, sourcemapFile, sourcemapPathTransform, sourcemapIgnoreList } = options;
  18180. if (!compact && code[code.length - 1] !== '\n')
  18181. code += '\n';
  18182. if (sourcemap) {
  18183. timeStart('sourcemaps', 3);
  18184. let resultingFile;
  18185. if (file)
  18186. resultingFile = node_path.resolve(sourcemapFile || file);
  18187. else if (dir)
  18188. resultingFile = node_path.resolve(dir, fileName);
  18189. else
  18190. resultingFile = node_path.resolve(fileName);
  18191. const decodedMap = magicString.generateDecodedMap({});
  18192. map = collapseSourcemaps(resultingFile, decodedMap, usedModules, sourcemapChain, sourcemapExcludeSources, log);
  18193. for (let sourcesIndex = 0; sourcesIndex < map.sources.length; ++sourcesIndex) {
  18194. let sourcePath = map.sources[sourcesIndex];
  18195. const sourcemapPath = `${resultingFile}.map`;
  18196. const ignoreList = sourcemapIgnoreList(sourcePath, sourcemapPath);
  18197. if (typeof ignoreList !== 'boolean') {
  18198. error(logFailedValidation('sourcemapIgnoreList function must return a boolean.'));
  18199. }
  18200. if (ignoreList) {
  18201. if (map.x_google_ignoreList === undefined) {
  18202. map.x_google_ignoreList = [];
  18203. }
  18204. if (!map.x_google_ignoreList.includes(sourcesIndex)) {
  18205. map.x_google_ignoreList.push(sourcesIndex);
  18206. }
  18207. }
  18208. if (sourcemapPathTransform) {
  18209. sourcePath = sourcemapPathTransform(sourcePath, sourcemapPath);
  18210. if (typeof sourcePath !== 'string') {
  18211. error(logFailedValidation(`sourcemapPathTransform function must return a string.`));
  18212. }
  18213. }
  18214. map.sources[sourcesIndex] = normalize(sourcePath);
  18215. }
  18216. timeEnd('sourcemaps', 3);
  18217. }
  18218. return {
  18219. code,
  18220. map
  18221. };
  18222. }
  18223. async function transformChunksAndGenerateContentHashes(renderedChunks, chunkGraph, outputOptions, pluginDriver, log) {
  18224. const nonHashedChunksWithPlaceholders = [];
  18225. const renderedChunksByPlaceholder = new Map();
  18226. const hashDependenciesByPlaceholder = new Map();
  18227. const initialHashesByPlaceholder = new Map();
  18228. const placeholders = new Set();
  18229. for (const { preliminaryFileName: { hashPlaceholder } } of renderedChunks) {
  18230. if (hashPlaceholder)
  18231. placeholders.add(hashPlaceholder);
  18232. }
  18233. await Promise.all(renderedChunks.map(async ({ chunk, preliminaryFileName: { fileName, hashPlaceholder }, preliminarySourcemapFileName, magicString, usedModules }) => {
  18234. const transformedChunk = {
  18235. chunk,
  18236. fileName,
  18237. sourcemapFileName: preliminarySourcemapFileName?.fileName ?? null,
  18238. ...(await transformChunk(magicString, fileName, usedModules, chunkGraph, outputOptions, pluginDriver, log))
  18239. };
  18240. const { code, map } = transformedChunk;
  18241. if (hashPlaceholder) {
  18242. // To create a reproducible content-only hash, all placeholders are
  18243. // replaced with the same value before hashing
  18244. const { containedPlaceholders, transformedCode } = replacePlaceholdersWithDefaultAndGetContainedPlaceholders(code, placeholders);
  18245. const hash = createHash().update(transformedCode);
  18246. const hashAugmentation = pluginDriver.hookReduceValueSync('augmentChunkHash', '', [chunk.getRenderedChunkInfo()], (augmentation, pluginHash) => {
  18247. if (pluginHash) {
  18248. augmentation += pluginHash;
  18249. }
  18250. return augmentation;
  18251. });
  18252. if (hashAugmentation) {
  18253. hash.update(hashAugmentation);
  18254. }
  18255. renderedChunksByPlaceholder.set(hashPlaceholder, transformedChunk);
  18256. hashDependenciesByPlaceholder.set(hashPlaceholder, {
  18257. containedPlaceholders,
  18258. contentHash: hash.digest('hex')
  18259. });
  18260. }
  18261. else {
  18262. nonHashedChunksWithPlaceholders.push(transformedChunk);
  18263. }
  18264. const sourcemapHashPlaceholder = preliminarySourcemapFileName?.hashPlaceholder;
  18265. if (map && sourcemapHashPlaceholder) {
  18266. initialHashesByPlaceholder.set(preliminarySourcemapFileName.hashPlaceholder, createHash()
  18267. .update(map.toString())
  18268. .digest('hex')
  18269. .slice(0, preliminarySourcemapFileName.hashPlaceholder.length));
  18270. }
  18271. }));
  18272. return {
  18273. hashDependenciesByPlaceholder,
  18274. initialHashesByPlaceholder,
  18275. nonHashedChunksWithPlaceholders,
  18276. renderedChunksByPlaceholder
  18277. };
  18278. }
  18279. function generateFinalHashes(renderedChunksByPlaceholder, hashDependenciesByPlaceholder, initialHashesByPlaceholder, bundle) {
  18280. const hashesByPlaceholder = new Map(initialHashesByPlaceholder);
  18281. for (const [placeholder, { fileName }] of renderedChunksByPlaceholder) {
  18282. let hash = createHash();
  18283. const hashDependencyPlaceholders = new Set([placeholder]);
  18284. for (const dependencyPlaceholder of hashDependencyPlaceholders) {
  18285. const { containedPlaceholders, contentHash } = hashDependenciesByPlaceholder.get(dependencyPlaceholder);
  18286. hash.update(contentHash);
  18287. for (const containedPlaceholder of containedPlaceholders) {
  18288. // When looping over a map, setting an entry only causes a new iteration if the key is new
  18289. hashDependencyPlaceholders.add(containedPlaceholder);
  18290. }
  18291. }
  18292. let finalFileName;
  18293. let finalHash;
  18294. do {
  18295. // In case of a hash collision, create a hash of the hash
  18296. if (finalHash) {
  18297. hash = createHash().update(finalHash);
  18298. }
  18299. finalHash = hash.digest('hex').slice(0, placeholder.length);
  18300. finalFileName = replaceSinglePlaceholder(fileName, placeholder, finalHash);
  18301. } while (bundle[lowercaseBundleKeys].has(finalFileName.toLowerCase()));
  18302. bundle[finalFileName] = FILE_PLACEHOLDER;
  18303. hashesByPlaceholder.set(placeholder, finalHash);
  18304. }
  18305. return hashesByPlaceholder;
  18306. }
  18307. function addChunksToBundle(renderedChunksByPlaceholder, hashesByPlaceholder, bundle, nonHashedChunksWithPlaceholders, pluginDriver, options) {
  18308. for (const { chunk, code, fileName, sourcemapFileName, map } of renderedChunksByPlaceholder.values()) {
  18309. let updatedCode = replacePlaceholders(code, hashesByPlaceholder);
  18310. const finalFileName = replacePlaceholders(fileName, hashesByPlaceholder);
  18311. let finalSourcemapFileName = null;
  18312. if (map) {
  18313. finalSourcemapFileName = sourcemapFileName
  18314. ? replacePlaceholders(sourcemapFileName, hashesByPlaceholder)
  18315. : `${finalFileName}.map`;
  18316. map.file = replacePlaceholders(map.file, hashesByPlaceholder);
  18317. updatedCode += emitSourceMapAndGetComment(finalSourcemapFileName, map, pluginDriver, options);
  18318. }
  18319. bundle[finalFileName] = chunk.finalizeChunk(updatedCode, map, finalSourcemapFileName, hashesByPlaceholder);
  18320. }
  18321. for (const { chunk, code, fileName, sourcemapFileName, map } of nonHashedChunksWithPlaceholders) {
  18322. let updatedCode = hashesByPlaceholder.size > 0 ? replacePlaceholders(code, hashesByPlaceholder) : code;
  18323. let finalSourcemapFileName = null;
  18324. if (map) {
  18325. finalSourcemapFileName = sourcemapFileName
  18326. ? replacePlaceholders(sourcemapFileName, hashesByPlaceholder)
  18327. : `${fileName}.map`;
  18328. updatedCode += emitSourceMapAndGetComment(finalSourcemapFileName, map, pluginDriver, options);
  18329. }
  18330. bundle[fileName] = chunk.finalizeChunk(updatedCode, map, finalSourcemapFileName, hashesByPlaceholder);
  18331. }
  18332. }
  18333. function emitSourceMapAndGetComment(fileName, map, pluginDriver, { sourcemap, sourcemapBaseUrl }) {
  18334. let url;
  18335. if (sourcemap === 'inline') {
  18336. url = map.toUrl();
  18337. }
  18338. else {
  18339. const sourcemapFileName = node_path.basename(fileName);
  18340. url = sourcemapBaseUrl
  18341. ? new URL(sourcemapFileName, sourcemapBaseUrl).toString()
  18342. : sourcemapFileName;
  18343. pluginDriver.emitFile({ fileName, source: map.toString(), type: 'asset' });
  18344. }
  18345. return sourcemap === 'hidden' ? '' : `//# ${SOURCEMAPPING_URL}=${url}\n`;
  18346. }
  18347. class Bundle {
  18348. constructor(outputOptions, unsetOptions, inputOptions, pluginDriver, graph) {
  18349. this.outputOptions = outputOptions;
  18350. this.unsetOptions = unsetOptions;
  18351. this.inputOptions = inputOptions;
  18352. this.pluginDriver = pluginDriver;
  18353. this.graph = graph;
  18354. this.facadeChunkByModule = new Map();
  18355. this.includedNamespaces = new Set();
  18356. }
  18357. async generate(isWrite) {
  18358. timeStart('GENERATE', 1);
  18359. const outputBundleBase = Object.create(null);
  18360. const outputBundle = getOutputBundle(outputBundleBase);
  18361. this.pluginDriver.setOutputBundle(outputBundle, this.outputOptions);
  18362. try {
  18363. timeStart('initialize render', 2);
  18364. await this.pluginDriver.hookParallel('renderStart', [this.outputOptions, this.inputOptions]);
  18365. timeEnd('initialize render', 2);
  18366. timeStart('generate chunks', 2);
  18367. const getHashPlaceholder = getHashPlaceholderGenerator();
  18368. const chunks = await this.generateChunks(outputBundle, getHashPlaceholder);
  18369. if (chunks.length > 1) {
  18370. validateOptionsForMultiChunkOutput(this.outputOptions, this.inputOptions.onLog);
  18371. }
  18372. this.pluginDriver.setChunkInformation(this.facadeChunkByModule);
  18373. for (const chunk of chunks) {
  18374. chunk.generateExports();
  18375. }
  18376. timeEnd('generate chunks', 2);
  18377. await renderChunks(chunks, outputBundle, this.pluginDriver, this.outputOptions, this.inputOptions.onLog);
  18378. }
  18379. catch (error_) {
  18380. await this.pluginDriver.hookParallel('renderError', [error_]);
  18381. throw error_;
  18382. }
  18383. removeUnreferencedAssets(outputBundle);
  18384. timeStart('generate bundle', 2);
  18385. await this.pluginDriver.hookSeq('generateBundle', [
  18386. this.outputOptions,
  18387. outputBundle,
  18388. isWrite
  18389. ]);
  18390. this.finaliseAssets(outputBundle);
  18391. validateOutputBundleFileNames(outputBundle);
  18392. timeEnd('generate bundle', 2);
  18393. timeEnd('GENERATE', 1);
  18394. return outputBundleBase;
  18395. }
  18396. async addManualChunks(manualChunks) {
  18397. const manualChunkAliasByEntry = new Map();
  18398. const chunkEntries = await Promise.all(Object.entries(manualChunks).map(async ([alias, files]) => ({
  18399. alias,
  18400. entries: await this.graph.moduleLoader.addAdditionalModules(files, true)
  18401. })));
  18402. for (const { alias, entries } of chunkEntries) {
  18403. for (const entry of entries) {
  18404. addModuleToManualChunk(alias, entry, manualChunkAliasByEntry);
  18405. }
  18406. }
  18407. return manualChunkAliasByEntry;
  18408. }
  18409. assignManualChunks(getManualChunk) {
  18410. // eslint-disable-next-line unicorn/prefer-module
  18411. const manualChunkAliasesWithEntry = [];
  18412. const manualChunksApi = {
  18413. getModuleIds: () => this.graph.modulesById.keys(),
  18414. getModuleInfo: this.graph.getModuleInfo
  18415. };
  18416. for (const module of this.graph.modulesById.values()) {
  18417. if (module instanceof Module) {
  18418. const manualChunkAlias = getManualChunk(module.id, manualChunksApi);
  18419. if (typeof manualChunkAlias === 'string') {
  18420. manualChunkAliasesWithEntry.push([manualChunkAlias, module]);
  18421. }
  18422. }
  18423. }
  18424. manualChunkAliasesWithEntry.sort(([aliasA], [aliasB]) => aliasA > aliasB ? 1 : aliasA < aliasB ? -1 : 0);
  18425. const manualChunkAliasByEntry = new Map();
  18426. for (const [alias, module] of manualChunkAliasesWithEntry) {
  18427. addModuleToManualChunk(alias, module, manualChunkAliasByEntry);
  18428. }
  18429. return manualChunkAliasByEntry;
  18430. }
  18431. finaliseAssets(bundle) {
  18432. if (this.outputOptions.validate) {
  18433. for (const file of Object.values(bundle)) {
  18434. if ('code' in file) {
  18435. try {
  18436. this.graph.contextParse(file.code, {
  18437. ecmaVersion: 'latest'
  18438. });
  18439. }
  18440. catch (error_) {
  18441. this.inputOptions.onLog(LOGLEVEL_WARN, logChunkInvalid(file, error_));
  18442. }
  18443. }
  18444. }
  18445. }
  18446. this.pluginDriver.finaliseAssets();
  18447. }
  18448. async generateChunks(bundle, getHashPlaceholder) {
  18449. const { experimentalMinChunkSize, inlineDynamicImports, manualChunks, preserveModules } = this.outputOptions;
  18450. const manualChunkAliasByEntry = typeof manualChunks === 'object'
  18451. ? await this.addManualChunks(manualChunks)
  18452. : this.assignManualChunks(manualChunks);
  18453. const snippets = getGenerateCodeSnippets(this.outputOptions);
  18454. const includedModules = getIncludedModules(this.graph.modulesById);
  18455. const inputBase = commondir(getAbsoluteEntryModulePaths(includedModules, preserveModules));
  18456. const externalChunkByModule = getExternalChunkByModule(this.graph.modulesById, this.outputOptions, inputBase);
  18457. const chunks = [];
  18458. const chunkByModule = new Map();
  18459. for (const { alias, modules } of inlineDynamicImports
  18460. ? [{ alias: null, modules: includedModules }]
  18461. : preserveModules
  18462. ? includedModules.map(module => ({ alias: null, modules: [module] }))
  18463. : getChunkAssignments(this.graph.entryModules, manualChunkAliasByEntry, experimentalMinChunkSize, this.inputOptions.onLog)) {
  18464. sortByExecutionOrder(modules);
  18465. 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);
  18466. chunks.push(chunk);
  18467. }
  18468. for (const chunk of chunks) {
  18469. chunk.link();
  18470. }
  18471. const facades = [];
  18472. for (const chunk of chunks) {
  18473. facades.push(...chunk.generateFacades());
  18474. }
  18475. return [...chunks, ...facades];
  18476. }
  18477. }
  18478. function validateOptionsForMultiChunkOutput(outputOptions, log) {
  18479. if (outputOptions.format === 'umd' || outputOptions.format === 'iife')
  18480. return error(logInvalidOption('output.format', URL_OUTPUT_FORMAT, 'UMD and IIFE output formats are not supported for code-splitting builds', outputOptions.format));
  18481. if (typeof outputOptions.file === 'string')
  18482. 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'));
  18483. if (outputOptions.sourcemapFile)
  18484. return error(logInvalidOption('output.sourcemapFile', URL_OUTPUT_SOURCEMAPFILE, '"output.sourcemapFile" is only supported for single-file builds'));
  18485. if (!outputOptions.amd.autoId && outputOptions.amd.id)
  18486. 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'));
  18487. }
  18488. function getIncludedModules(modulesById) {
  18489. const includedModules = [];
  18490. for (const module of modulesById.values()) {
  18491. if (module instanceof Module &&
  18492. (module.isIncluded() || module.info.isEntry || module.includedDynamicImporters.length > 0)) {
  18493. includedModules.push(module);
  18494. }
  18495. }
  18496. return includedModules;
  18497. }
  18498. function getAbsoluteEntryModulePaths(includedModules, preserveModules) {
  18499. const absoluteEntryModulePaths = [];
  18500. for (const module of includedModules) {
  18501. if ((module.info.isEntry || preserveModules) && isAbsolute(module.id)) {
  18502. absoluteEntryModulePaths.push(module.id);
  18503. }
  18504. }
  18505. return absoluteEntryModulePaths;
  18506. }
  18507. function getExternalChunkByModule(modulesById, outputOptions, inputBase) {
  18508. const externalChunkByModule = new Map();
  18509. for (const module of modulesById.values()) {
  18510. if (module instanceof ExternalModule) {
  18511. externalChunkByModule.set(module, new ExternalChunk(module, outputOptions, inputBase));
  18512. }
  18513. }
  18514. return externalChunkByModule;
  18515. }
  18516. function addModuleToManualChunk(alias, module, manualChunkAliasByEntry) {
  18517. const existingAlias = manualChunkAliasByEntry.get(module);
  18518. if (typeof existingAlias === 'string' && existingAlias !== alias) {
  18519. return error(logCannotAssignModuleToChunk(module.id, alias, existingAlias));
  18520. }
  18521. manualChunkAliasByEntry.set(module, alias);
  18522. }
  18523. function isFileNameOutsideOutputDirectory(fileName) {
  18524. // Use join() to normalize ".." segments, then replace backslashes so the
  18525. // string checks below work identically on Windows and POSIX.
  18526. const normalized = node_path.join(fileName).replace(/\\/g, '/');
  18527. return (normalized === '..' ||
  18528. normalized.startsWith('../') ||
  18529. normalized === '.' ||
  18530. isAbsolute(normalized));
  18531. }
  18532. function validateOutputBundleFileNames(bundle) {
  18533. for (const [bundleKey, entry] of Object.entries(bundle)) {
  18534. if (isFileNameOutsideOutputDirectory(bundleKey)) {
  18535. return error(logFileNameOutsideOutputDirectory(bundleKey));
  18536. }
  18537. if (entry.type !== 'placeholder') {
  18538. const { fileName } = entry;
  18539. if (fileName !== bundleKey && isFileNameOutsideOutputDirectory(fileName)) {
  18540. return error(logFileNameOutsideOutputDirectory(fileName));
  18541. }
  18542. }
  18543. }
  18544. }
  18545. // This file was generated. Do not modify manually!
  18546. 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];
  18547. // This file was generated. Do not modify manually!
  18548. 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];
  18549. // This file was generated. Do not modify manually!
  18550. 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";
  18551. // This file was generated. Do not modify manually!
  18552. 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";
  18553. // These are a run-length and offset encoded representation of the
  18554. // >0xffff code points that are a valid part of identifiers. The
  18555. // offset starts at 0x10000, and each pair of numbers represents an
  18556. // offset to the next range, and then a size of the range.
  18557. // Reserved word lists for various dialects of the language
  18558. var reservedWords = {
  18559. 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",
  18560. 5: "class enum extends super const export import",
  18561. 6: "enum",
  18562. strict: "implements interface let package private protected public static yield",
  18563. strictBind: "eval arguments"
  18564. };
  18565. // And the keywords
  18566. 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";
  18567. var keywords$1 = {
  18568. 5: ecma5AndLessKeywords,
  18569. "5module": ecma5AndLessKeywords + " export import",
  18570. 6: ecma5AndLessKeywords + " const class extends export import super"
  18571. };
  18572. var keywordRelationalOperator = /^in(stanceof)?$/;
  18573. // ## Character categories
  18574. var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  18575. var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  18576. // This has a complexity linear to the value of the code. The
  18577. // assumption is that looking up astral identifier characters is
  18578. // rare.
  18579. function isInAstralSet(code, set) {
  18580. var pos = 0x10000;
  18581. for (var i = 0; i < set.length; i += 2) {
  18582. pos += set[i];
  18583. if (pos > code) { return false }
  18584. pos += set[i + 1];
  18585. if (pos >= code) { return true }
  18586. }
  18587. return false
  18588. }
  18589. // Test whether a given character code starts an identifier.
  18590. function isIdentifierStart(code, astral) {
  18591. if (code < 65) { return code === 36 }
  18592. if (code < 91) { return true }
  18593. if (code < 97) { return code === 95 }
  18594. if (code < 123) { return true }
  18595. if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) }
  18596. if (astral === false) { return false }
  18597. return isInAstralSet(code, astralIdentifierStartCodes)
  18598. }
  18599. // Test whether a given character is part of an identifier.
  18600. function isIdentifierChar(code, astral) {
  18601. if (code < 48) { return code === 36 }
  18602. if (code < 58) { return true }
  18603. if (code < 65) { return false }
  18604. if (code < 91) { return true }
  18605. if (code < 97) { return code === 95 }
  18606. if (code < 123) { return true }
  18607. if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) }
  18608. if (astral === false) { return false }
  18609. return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes)
  18610. }
  18611. // ## Token types
  18612. // The assignment of fine-grained, information-carrying type objects
  18613. // allows the tokenizer to store the information it has about a
  18614. // token in a way that is very cheap for the parser to look up.
  18615. // All token type variables start with an underscore, to make them
  18616. // easy to recognize.
  18617. // The `beforeExpr` property is used to disambiguate between regular
  18618. // expressions and divisions. It is set on all token types that can
  18619. // be followed by an expression (thus, a slash after them would be a
  18620. // regular expression).
  18621. //
  18622. // The `startsExpr` property is used to check if the token ends a
  18623. // `yield` expression. It is set on all token types that either can
  18624. // directly start an expression (like a quotation mark) or can
  18625. // continue an expression (like the body of a string).
  18626. //
  18627. // `isLoop` marks a keyword as starting a loop, which is important
  18628. // to know when parsing a label, in order to allow or disallow
  18629. // continue jumps to that label.
  18630. var TokenType = function TokenType(label, conf) {
  18631. if ( conf === void 0 ) conf = {};
  18632. this.label = label;
  18633. this.keyword = conf.keyword;
  18634. this.beforeExpr = !!conf.beforeExpr;
  18635. this.startsExpr = !!conf.startsExpr;
  18636. this.isLoop = !!conf.isLoop;
  18637. this.isAssign = !!conf.isAssign;
  18638. this.prefix = !!conf.prefix;
  18639. this.postfix = !!conf.postfix;
  18640. this.binop = conf.binop || null;
  18641. this.updateContext = null;
  18642. };
  18643. function binop(name, prec) {
  18644. return new TokenType(name, {beforeExpr: true, binop: prec})
  18645. }
  18646. var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true};
  18647. // Map keyword names to token types.
  18648. var keywords = {};
  18649. // Succinct definitions of keyword token types
  18650. function kw(name, options) {
  18651. if ( options === void 0 ) options = {};
  18652. options.keyword = name;
  18653. return keywords[name] = new TokenType(name, options)
  18654. }
  18655. var types$1 = {
  18656. num: new TokenType("num", startsExpr),
  18657. regexp: new TokenType("regexp", startsExpr),
  18658. string: new TokenType("string", startsExpr),
  18659. name: new TokenType("name", startsExpr),
  18660. privateId: new TokenType("privateId", startsExpr),
  18661. eof: new TokenType("eof"),
  18662. // Punctuation token types.
  18663. bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}),
  18664. bracketR: new TokenType("]"),
  18665. braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}),
  18666. braceR: new TokenType("}"),
  18667. parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}),
  18668. parenR: new TokenType(")"),
  18669. comma: new TokenType(",", beforeExpr),
  18670. semi: new TokenType(";", beforeExpr),
  18671. colon: new TokenType(":", beforeExpr),
  18672. dot: new TokenType("."),
  18673. question: new TokenType("?", beforeExpr),
  18674. questionDot: new TokenType("?."),
  18675. arrow: new TokenType("=>", beforeExpr),
  18676. template: new TokenType("template"),
  18677. invalidTemplate: new TokenType("invalidTemplate"),
  18678. ellipsis: new TokenType("...", beforeExpr),
  18679. backQuote: new TokenType("`", startsExpr),
  18680. dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}),
  18681. // Operators. These carry several kinds of properties to help the
  18682. // parser use them properly (the presence of these properties is
  18683. // what categorizes them as operators).
  18684. //
  18685. // `binop`, when present, specifies that this operator is a binary
  18686. // operator, and will refer to its precedence.
  18687. //
  18688. // `prefix` and `postfix` mark the operator as a prefix or postfix
  18689. // unary operator.
  18690. //
  18691. // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
  18692. // binary operators with a very low precedence, that should result
  18693. // in AssignmentExpression nodes.
  18694. eq: new TokenType("=", {beforeExpr: true, isAssign: true}),
  18695. assign: new TokenType("_=", {beforeExpr: true, isAssign: true}),
  18696. incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}),
  18697. prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}),
  18698. logicalOR: binop("||", 1),
  18699. logicalAND: binop("&&", 2),
  18700. bitwiseOR: binop("|", 3),
  18701. bitwiseXOR: binop("^", 4),
  18702. bitwiseAND: binop("&", 5),
  18703. equality: binop("==/!=/===/!==", 6),
  18704. relational: binop("</>/<=/>=", 7),
  18705. bitShift: binop("<</>>/>>>", 8),
  18706. plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}),
  18707. modulo: binop("%", 10),
  18708. star: binop("*", 10),
  18709. slash: binop("/", 10),
  18710. starstar: new TokenType("**", {beforeExpr: true}),
  18711. coalesce: binop("??", 1),
  18712. // Keyword token types.
  18713. _break: kw("break"),
  18714. _case: kw("case", beforeExpr),
  18715. _catch: kw("catch"),
  18716. _continue: kw("continue"),
  18717. _debugger: kw("debugger"),
  18718. _default: kw("default", beforeExpr),
  18719. _do: kw("do", {isLoop: true, beforeExpr: true}),
  18720. _else: kw("else", beforeExpr),
  18721. _finally: kw("finally"),
  18722. _for: kw("for", {isLoop: true}),
  18723. _function: kw("function", startsExpr),
  18724. _if: kw("if"),
  18725. _return: kw("return", beforeExpr),
  18726. _switch: kw("switch"),
  18727. _throw: kw("throw", beforeExpr),
  18728. _try: kw("try"),
  18729. _var: kw("var"),
  18730. _const: kw("const"),
  18731. _while: kw("while", {isLoop: true}),
  18732. _with: kw("with"),
  18733. _new: kw("new", {beforeExpr: true, startsExpr: true}),
  18734. _this: kw("this", startsExpr),
  18735. _super: kw("super", startsExpr),
  18736. _class: kw("class", startsExpr),
  18737. _extends: kw("extends", beforeExpr),
  18738. _export: kw("export"),
  18739. _import: kw("import", startsExpr),
  18740. _null: kw("null", startsExpr),
  18741. _true: kw("true", startsExpr),
  18742. _false: kw("false", startsExpr),
  18743. _in: kw("in", {beforeExpr: true, binop: 7}),
  18744. _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}),
  18745. _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}),
  18746. _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}),
  18747. _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true})
  18748. };
  18749. // Matches a whole line break (where CRLF is considered a single
  18750. // line break). Used to count lines.
  18751. var lineBreak = /\r\n?|\n|\u2028|\u2029/;
  18752. var lineBreakG = new RegExp(lineBreak.source, "g");
  18753. function isNewLine(code) {
  18754. return code === 10 || code === 13 || code === 0x2028 || code === 0x2029
  18755. }
  18756. function nextLineBreak(code, from, end) {
  18757. if ( end === void 0 ) end = code.length;
  18758. for (var i = from; i < end; i++) {
  18759. var next = code.charCodeAt(i);
  18760. if (isNewLine(next))
  18761. { return i < end - 1 && next === 13 && code.charCodeAt(i + 1) === 10 ? i + 2 : i + 1 }
  18762. }
  18763. return -1
  18764. }
  18765. var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
  18766. var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
  18767. var ref = Object.prototype;
  18768. var hasOwnProperty = ref.hasOwnProperty;
  18769. var toString = ref.toString;
  18770. var hasOwn = Object.hasOwn || (function (obj, propName) { return (
  18771. hasOwnProperty.call(obj, propName)
  18772. ); });
  18773. var isArray = Array.isArray || (function (obj) { return (
  18774. toString.call(obj) === "[object Array]"
  18775. ); });
  18776. function wordsRegexp(words) {
  18777. return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$")
  18778. }
  18779. function codePointToString(code) {
  18780. // UTF-16 Decoding
  18781. if (code <= 0xFFFF) { return String.fromCharCode(code) }
  18782. code -= 0x10000;
  18783. return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00)
  18784. }
  18785. var loneSurrogate = /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/;
  18786. // These are used when `options.locations` is on, for the
  18787. // `startLoc` and `endLoc` properties.
  18788. var Position = function Position(line, col) {
  18789. this.line = line;
  18790. this.column = col;
  18791. };
  18792. Position.prototype.offset = function offset (n) {
  18793. return new Position(this.line, this.column + n)
  18794. };
  18795. var SourceLocation = function SourceLocation(p, start, end) {
  18796. this.start = start;
  18797. this.end = end;
  18798. if (p.sourceFile !== null) { this.source = p.sourceFile; }
  18799. };
  18800. // The `getLineInfo` function is mostly useful when the
  18801. // `locations` option is off (for performance reasons) and you
  18802. // want to find the line/column position for a given character
  18803. // offset. `input` should be the code string that the offset refers
  18804. // into.
  18805. function getLineInfo(input, offset) {
  18806. for (var line = 1, cur = 0;;) {
  18807. var nextBreak = nextLineBreak(input, cur, offset);
  18808. if (nextBreak < 0) { return new Position(line, offset - cur) }
  18809. ++line;
  18810. cur = nextBreak;
  18811. }
  18812. }
  18813. // A second argument must be given to configure the parser process.
  18814. // These options are recognized (only `ecmaVersion` is required):
  18815. var defaultOptions = {
  18816. // `ecmaVersion` indicates the ECMAScript version to parse. Must be
  18817. // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10
  18818. // (2019), 11 (2020), 12 (2021), 13 (2022), 14 (2023), or `"latest"`
  18819. // (the latest version the library supports). This influences
  18820. // support for strict mode, the set of reserved words, and support
  18821. // for new syntax features.
  18822. ecmaVersion: null,
  18823. // `sourceType` indicates the mode the code should be parsed in.
  18824. // Can be either `"script"` or `"module"`. This influences global
  18825. // strict mode and parsing of `import` and `export` declarations.
  18826. sourceType: "script",
  18827. // `onInsertedSemicolon` can be a callback that will be called
  18828. // when a semicolon is automatically inserted. It will be passed
  18829. // the position of the comma as an offset, and if `locations` is
  18830. // enabled, it is given the location as a `{line, column}` object
  18831. // as second argument.
  18832. onInsertedSemicolon: null,
  18833. // `onTrailingComma` is similar to `onInsertedSemicolon`, but for
  18834. // trailing commas.
  18835. onTrailingComma: null,
  18836. // By default, reserved words are only enforced if ecmaVersion >= 5.
  18837. // Set `allowReserved` to a boolean value to explicitly turn this on
  18838. // an off. When this option has the value "never", reserved words
  18839. // and keywords can also not be used as property names.
  18840. allowReserved: null,
  18841. // When enabled, a return at the top level is not considered an
  18842. // error.
  18843. allowReturnOutsideFunction: false,
  18844. // When enabled, import/export statements are not constrained to
  18845. // appearing at the top of the program, and an import.meta expression
  18846. // in a script isn't considered an error.
  18847. allowImportExportEverywhere: false,
  18848. // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022.
  18849. // When enabled, await identifiers are allowed to appear at the top-level scope,
  18850. // but they are still not allowed in non-async functions.
  18851. allowAwaitOutsideFunction: null,
  18852. // When enabled, super identifiers are not constrained to
  18853. // appearing in methods and do not raise an error when they appear elsewhere.
  18854. allowSuperOutsideMethod: null,
  18855. // When enabled, hashbang directive in the beginning of file is
  18856. // allowed and treated as a line comment. Enabled by default when
  18857. // `ecmaVersion` >= 2023.
  18858. allowHashBang: false,
  18859. // By default, the parser will verify that private properties are
  18860. // only used in places where they are valid and have been declared.
  18861. // Set this to false to turn such checks off.
  18862. checkPrivateFields: true,
  18863. // When `locations` is on, `loc` properties holding objects with
  18864. // `start` and `end` properties in `{line, column}` form (with
  18865. // line being 1-based and column 0-based) will be attached to the
  18866. // nodes.
  18867. locations: false,
  18868. // A function can be passed as `onToken` option, which will
  18869. // cause Acorn to call that function with object in the same
  18870. // format as tokens returned from `tokenizer().getToken()`. Note
  18871. // that you are not allowed to call the parser from the
  18872. // callback—that will corrupt its internal state.
  18873. onToken: null,
  18874. // A function can be passed as `onComment` option, which will
  18875. // cause Acorn to call that function with `(block, text, start,
  18876. // end)` parameters whenever a comment is skipped. `block` is a
  18877. // boolean indicating whether this is a block (`/* */`) comment,
  18878. // `text` is the content of the comment, and `start` and `end` are
  18879. // character offsets that denote the start and end of the comment.
  18880. // When the `locations` option is on, two more parameters are
  18881. // passed, the full `{line, column}` locations of the start and
  18882. // end of the comments. Note that you are not allowed to call the
  18883. // parser from the callback—that will corrupt its internal state.
  18884. onComment: null,
  18885. // Nodes have their start and end characters offsets recorded in
  18886. // `start` and `end` properties (directly on the node, rather than
  18887. // the `loc` object, which holds line/column data. To also add a
  18888. // [semi-standardized][range] `range` property holding a `[start,
  18889. // end]` array with the same numbers, set the `ranges` option to
  18890. // `true`.
  18891. //
  18892. // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
  18893. ranges: false,
  18894. // It is possible to parse multiple files into a single AST by
  18895. // passing the tree produced by parsing the first file as
  18896. // `program` option in subsequent parses. This will add the
  18897. // toplevel forms of the parsed file to the `Program` (top) node
  18898. // of an existing parse tree.
  18899. program: null,
  18900. // When `locations` is on, you can pass this to record the source
  18901. // file in every node's `loc` object.
  18902. sourceFile: null,
  18903. // This value, if given, is stored in every node, whether
  18904. // `locations` is on or off.
  18905. directSourceFile: null,
  18906. // When enabled, parenthesized expressions are represented by
  18907. // (non-standard) ParenthesizedExpression nodes
  18908. preserveParens: false
  18909. };
  18910. // Interpret and default an options object
  18911. var warnedAboutEcmaVersion = false;
  18912. function getOptions(opts) {
  18913. var options = {};
  18914. for (var opt in defaultOptions)
  18915. { options[opt] = opts && hasOwn(opts, opt) ? opts[opt] : defaultOptions[opt]; }
  18916. if (options.ecmaVersion === "latest") {
  18917. options.ecmaVersion = 1e8;
  18918. } else if (options.ecmaVersion == null) {
  18919. if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) {
  18920. warnedAboutEcmaVersion = true;
  18921. console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.");
  18922. }
  18923. options.ecmaVersion = 11;
  18924. } else if (options.ecmaVersion >= 2015) {
  18925. options.ecmaVersion -= 2009;
  18926. }
  18927. if (options.allowReserved == null)
  18928. { options.allowReserved = options.ecmaVersion < 5; }
  18929. if (!opts || opts.allowHashBang == null)
  18930. { options.allowHashBang = options.ecmaVersion >= 14; }
  18931. if (isArray(options.onToken)) {
  18932. var tokens = options.onToken;
  18933. options.onToken = function (token) { return tokens.push(token); };
  18934. }
  18935. if (isArray(options.onComment))
  18936. { options.onComment = pushComment(options, options.onComment); }
  18937. return options
  18938. }
  18939. function pushComment(options, array) {
  18940. return function(block, text, start, end, startLoc, endLoc) {
  18941. var comment = {
  18942. type: block ? "Block" : "Line",
  18943. value: text,
  18944. start: start,
  18945. end: end
  18946. };
  18947. if (options.locations)
  18948. { comment.loc = new SourceLocation(this, startLoc, endLoc); }
  18949. if (options.ranges)
  18950. { comment.range = [start, end]; }
  18951. array.push(comment);
  18952. }
  18953. }
  18954. // Each scope gets a bitset that may contain these flags
  18955. var
  18956. SCOPE_TOP = 1,
  18957. SCOPE_FUNCTION = 2,
  18958. SCOPE_ASYNC = 4,
  18959. SCOPE_GENERATOR = 8,
  18960. SCOPE_ARROW = 16,
  18961. SCOPE_SIMPLE_CATCH = 32,
  18962. SCOPE_SUPER = 64,
  18963. SCOPE_DIRECT_SUPER = 128,
  18964. SCOPE_CLASS_STATIC_BLOCK = 256,
  18965. SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK;
  18966. function functionFlags(async, generator) {
  18967. return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0)
  18968. }
  18969. // Used in checkLVal* and declareName to determine the type of a binding
  18970. var
  18971. BIND_NONE = 0, // Not a binding
  18972. BIND_VAR = 1, // Var-style binding
  18973. BIND_LEXICAL = 2, // Let- or const-style binding
  18974. BIND_FUNCTION = 3, // Function declaration
  18975. BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding
  18976. BIND_OUTSIDE = 5; // Special case for function names as bound inside the function
  18977. var Parser = function Parser(options, input, startPos) {
  18978. this.options = options = getOptions(options);
  18979. this.sourceFile = options.sourceFile;
  18980. this.keywords = wordsRegexp(keywords$1[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);
  18981. var reserved = "";
  18982. if (options.allowReserved !== true) {
  18983. reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3];
  18984. if (options.sourceType === "module") { reserved += " await"; }
  18985. }
  18986. this.reservedWords = wordsRegexp(reserved);
  18987. var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict;
  18988. this.reservedWordsStrict = wordsRegexp(reservedStrict);
  18989. this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind);
  18990. this.input = String(input);
  18991. // Used to signal to callers of `readWord1` whether the word
  18992. // contained any escape sequences. This is needed because words with
  18993. // escape sequences must not be interpreted as keywords.
  18994. this.containsEsc = false;
  18995. // Set up token state
  18996. // The current position of the tokenizer in the input.
  18997. if (startPos) {
  18998. this.pos = startPos;
  18999. this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;
  19000. this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;
  19001. } else {
  19002. this.pos = this.lineStart = 0;
  19003. this.curLine = 1;
  19004. }
  19005. // Properties of the current token:
  19006. // Its type
  19007. this.type = types$1.eof;
  19008. // For tokens that include more information than their type, the value
  19009. this.value = null;
  19010. // Its start and end offset
  19011. this.start = this.end = this.pos;
  19012. // And, if locations are used, the {line, column} object
  19013. // corresponding to those offsets
  19014. this.startLoc = this.endLoc = this.curPosition();
  19015. // Position information for the previous token
  19016. this.lastTokEndLoc = this.lastTokStartLoc = null;
  19017. this.lastTokStart = this.lastTokEnd = this.pos;
  19018. // The context stack is used to superficially track syntactic
  19019. // context to predict whether a regular expression is allowed in a
  19020. // given position.
  19021. this.context = this.initialContext();
  19022. this.exprAllowed = true;
  19023. // Figure out if it's a module code.
  19024. this.inModule = options.sourceType === "module";
  19025. this.strict = this.inModule || this.strictDirective(this.pos);
  19026. // Used to signify the start of a potential arrow function
  19027. this.potentialArrowAt = -1;
  19028. this.potentialArrowInForAwait = false;
  19029. // Positions to delayed-check that yield/await does not exist in default parameters.
  19030. this.yieldPos = this.awaitPos = this.awaitIdentPos = 0;
  19031. // Labels in scope.
  19032. this.labels = [];
  19033. // Thus-far undefined exports.
  19034. this.undefinedExports = Object.create(null);
  19035. // If enabled, skip leading hashbang line.
  19036. if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!")
  19037. { this.skipLineComment(2); }
  19038. // Scope tracking for duplicate variable names (see scope.js)
  19039. this.scopeStack = [];
  19040. this.enterScope(SCOPE_TOP);
  19041. // For RegExp validation
  19042. this.regexpState = null;
  19043. // The stack of private names.
  19044. // Each element has two properties: 'declared' and 'used'.
  19045. // When it exited from the outermost class definition, all used private names must be declared.
  19046. this.privateNameStack = [];
  19047. };
  19048. 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 } };
  19049. Parser.prototype.parse = function parse () {
  19050. var node = this.options.program || this.startNode();
  19051. this.nextToken();
  19052. return this.parseTopLevel(node)
  19053. };
  19054. prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 };
  19055. prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 && !this.currentVarScope().inClassFieldInit };
  19056. prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 && !this.currentVarScope().inClassFieldInit };
  19057. prototypeAccessors.canAwait.get = function () {
  19058. for (var i = this.scopeStack.length - 1; i >= 0; i--) {
  19059. var scope = this.scopeStack[i];
  19060. if (scope.inClassFieldInit || scope.flags & SCOPE_CLASS_STATIC_BLOCK) { return false }
  19061. if (scope.flags & SCOPE_FUNCTION) { return (scope.flags & SCOPE_ASYNC) > 0 }
  19062. }
  19063. return (this.inModule && this.options.ecmaVersion >= 13) || this.options.allowAwaitOutsideFunction
  19064. };
  19065. prototypeAccessors.allowSuper.get = function () {
  19066. var ref = this.currentThisScope();
  19067. var flags = ref.flags;
  19068. var inClassFieldInit = ref.inClassFieldInit;
  19069. return (flags & SCOPE_SUPER) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod
  19070. };
  19071. prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 };
  19072. prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) };
  19073. prototypeAccessors.allowNewDotTarget.get = function () {
  19074. var ref = this.currentThisScope();
  19075. var flags = ref.flags;
  19076. var inClassFieldInit = ref.inClassFieldInit;
  19077. return (flags & (SCOPE_FUNCTION | SCOPE_CLASS_STATIC_BLOCK)) > 0 || inClassFieldInit
  19078. };
  19079. prototypeAccessors.inClassStaticBlock.get = function () {
  19080. return (this.currentVarScope().flags & SCOPE_CLASS_STATIC_BLOCK) > 0
  19081. };
  19082. Parser.extend = function extend () {
  19083. var plugins = [], len = arguments.length;
  19084. while ( len-- ) plugins[ len ] = arguments[ len ];
  19085. var cls = this;
  19086. for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); }
  19087. return cls
  19088. };
  19089. Parser.parse = function parse (input, options) {
  19090. return new this(options, input).parse()
  19091. };
  19092. Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) {
  19093. var parser = new this(options, input, pos);
  19094. parser.nextToken();
  19095. return parser.parseExpression()
  19096. };
  19097. Parser.tokenizer = function tokenizer (input, options) {
  19098. return new this(options, input)
  19099. };
  19100. Object.defineProperties( Parser.prototype, prototypeAccessors );
  19101. var pp$9 = Parser.prototype;
  19102. // ## Parser utilities
  19103. var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/;
  19104. pp$9.strictDirective = function(start) {
  19105. if (this.options.ecmaVersion < 5) { return false }
  19106. for (;;) {
  19107. // Try to find string literal.
  19108. skipWhiteSpace.lastIndex = start;
  19109. start += skipWhiteSpace.exec(this.input)[0].length;
  19110. var match = literal.exec(this.input.slice(start));
  19111. if (!match) { return false }
  19112. if ((match[1] || match[2]) === "use strict") {
  19113. skipWhiteSpace.lastIndex = start + match[0].length;
  19114. var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length;
  19115. var next = this.input.charAt(end);
  19116. return next === ";" || next === "}" ||
  19117. (lineBreak.test(spaceAfter[0]) &&
  19118. !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "="))
  19119. }
  19120. start += match[0].length;
  19121. // Skip semicolon, if any.
  19122. skipWhiteSpace.lastIndex = start;
  19123. start += skipWhiteSpace.exec(this.input)[0].length;
  19124. if (this.input[start] === ";")
  19125. { start++; }
  19126. }
  19127. };
  19128. // Predicate that tests whether the next token is of the given
  19129. // type, and if yes, consumes it as a side effect.
  19130. pp$9.eat = function(type) {
  19131. if (this.type === type) {
  19132. this.next();
  19133. return true
  19134. } else {
  19135. return false
  19136. }
  19137. };
  19138. // Tests whether parsed token is a contextual keyword.
  19139. pp$9.isContextual = function(name) {
  19140. return this.type === types$1.name && this.value === name && !this.containsEsc
  19141. };
  19142. // Consumes contextual keyword if possible.
  19143. pp$9.eatContextual = function(name) {
  19144. if (!this.isContextual(name)) { return false }
  19145. this.next();
  19146. return true
  19147. };
  19148. // Asserts that following token is given contextual keyword.
  19149. pp$9.expectContextual = function(name) {
  19150. if (!this.eatContextual(name)) { this.unexpected(); }
  19151. };
  19152. // Test whether a semicolon can be inserted at the current position.
  19153. pp$9.canInsertSemicolon = function() {
  19154. return this.type === types$1.eof ||
  19155. this.type === types$1.braceR ||
  19156. lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
  19157. };
  19158. pp$9.insertSemicolon = function() {
  19159. if (this.canInsertSemicolon()) {
  19160. if (this.options.onInsertedSemicolon)
  19161. { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); }
  19162. return true
  19163. }
  19164. };
  19165. // Consume a semicolon, or, failing that, see if we are allowed to
  19166. // pretend that there is a semicolon at this position.
  19167. pp$9.semicolon = function() {
  19168. if (!this.eat(types$1.semi) && !this.insertSemicolon()) { this.unexpected(); }
  19169. };
  19170. pp$9.afterTrailingComma = function(tokType, notNext) {
  19171. if (this.type === tokType) {
  19172. if (this.options.onTrailingComma)
  19173. { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); }
  19174. if (!notNext)
  19175. { this.next(); }
  19176. return true
  19177. }
  19178. };
  19179. // Expect a token of a given type. If found, consume it, otherwise,
  19180. // raise an unexpected token error.
  19181. pp$9.expect = function(type) {
  19182. this.eat(type) || this.unexpected();
  19183. };
  19184. // Raise an unexpected token error.
  19185. pp$9.unexpected = function(pos) {
  19186. this.raise(pos != null ? pos : this.start, "Unexpected token");
  19187. };
  19188. var DestructuringErrors = function DestructuringErrors() {
  19189. this.shorthandAssign =
  19190. this.trailingComma =
  19191. this.parenthesizedAssign =
  19192. this.parenthesizedBind =
  19193. this.doubleProto =
  19194. -1;
  19195. };
  19196. pp$9.checkPatternErrors = function(refDestructuringErrors, isAssign) {
  19197. if (!refDestructuringErrors) { return }
  19198. if (refDestructuringErrors.trailingComma > -1)
  19199. { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); }
  19200. var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;
  19201. if (parens > -1) { this.raiseRecoverable(parens, isAssign ? "Assigning to rvalue" : "Parenthesized pattern"); }
  19202. };
  19203. pp$9.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
  19204. if (!refDestructuringErrors) { return false }
  19205. var shorthandAssign = refDestructuringErrors.shorthandAssign;
  19206. var doubleProto = refDestructuringErrors.doubleProto;
  19207. if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 }
  19208. if (shorthandAssign >= 0)
  19209. { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); }
  19210. if (doubleProto >= 0)
  19211. { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); }
  19212. };
  19213. pp$9.checkYieldAwaitInDefaultParams = function() {
  19214. if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos))
  19215. { this.raise(this.yieldPos, "Yield expression cannot be a default value"); }
  19216. if (this.awaitPos)
  19217. { this.raise(this.awaitPos, "Await expression cannot be a default value"); }
  19218. };
  19219. pp$9.isSimpleAssignTarget = function(expr) {
  19220. if (expr.type === "ParenthesizedExpression")
  19221. { return this.isSimpleAssignTarget(expr.expression) }
  19222. return expr.type === "Identifier" || expr.type === "MemberExpression"
  19223. };
  19224. var pp$8 = Parser.prototype;
  19225. // ### Statement parsing
  19226. // Parse a program. Initializes the parser, reads any number of
  19227. // statements, and wraps them in a Program node. Optionally takes a
  19228. // `program` argument. If present, the statements will be appended
  19229. // to its body instead of creating a new node.
  19230. pp$8.parseTopLevel = function(node) {
  19231. var exports = Object.create(null);
  19232. if (!node.body) { node.body = []; }
  19233. while (this.type !== types$1.eof) {
  19234. var stmt = this.parseStatement(null, true, exports);
  19235. node.body.push(stmt);
  19236. }
  19237. if (this.inModule)
  19238. { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1)
  19239. {
  19240. var name = list[i];
  19241. this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined"));
  19242. } }
  19243. this.adaptDirectivePrologue(node.body);
  19244. this.next();
  19245. node.sourceType = this.options.sourceType;
  19246. return this.finishNode(node, "Program")
  19247. };
  19248. var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"};
  19249. pp$8.isLet = function(context) {
  19250. if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false }
  19251. skipWhiteSpace.lastIndex = this.pos;
  19252. var skip = skipWhiteSpace.exec(this.input);
  19253. var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
  19254. // For ambiguous cases, determine if a LexicalDeclaration (or only a
  19255. // Statement) is allowed here. If context is not empty then only a Statement
  19256. // is allowed. However, `let [` is an explicit negative lookahead for
  19257. // ExpressionStatement, so special-case it first.
  19258. if (nextCh === 91 || nextCh === 92) { return true } // '[', '/'
  19259. if (context) { return false }
  19260. if (nextCh === 123 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } // '{', astral
  19261. if (isIdentifierStart(nextCh, true)) {
  19262. var pos = next + 1;
  19263. while (isIdentifierChar(nextCh = this.input.charCodeAt(pos), true)) { ++pos; }
  19264. if (nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true }
  19265. var ident = this.input.slice(next, pos);
  19266. if (!keywordRelationalOperator.test(ident)) { return true }
  19267. }
  19268. return false
  19269. };
  19270. // check 'async [no LineTerminator here] function'
  19271. // - 'async /*foo*/ function' is OK.
  19272. // - 'async /*\n*/ function' is invalid.
  19273. pp$8.isAsyncFunction = function() {
  19274. if (this.options.ecmaVersion < 8 || !this.isContextual("async"))
  19275. { return false }
  19276. skipWhiteSpace.lastIndex = this.pos;
  19277. var skip = skipWhiteSpace.exec(this.input);
  19278. var next = this.pos + skip[0].length, after;
  19279. return !lineBreak.test(this.input.slice(this.pos, next)) &&
  19280. this.input.slice(next, next + 8) === "function" &&
  19281. (next + 8 === this.input.length ||
  19282. !(isIdentifierChar(after = this.input.charCodeAt(next + 8)) || after > 0xd7ff && after < 0xdc00))
  19283. };
  19284. // Parse a single statement.
  19285. //
  19286. // If expecting a statement and finding a slash operator, parse a
  19287. // regular expression literal. This is to handle cases like
  19288. // `if (foo) /blah/.exec(foo)`, where looking at the previous token
  19289. // does not help.
  19290. pp$8.parseStatement = function(context, topLevel, exports) {
  19291. var starttype = this.type, node = this.startNode(), kind;
  19292. if (this.isLet(context)) {
  19293. starttype = types$1._var;
  19294. kind = "let";
  19295. }
  19296. // Most types of statements are recognized by the keyword they
  19297. // start with. Many are trivial to parse, some require a bit of
  19298. // complexity.
  19299. switch (starttype) {
  19300. case types$1._break: case types$1._continue: return this.parseBreakContinueStatement(node, starttype.keyword)
  19301. case types$1._debugger: return this.parseDebuggerStatement(node)
  19302. case types$1._do: return this.parseDoStatement(node)
  19303. case types$1._for: return this.parseForStatement(node)
  19304. case types$1._function:
  19305. // Function as sole body of either an if statement or a labeled statement
  19306. // works, but not when it is part of a labeled statement that is the sole
  19307. // body of an if statement.
  19308. if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); }
  19309. return this.parseFunctionStatement(node, false, !context)
  19310. case types$1._class:
  19311. if (context) { this.unexpected(); }
  19312. return this.parseClass(node, true)
  19313. case types$1._if: return this.parseIfStatement(node)
  19314. case types$1._return: return this.parseReturnStatement(node)
  19315. case types$1._switch: return this.parseSwitchStatement(node)
  19316. case types$1._throw: return this.parseThrowStatement(node)
  19317. case types$1._try: return this.parseTryStatement(node)
  19318. case types$1._const: case types$1._var:
  19319. kind = kind || this.value;
  19320. if (context && kind !== "var") { this.unexpected(); }
  19321. return this.parseVarStatement(node, kind)
  19322. case types$1._while: return this.parseWhileStatement(node)
  19323. case types$1._with: return this.parseWithStatement(node)
  19324. case types$1.braceL: return this.parseBlock(true, node)
  19325. case types$1.semi: return this.parseEmptyStatement(node)
  19326. case types$1._export:
  19327. case types$1._import:
  19328. if (this.options.ecmaVersion > 10 && starttype === types$1._import) {
  19329. skipWhiteSpace.lastIndex = this.pos;
  19330. var skip = skipWhiteSpace.exec(this.input);
  19331. var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
  19332. if (nextCh === 40 || nextCh === 46) // '(' or '.'
  19333. { return this.parseExpressionStatement(node, this.parseExpression()) }
  19334. }
  19335. if (!this.options.allowImportExportEverywhere) {
  19336. if (!topLevel)
  19337. { this.raise(this.start, "'import' and 'export' may only appear at the top level"); }
  19338. if (!this.inModule)
  19339. { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); }
  19340. }
  19341. return starttype === types$1._import ? this.parseImport(node) : this.parseExport(node, exports)
  19342. // If the statement does not start with a statement keyword or a
  19343. // brace, it's an ExpressionStatement or LabeledStatement. We
  19344. // simply start parsing an expression, and afterwards, if the
  19345. // next token is a colon and the expression was a simple
  19346. // Identifier node, we switch to interpreting it as a label.
  19347. default:
  19348. if (this.isAsyncFunction()) {
  19349. if (context) { this.unexpected(); }
  19350. this.next();
  19351. return this.parseFunctionStatement(node, true, !context)
  19352. }
  19353. var maybeName = this.value, expr = this.parseExpression();
  19354. if (starttype === types$1.name && expr.type === "Identifier" && this.eat(types$1.colon))
  19355. { return this.parseLabeledStatement(node, maybeName, expr, context) }
  19356. else { return this.parseExpressionStatement(node, expr) }
  19357. }
  19358. };
  19359. pp$8.parseBreakContinueStatement = function(node, keyword) {
  19360. var isBreak = keyword === "break";
  19361. this.next();
  19362. if (this.eat(types$1.semi) || this.insertSemicolon()) { node.label = null; }
  19363. else if (this.type !== types$1.name) { this.unexpected(); }
  19364. else {
  19365. node.label = this.parseIdent();
  19366. this.semicolon();
  19367. }
  19368. // Verify that there is an actual destination to break or
  19369. // continue to.
  19370. var i = 0;
  19371. for (; i < this.labels.length; ++i) {
  19372. var lab = this.labels[i];
  19373. if (node.label == null || lab.name === node.label.name) {
  19374. if (lab.kind != null && (isBreak || lab.kind === "loop")) { break }
  19375. if (node.label && isBreak) { break }
  19376. }
  19377. }
  19378. if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); }
  19379. return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement")
  19380. };
  19381. pp$8.parseDebuggerStatement = function(node) {
  19382. this.next();
  19383. this.semicolon();
  19384. return this.finishNode(node, "DebuggerStatement")
  19385. };
  19386. pp$8.parseDoStatement = function(node) {
  19387. this.next();
  19388. this.labels.push(loopLabel);
  19389. node.body = this.parseStatement("do");
  19390. this.labels.pop();
  19391. this.expect(types$1._while);
  19392. node.test = this.parseParenExpression();
  19393. if (this.options.ecmaVersion >= 6)
  19394. { this.eat(types$1.semi); }
  19395. else
  19396. { this.semicolon(); }
  19397. return this.finishNode(node, "DoWhileStatement")
  19398. };
  19399. // Disambiguating between a `for` and a `for`/`in` or `for`/`of`
  19400. // loop is non-trivial. Basically, we have to parse the init `var`
  19401. // statement or expression, disallowing the `in` operator (see
  19402. // the second parameter to `parseExpression`), and then check
  19403. // whether the next token is `in` or `of`. When there is no init
  19404. // part (semicolon immediately after the opening parenthesis), it
  19405. // is a regular `for` loop.
  19406. pp$8.parseForStatement = function(node) {
  19407. this.next();
  19408. var awaitAt = (this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await")) ? this.lastTokStart : -1;
  19409. this.labels.push(loopLabel);
  19410. this.enterScope(0);
  19411. this.expect(types$1.parenL);
  19412. if (this.type === types$1.semi) {
  19413. if (awaitAt > -1) { this.unexpected(awaitAt); }
  19414. return this.parseFor(node, null)
  19415. }
  19416. var isLet = this.isLet();
  19417. if (this.type === types$1._var || this.type === types$1._const || isLet) {
  19418. var init$1 = this.startNode(), kind = isLet ? "let" : this.value;
  19419. this.next();
  19420. this.parseVar(init$1, true, kind);
  19421. this.finishNode(init$1, "VariableDeclaration");
  19422. if ((this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) {
  19423. if (this.options.ecmaVersion >= 9) {
  19424. if (this.type === types$1._in) {
  19425. if (awaitAt > -1) { this.unexpected(awaitAt); }
  19426. } else { node.await = awaitAt > -1; }
  19427. }
  19428. return this.parseForIn(node, init$1)
  19429. }
  19430. if (awaitAt > -1) { this.unexpected(awaitAt); }
  19431. return this.parseFor(node, init$1)
  19432. }
  19433. var startsWithLet = this.isContextual("let"), isForOf = false;
  19434. var refDestructuringErrors = new DestructuringErrors;
  19435. var init = this.parseExpression(awaitAt > -1 ? "await" : true, refDestructuringErrors);
  19436. if (this.type === types$1._in || (isForOf = this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
  19437. if (this.options.ecmaVersion >= 9) {
  19438. if (this.type === types$1._in) {
  19439. if (awaitAt > -1) { this.unexpected(awaitAt); }
  19440. } else { node.await = awaitAt > -1; }
  19441. }
  19442. if (startsWithLet && isForOf) { this.raise(init.start, "The left-hand side of a for-of loop may not start with 'let'."); }
  19443. this.toAssignable(init, false, refDestructuringErrors);
  19444. this.checkLValPattern(init);
  19445. return this.parseForIn(node, init)
  19446. } else {
  19447. this.checkExpressionErrors(refDestructuringErrors, true);
  19448. }
  19449. if (awaitAt > -1) { this.unexpected(awaitAt); }
  19450. return this.parseFor(node, init)
  19451. };
  19452. pp$8.parseFunctionStatement = function(node, isAsync, declarationPosition) {
  19453. this.next();
  19454. return this.parseFunction(node, FUNC_STATEMENT$1 | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync)
  19455. };
  19456. pp$8.parseIfStatement = function(node) {
  19457. this.next();
  19458. node.test = this.parseParenExpression();
  19459. // allow function declarations in branches, but only in non-strict mode
  19460. node.consequent = this.parseStatement("if");
  19461. node.alternate = this.eat(types$1._else) ? this.parseStatement("if") : null;
  19462. return this.finishNode(node, "IfStatement")
  19463. };
  19464. pp$8.parseReturnStatement = function(node) {
  19465. if (!this.inFunction && !this.options.allowReturnOutsideFunction)
  19466. { this.raise(this.start, "'return' outside of function"); }
  19467. this.next();
  19468. // In `return` (and `break`/`continue`), the keywords with
  19469. // optional arguments, we eagerly look for a semicolon or the
  19470. // possibility to insert one.
  19471. if (this.eat(types$1.semi) || this.insertSemicolon()) { node.argument = null; }
  19472. else { node.argument = this.parseExpression(); this.semicolon(); }
  19473. return this.finishNode(node, "ReturnStatement")
  19474. };
  19475. pp$8.parseSwitchStatement = function(node) {
  19476. this.next();
  19477. node.discriminant = this.parseParenExpression();
  19478. node.cases = [];
  19479. this.expect(types$1.braceL);
  19480. this.labels.push(switchLabel);
  19481. this.enterScope(0);
  19482. // Statements under must be grouped (by label) in SwitchCase
  19483. // nodes. `cur` is used to keep the node that we are currently
  19484. // adding statements to.
  19485. var cur;
  19486. for (var sawDefault = false; this.type !== types$1.braceR;) {
  19487. if (this.type === types$1._case || this.type === types$1._default) {
  19488. var isCase = this.type === types$1._case;
  19489. if (cur) { this.finishNode(cur, "SwitchCase"); }
  19490. node.cases.push(cur = this.startNode());
  19491. cur.consequent = [];
  19492. this.next();
  19493. if (isCase) {
  19494. cur.test = this.parseExpression();
  19495. } else {
  19496. if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); }
  19497. sawDefault = true;
  19498. cur.test = null;
  19499. }
  19500. this.expect(types$1.colon);
  19501. } else {
  19502. if (!cur) { this.unexpected(); }
  19503. cur.consequent.push(this.parseStatement(null));
  19504. }
  19505. }
  19506. this.exitScope();
  19507. if (cur) { this.finishNode(cur, "SwitchCase"); }
  19508. this.next(); // Closing brace
  19509. this.labels.pop();
  19510. return this.finishNode(node, "SwitchStatement")
  19511. };
  19512. pp$8.parseThrowStatement = function(node) {
  19513. this.next();
  19514. if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start)))
  19515. { this.raise(this.lastTokEnd, "Illegal newline after throw"); }
  19516. node.argument = this.parseExpression();
  19517. this.semicolon();
  19518. return this.finishNode(node, "ThrowStatement")
  19519. };
  19520. // Reused empty array added for node fields that are always empty.
  19521. var empty$1 = [];
  19522. pp$8.parseCatchClauseParam = function() {
  19523. var param = this.parseBindingAtom();
  19524. var simple = param.type === "Identifier";
  19525. this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0);
  19526. this.checkLValPattern(param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL);
  19527. this.expect(types$1.parenR);
  19528. return param
  19529. };
  19530. pp$8.parseTryStatement = function(node) {
  19531. this.next();
  19532. node.block = this.parseBlock();
  19533. node.handler = null;
  19534. if (this.type === types$1._catch) {
  19535. var clause = this.startNode();
  19536. this.next();
  19537. if (this.eat(types$1.parenL)) {
  19538. clause.param = this.parseCatchClauseParam();
  19539. } else {
  19540. if (this.options.ecmaVersion < 10) { this.unexpected(); }
  19541. clause.param = null;
  19542. this.enterScope(0);
  19543. }
  19544. clause.body = this.parseBlock(false);
  19545. this.exitScope();
  19546. node.handler = this.finishNode(clause, "CatchClause");
  19547. }
  19548. node.finalizer = this.eat(types$1._finally) ? this.parseBlock() : null;
  19549. if (!node.handler && !node.finalizer)
  19550. { this.raise(node.start, "Missing catch or finally clause"); }
  19551. return this.finishNode(node, "TryStatement")
  19552. };
  19553. pp$8.parseVarStatement = function(node, kind, allowMissingInitializer) {
  19554. this.next();
  19555. this.parseVar(node, false, kind, allowMissingInitializer);
  19556. this.semicolon();
  19557. return this.finishNode(node, "VariableDeclaration")
  19558. };
  19559. pp$8.parseWhileStatement = function(node) {
  19560. this.next();
  19561. node.test = this.parseParenExpression();
  19562. this.labels.push(loopLabel);
  19563. node.body = this.parseStatement("while");
  19564. this.labels.pop();
  19565. return this.finishNode(node, "WhileStatement")
  19566. };
  19567. pp$8.parseWithStatement = function(node) {
  19568. if (this.strict) { this.raise(this.start, "'with' in strict mode"); }
  19569. this.next();
  19570. node.object = this.parseParenExpression();
  19571. node.body = this.parseStatement("with");
  19572. return this.finishNode(node, "WithStatement")
  19573. };
  19574. pp$8.parseEmptyStatement = function(node) {
  19575. this.next();
  19576. return this.finishNode(node, "EmptyStatement")
  19577. };
  19578. pp$8.parseLabeledStatement = function(node, maybeName, expr, context) {
  19579. for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1)
  19580. {
  19581. var label = list[i$1];
  19582. if (label.name === maybeName)
  19583. { this.raise(expr.start, "Label '" + maybeName + "' is already declared");
  19584. } }
  19585. var kind = this.type.isLoop ? "loop" : this.type === types$1._switch ? "switch" : null;
  19586. for (var i = this.labels.length - 1; i >= 0; i--) {
  19587. var label$1 = this.labels[i];
  19588. if (label$1.statementStart === node.start) {
  19589. // Update information about previous labels on this node
  19590. label$1.statementStart = this.start;
  19591. label$1.kind = kind;
  19592. } else { break }
  19593. }
  19594. this.labels.push({name: maybeName, kind: kind, statementStart: this.start});
  19595. node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
  19596. this.labels.pop();
  19597. node.label = expr;
  19598. return this.finishNode(node, "LabeledStatement")
  19599. };
  19600. pp$8.parseExpressionStatement = function(node, expr) {
  19601. node.expression = expr;
  19602. this.semicolon();
  19603. return this.finishNode(node, "ExpressionStatement")
  19604. };
  19605. // Parse a semicolon-enclosed block of statements, handling `"use
  19606. // strict"` declarations when `allowStrict` is true (used for
  19607. // function bodies).
  19608. pp$8.parseBlock = function(createNewLexicalScope, node, exitStrict) {
  19609. if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true;
  19610. if ( node === void 0 ) node = this.startNode();
  19611. node.body = [];
  19612. this.expect(types$1.braceL);
  19613. if (createNewLexicalScope) { this.enterScope(0); }
  19614. while (this.type !== types$1.braceR) {
  19615. var stmt = this.parseStatement(null);
  19616. node.body.push(stmt);
  19617. }
  19618. if (exitStrict) { this.strict = false; }
  19619. this.next();
  19620. if (createNewLexicalScope) { this.exitScope(); }
  19621. return this.finishNode(node, "BlockStatement")
  19622. };
  19623. // Parse a regular `for` loop. The disambiguation code in
  19624. // `parseStatement` will already have parsed the init statement or
  19625. // expression.
  19626. pp$8.parseFor = function(node, init) {
  19627. node.init = init;
  19628. this.expect(types$1.semi);
  19629. node.test = this.type === types$1.semi ? null : this.parseExpression();
  19630. this.expect(types$1.semi);
  19631. node.update = this.type === types$1.parenR ? null : this.parseExpression();
  19632. this.expect(types$1.parenR);
  19633. node.body = this.parseStatement("for");
  19634. this.exitScope();
  19635. this.labels.pop();
  19636. return this.finishNode(node, "ForStatement")
  19637. };
  19638. // Parse a `for`/`in` and `for`/`of` loop, which are almost
  19639. // same from parser's perspective.
  19640. pp$8.parseForIn = function(node, init) {
  19641. var isForIn = this.type === types$1._in;
  19642. this.next();
  19643. if (
  19644. init.type === "VariableDeclaration" &&
  19645. init.declarations[0].init != null &&
  19646. (
  19647. !isForIn ||
  19648. this.options.ecmaVersion < 8 ||
  19649. this.strict ||
  19650. init.kind !== "var" ||
  19651. init.declarations[0].id.type !== "Identifier"
  19652. )
  19653. ) {
  19654. this.raise(
  19655. init.start,
  19656. ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer")
  19657. );
  19658. }
  19659. node.left = init;
  19660. node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
  19661. this.expect(types$1.parenR);
  19662. node.body = this.parseStatement("for");
  19663. this.exitScope();
  19664. this.labels.pop();
  19665. return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement")
  19666. };
  19667. // Parse a list of variable declarations.
  19668. pp$8.parseVar = function(node, isFor, kind, allowMissingInitializer) {
  19669. node.declarations = [];
  19670. node.kind = kind;
  19671. for (;;) {
  19672. var decl = this.startNode();
  19673. this.parseVarId(decl, kind);
  19674. if (this.eat(types$1.eq)) {
  19675. decl.init = this.parseMaybeAssign(isFor);
  19676. } else if (!allowMissingInitializer && kind === "const" && !(this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) {
  19677. this.unexpected();
  19678. } else if (!allowMissingInitializer && decl.id.type !== "Identifier" && !(isFor && (this.type === types$1._in || this.isContextual("of")))) {
  19679. this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
  19680. } else {
  19681. decl.init = null;
  19682. }
  19683. node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
  19684. if (!this.eat(types$1.comma)) { break }
  19685. }
  19686. return node
  19687. };
  19688. pp$8.parseVarId = function(decl, kind) {
  19689. decl.id = this.parseBindingAtom();
  19690. this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false);
  19691. };
  19692. var FUNC_STATEMENT$1 = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID$1 = 4;
  19693. // Parse a function declaration or literal (depending on the
  19694. // `statement & FUNC_STATEMENT`).
  19695. // Remove `allowExpressionBody` for 7.0.0, as it is only called with false
  19696. pp$8.parseFunction = function(node, statement, allowExpressionBody, isAsync, forInit) {
  19697. this.initFunction(node);
  19698. if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) {
  19699. if (this.type === types$1.star && (statement & FUNC_HANGING_STATEMENT))
  19700. { this.unexpected(); }
  19701. node.generator = this.eat(types$1.star);
  19702. }
  19703. if (this.options.ecmaVersion >= 8)
  19704. { node.async = !!isAsync; }
  19705. if (statement & FUNC_STATEMENT$1) {
  19706. node.id = (statement & FUNC_NULLABLE_ID$1) && this.type !== types$1.name ? null : this.parseIdent();
  19707. if (node.id && !(statement & FUNC_HANGING_STATEMENT))
  19708. // If it is a regular function declaration in sloppy mode, then it is
  19709. // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding
  19710. // mode depends on properties of the current scope (see
  19711. // treatFunctionsAsVar).
  19712. { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); }
  19713. }
  19714. var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  19715. this.yieldPos = 0;
  19716. this.awaitPos = 0;
  19717. this.awaitIdentPos = 0;
  19718. this.enterScope(functionFlags(node.async, node.generator));
  19719. if (!(statement & FUNC_STATEMENT$1))
  19720. { node.id = this.type === types$1.name ? this.parseIdent() : null; }
  19721. this.parseFunctionParams(node);
  19722. this.parseFunctionBody(node, allowExpressionBody, false, forInit);
  19723. this.yieldPos = oldYieldPos;
  19724. this.awaitPos = oldAwaitPos;
  19725. this.awaitIdentPos = oldAwaitIdentPos;
  19726. return this.finishNode(node, (statement & FUNC_STATEMENT$1) ? "FunctionDeclaration" : "FunctionExpression")
  19727. };
  19728. pp$8.parseFunctionParams = function(node) {
  19729. this.expect(types$1.parenL);
  19730. node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8);
  19731. this.checkYieldAwaitInDefaultParams();
  19732. };
  19733. // Parse a class declaration or literal (depending on the
  19734. // `isStatement` parameter).
  19735. pp$8.parseClass = function(node, isStatement) {
  19736. this.next();
  19737. // ecma-262 14.6 Class Definitions
  19738. // A class definition is always strict mode code.
  19739. var oldStrict = this.strict;
  19740. this.strict = true;
  19741. this.parseClassId(node, isStatement);
  19742. this.parseClassSuper(node);
  19743. var privateNameMap = this.enterClassBody();
  19744. var classBody = this.startNode();
  19745. var hadConstructor = false;
  19746. classBody.body = [];
  19747. this.expect(types$1.braceL);
  19748. while (this.type !== types$1.braceR) {
  19749. var element = this.parseClassElement(node.superClass !== null);
  19750. if (element) {
  19751. classBody.body.push(element);
  19752. if (element.type === "MethodDefinition" && element.kind === "constructor") {
  19753. if (hadConstructor) { this.raiseRecoverable(element.start, "Duplicate constructor in the same class"); }
  19754. hadConstructor = true;
  19755. } else if (element.key && element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) {
  19756. this.raiseRecoverable(element.key.start, ("Identifier '#" + (element.key.name) + "' has already been declared"));
  19757. }
  19758. }
  19759. }
  19760. this.strict = oldStrict;
  19761. this.next();
  19762. node.body = this.finishNode(classBody, "ClassBody");
  19763. this.exitClassBody();
  19764. return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression")
  19765. };
  19766. pp$8.parseClassElement = function(constructorAllowsSuper) {
  19767. if (this.eat(types$1.semi)) { return null }
  19768. var ecmaVersion = this.options.ecmaVersion;
  19769. var node = this.startNode();
  19770. var keyName = "";
  19771. var isGenerator = false;
  19772. var isAsync = false;
  19773. var kind = "method";
  19774. var isStatic = false;
  19775. if (this.eatContextual("static")) {
  19776. // Parse static init block
  19777. if (ecmaVersion >= 13 && this.eat(types$1.braceL)) {
  19778. this.parseClassStaticBlock(node);
  19779. return node
  19780. }
  19781. if (this.isClassElementNameStart() || this.type === types$1.star) {
  19782. isStatic = true;
  19783. } else {
  19784. keyName = "static";
  19785. }
  19786. }
  19787. node.static = isStatic;
  19788. if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) {
  19789. if ((this.isClassElementNameStart() || this.type === types$1.star) && !this.canInsertSemicolon()) {
  19790. isAsync = true;
  19791. } else {
  19792. keyName = "async";
  19793. }
  19794. }
  19795. if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(types$1.star)) {
  19796. isGenerator = true;
  19797. }
  19798. if (!keyName && !isAsync && !isGenerator) {
  19799. var lastValue = this.value;
  19800. if (this.eatContextual("get") || this.eatContextual("set")) {
  19801. if (this.isClassElementNameStart()) {
  19802. kind = lastValue;
  19803. } else {
  19804. keyName = lastValue;
  19805. }
  19806. }
  19807. }
  19808. // Parse element name
  19809. if (keyName) {
  19810. // 'async', 'get', 'set', or 'static' were not a keyword contextually.
  19811. // The last token is any of those. Make it the element name.
  19812. node.computed = false;
  19813. node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc);
  19814. node.key.name = keyName;
  19815. this.finishNode(node.key, "Identifier");
  19816. } else {
  19817. this.parseClassElementName(node);
  19818. }
  19819. // Parse element value
  19820. if (ecmaVersion < 13 || this.type === types$1.parenL || kind !== "method" || isGenerator || isAsync) {
  19821. var isConstructor = !node.static && checkKeyName(node, "constructor");
  19822. var allowsDirectSuper = isConstructor && constructorAllowsSuper;
  19823. // Couldn't move this check into the 'parseClassMethod' method for backward compatibility.
  19824. if (isConstructor && kind !== "method") { this.raise(node.key.start, "Constructor can't have get/set modifier"); }
  19825. node.kind = isConstructor ? "constructor" : kind;
  19826. this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper);
  19827. } else {
  19828. this.parseClassField(node);
  19829. }
  19830. return node
  19831. };
  19832. pp$8.isClassElementNameStart = function() {
  19833. return (
  19834. this.type === types$1.name ||
  19835. this.type === types$1.privateId ||
  19836. this.type === types$1.num ||
  19837. this.type === types$1.string ||
  19838. this.type === types$1.bracketL ||
  19839. this.type.keyword
  19840. )
  19841. };
  19842. pp$8.parseClassElementName = function(element) {
  19843. if (this.type === types$1.privateId) {
  19844. if (this.value === "constructor") {
  19845. this.raise(this.start, "Classes can't have an element named '#constructor'");
  19846. }
  19847. element.computed = false;
  19848. element.key = this.parsePrivateIdent();
  19849. } else {
  19850. this.parsePropertyName(element);
  19851. }
  19852. };
  19853. pp$8.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) {
  19854. // Check key and flags
  19855. var key = method.key;
  19856. if (method.kind === "constructor") {
  19857. if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); }
  19858. if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); }
  19859. } else if (method.static && checkKeyName(method, "prototype")) {
  19860. this.raise(key.start, "Classes may not have a static property named prototype");
  19861. }
  19862. // Parse value
  19863. var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper);
  19864. // Check value
  19865. if (method.kind === "get" && value.params.length !== 0)
  19866. { this.raiseRecoverable(value.start, "getter should have no params"); }
  19867. if (method.kind === "set" && value.params.length !== 1)
  19868. { this.raiseRecoverable(value.start, "setter should have exactly one param"); }
  19869. if (method.kind === "set" && value.params[0].type === "RestElement")
  19870. { this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params"); }
  19871. return this.finishNode(method, "MethodDefinition")
  19872. };
  19873. pp$8.parseClassField = function(field) {
  19874. if (checkKeyName(field, "constructor")) {
  19875. this.raise(field.key.start, "Classes can't have a field named 'constructor'");
  19876. } else if (field.static && checkKeyName(field, "prototype")) {
  19877. this.raise(field.key.start, "Classes can't have a static field named 'prototype'");
  19878. }
  19879. if (this.eat(types$1.eq)) {
  19880. // To raise SyntaxError if 'arguments' exists in the initializer.
  19881. var scope = this.currentThisScope();
  19882. var inClassFieldInit = scope.inClassFieldInit;
  19883. scope.inClassFieldInit = true;
  19884. field.value = this.parseMaybeAssign();
  19885. scope.inClassFieldInit = inClassFieldInit;
  19886. } else {
  19887. field.value = null;
  19888. }
  19889. this.semicolon();
  19890. return this.finishNode(field, "PropertyDefinition")
  19891. };
  19892. pp$8.parseClassStaticBlock = function(node) {
  19893. node.body = [];
  19894. var oldLabels = this.labels;
  19895. this.labels = [];
  19896. this.enterScope(SCOPE_CLASS_STATIC_BLOCK | SCOPE_SUPER);
  19897. while (this.type !== types$1.braceR) {
  19898. var stmt = this.parseStatement(null);
  19899. node.body.push(stmt);
  19900. }
  19901. this.next();
  19902. this.exitScope();
  19903. this.labels = oldLabels;
  19904. return this.finishNode(node, "StaticBlock")
  19905. };
  19906. pp$8.parseClassId = function(node, isStatement) {
  19907. if (this.type === types$1.name) {
  19908. node.id = this.parseIdent();
  19909. if (isStatement)
  19910. { this.checkLValSimple(node.id, BIND_LEXICAL, false); }
  19911. } else {
  19912. if (isStatement === true)
  19913. { this.unexpected(); }
  19914. node.id = null;
  19915. }
  19916. };
  19917. pp$8.parseClassSuper = function(node) {
  19918. node.superClass = this.eat(types$1._extends) ? this.parseExprSubscripts(null, false) : null;
  19919. };
  19920. pp$8.enterClassBody = function() {
  19921. var element = {declared: Object.create(null), used: []};
  19922. this.privateNameStack.push(element);
  19923. return element.declared
  19924. };
  19925. pp$8.exitClassBody = function() {
  19926. var ref = this.privateNameStack.pop();
  19927. var declared = ref.declared;
  19928. var used = ref.used;
  19929. if (!this.options.checkPrivateFields) { return }
  19930. var len = this.privateNameStack.length;
  19931. var parent = len === 0 ? null : this.privateNameStack[len - 1];
  19932. for (var i = 0; i < used.length; ++i) {
  19933. var id = used[i];
  19934. if (!hasOwn(declared, id.name)) {
  19935. if (parent) {
  19936. parent.used.push(id);
  19937. } else {
  19938. this.raiseRecoverable(id.start, ("Private field '#" + (id.name) + "' must be declared in an enclosing class"));
  19939. }
  19940. }
  19941. }
  19942. };
  19943. function isPrivateNameConflicted(privateNameMap, element) {
  19944. var name = element.key.name;
  19945. var curr = privateNameMap[name];
  19946. var next = "true";
  19947. if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) {
  19948. next = (element.static ? "s" : "i") + element.kind;
  19949. }
  19950. // `class { get #a(){}; static set #a(_){} }` is also conflict.
  19951. if (
  19952. curr === "iget" && next === "iset" ||
  19953. curr === "iset" && next === "iget" ||
  19954. curr === "sget" && next === "sset" ||
  19955. curr === "sset" && next === "sget"
  19956. ) {
  19957. privateNameMap[name] = "true";
  19958. return false
  19959. } else if (!curr) {
  19960. privateNameMap[name] = next;
  19961. return false
  19962. } else {
  19963. return true
  19964. }
  19965. }
  19966. function checkKeyName(node, name) {
  19967. var computed = node.computed;
  19968. var key = node.key;
  19969. return !computed && (
  19970. key.type === "Identifier" && key.name === name ||
  19971. key.type === "Literal" && key.value === name
  19972. )
  19973. }
  19974. // Parses module export declaration.
  19975. pp$8.parseExportAllDeclaration = function(node, exports) {
  19976. if (this.options.ecmaVersion >= 11) {
  19977. if (this.eatContextual("as")) {
  19978. node.exported = this.parseModuleExportName();
  19979. this.checkExport(exports, node.exported, this.lastTokStart);
  19980. } else {
  19981. node.exported = null;
  19982. }
  19983. }
  19984. this.expectContextual("from");
  19985. if (this.type !== types$1.string) { this.unexpected(); }
  19986. node.source = this.parseExprAtom();
  19987. this.semicolon();
  19988. return this.finishNode(node, "ExportAllDeclaration")
  19989. };
  19990. pp$8.parseExport = function(node, exports) {
  19991. this.next();
  19992. // export * from '...'
  19993. if (this.eat(types$1.star)) {
  19994. return this.parseExportAllDeclaration(node, exports)
  19995. }
  19996. if (this.eat(types$1._default)) { // export default ...
  19997. this.checkExport(exports, "default", this.lastTokStart);
  19998. node.declaration = this.parseExportDefaultDeclaration();
  19999. return this.finishNode(node, "ExportDefaultDeclaration")
  20000. }
  20001. // export var|const|let|function|class ...
  20002. if (this.shouldParseExportStatement()) {
  20003. node.declaration = this.parseExportDeclaration(node);
  20004. if (node.declaration.type === "VariableDeclaration")
  20005. { this.checkVariableExport(exports, node.declaration.declarations); }
  20006. else
  20007. { this.checkExport(exports, node.declaration.id, node.declaration.id.start); }
  20008. node.specifiers = [];
  20009. node.source = null;
  20010. } else { // export { x, y as z } [from '...']
  20011. node.declaration = null;
  20012. node.specifiers = this.parseExportSpecifiers(exports);
  20013. if (this.eatContextual("from")) {
  20014. if (this.type !== types$1.string) { this.unexpected(); }
  20015. node.source = this.parseExprAtom();
  20016. } else {
  20017. for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
  20018. // check for keywords used as local names
  20019. var spec = list[i];
  20020. this.checkUnreserved(spec.local);
  20021. // check if export is defined
  20022. this.checkLocalExport(spec.local);
  20023. if (spec.local.type === "Literal") {
  20024. this.raise(spec.local.start, "A string literal cannot be used as an exported binding without `from`.");
  20025. }
  20026. }
  20027. node.source = null;
  20028. }
  20029. this.semicolon();
  20030. }
  20031. return this.finishNode(node, "ExportNamedDeclaration")
  20032. };
  20033. pp$8.parseExportDeclaration = function(node) {
  20034. return this.parseStatement(null)
  20035. };
  20036. pp$8.parseExportDefaultDeclaration = function() {
  20037. var isAsync;
  20038. if (this.type === types$1._function || (isAsync = this.isAsyncFunction())) {
  20039. var fNode = this.startNode();
  20040. this.next();
  20041. if (isAsync) { this.next(); }
  20042. return this.parseFunction(fNode, FUNC_STATEMENT$1 | FUNC_NULLABLE_ID$1, false, isAsync)
  20043. } else if (this.type === types$1._class) {
  20044. var cNode = this.startNode();
  20045. return this.parseClass(cNode, "nullableID")
  20046. } else {
  20047. var declaration = this.parseMaybeAssign();
  20048. this.semicolon();
  20049. return declaration
  20050. }
  20051. };
  20052. pp$8.checkExport = function(exports, name, pos) {
  20053. if (!exports) { return }
  20054. if (typeof name !== "string")
  20055. { name = name.type === "Identifier" ? name.name : name.value; }
  20056. if (hasOwn(exports, name))
  20057. { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); }
  20058. exports[name] = true;
  20059. };
  20060. pp$8.checkPatternExport = function(exports, pat) {
  20061. var type = pat.type;
  20062. if (type === "Identifier")
  20063. { this.checkExport(exports, pat, pat.start); }
  20064. else if (type === "ObjectPattern")
  20065. { for (var i = 0, list = pat.properties; i < list.length; i += 1)
  20066. {
  20067. var prop = list[i];
  20068. this.checkPatternExport(exports, prop);
  20069. } }
  20070. else if (type === "ArrayPattern")
  20071. { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) {
  20072. var elt = list$1[i$1];
  20073. if (elt) { this.checkPatternExport(exports, elt); }
  20074. } }
  20075. else if (type === "Property")
  20076. { this.checkPatternExport(exports, pat.value); }
  20077. else if (type === "AssignmentPattern")
  20078. { this.checkPatternExport(exports, pat.left); }
  20079. else if (type === "RestElement")
  20080. { this.checkPatternExport(exports, pat.argument); }
  20081. else if (type === "ParenthesizedExpression")
  20082. { this.checkPatternExport(exports, pat.expression); }
  20083. };
  20084. pp$8.checkVariableExport = function(exports, decls) {
  20085. if (!exports) { return }
  20086. for (var i = 0, list = decls; i < list.length; i += 1)
  20087. {
  20088. var decl = list[i];
  20089. this.checkPatternExport(exports, decl.id);
  20090. }
  20091. };
  20092. pp$8.shouldParseExportStatement = function() {
  20093. return this.type.keyword === "var" ||
  20094. this.type.keyword === "const" ||
  20095. this.type.keyword === "class" ||
  20096. this.type.keyword === "function" ||
  20097. this.isLet() ||
  20098. this.isAsyncFunction()
  20099. };
  20100. // Parses a comma-separated list of module exports.
  20101. pp$8.parseExportSpecifier = function(exports) {
  20102. var node = this.startNode();
  20103. node.local = this.parseModuleExportName();
  20104. node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local;
  20105. this.checkExport(
  20106. exports,
  20107. node.exported,
  20108. node.exported.start
  20109. );
  20110. return this.finishNode(node, "ExportSpecifier")
  20111. };
  20112. pp$8.parseExportSpecifiers = function(exports) {
  20113. var nodes = [], first = true;
  20114. // export { x, y as z } [from '...']
  20115. this.expect(types$1.braceL);
  20116. while (!this.eat(types$1.braceR)) {
  20117. if (!first) {
  20118. this.expect(types$1.comma);
  20119. if (this.afterTrailingComma(types$1.braceR)) { break }
  20120. } else { first = false; }
  20121. nodes.push(this.parseExportSpecifier(exports));
  20122. }
  20123. return nodes
  20124. };
  20125. // Parses import declaration.
  20126. pp$8.parseImport = function(node) {
  20127. this.next();
  20128. // import '...'
  20129. if (this.type === types$1.string) {
  20130. node.specifiers = empty$1;
  20131. node.source = this.parseExprAtom();
  20132. } else {
  20133. node.specifiers = this.parseImportSpecifiers();
  20134. this.expectContextual("from");
  20135. node.source = this.type === types$1.string ? this.parseExprAtom() : this.unexpected();
  20136. }
  20137. this.semicolon();
  20138. return this.finishNode(node, "ImportDeclaration")
  20139. };
  20140. // Parses a comma-separated list of module imports.
  20141. pp$8.parseImportSpecifier = function() {
  20142. var node = this.startNode();
  20143. node.imported = this.parseModuleExportName();
  20144. if (this.eatContextual("as")) {
  20145. node.local = this.parseIdent();
  20146. } else {
  20147. this.checkUnreserved(node.imported);
  20148. node.local = node.imported;
  20149. }
  20150. this.checkLValSimple(node.local, BIND_LEXICAL);
  20151. return this.finishNode(node, "ImportSpecifier")
  20152. };
  20153. pp$8.parseImportDefaultSpecifier = function() {
  20154. // import defaultObj, { x, y as z } from '...'
  20155. var node = this.startNode();
  20156. node.local = this.parseIdent();
  20157. this.checkLValSimple(node.local, BIND_LEXICAL);
  20158. return this.finishNode(node, "ImportDefaultSpecifier")
  20159. };
  20160. pp$8.parseImportNamespaceSpecifier = function() {
  20161. var node = this.startNode();
  20162. this.next();
  20163. this.expectContextual("as");
  20164. node.local = this.parseIdent();
  20165. this.checkLValSimple(node.local, BIND_LEXICAL);
  20166. return this.finishNode(node, "ImportNamespaceSpecifier")
  20167. };
  20168. pp$8.parseImportSpecifiers = function() {
  20169. var nodes = [], first = true;
  20170. if (this.type === types$1.name) {
  20171. nodes.push(this.parseImportDefaultSpecifier());
  20172. if (!this.eat(types$1.comma)) { return nodes }
  20173. }
  20174. if (this.type === types$1.star) {
  20175. nodes.push(this.parseImportNamespaceSpecifier());
  20176. return nodes
  20177. }
  20178. this.expect(types$1.braceL);
  20179. while (!this.eat(types$1.braceR)) {
  20180. if (!first) {
  20181. this.expect(types$1.comma);
  20182. if (this.afterTrailingComma(types$1.braceR)) { break }
  20183. } else { first = false; }
  20184. nodes.push(this.parseImportSpecifier());
  20185. }
  20186. return nodes
  20187. };
  20188. pp$8.parseModuleExportName = function() {
  20189. if (this.options.ecmaVersion >= 13 && this.type === types$1.string) {
  20190. var stringLiteral = this.parseLiteral(this.value);
  20191. if (loneSurrogate.test(stringLiteral.value)) {
  20192. this.raise(stringLiteral.start, "An export name cannot include a lone surrogate.");
  20193. }
  20194. return stringLiteral
  20195. }
  20196. return this.parseIdent(true)
  20197. };
  20198. // Set `ExpressionStatement#directive` property for directive prologues.
  20199. pp$8.adaptDirectivePrologue = function(statements) {
  20200. for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) {
  20201. statements[i].directive = statements[i].expression.raw.slice(1, -1);
  20202. }
  20203. };
  20204. pp$8.isDirectiveCandidate = function(statement) {
  20205. return (
  20206. this.options.ecmaVersion >= 5 &&
  20207. statement.type === "ExpressionStatement" &&
  20208. statement.expression.type === "Literal" &&
  20209. typeof statement.expression.value === "string" &&
  20210. // Reject parenthesized strings.
  20211. (this.input[statement.start] === "\"" || this.input[statement.start] === "'")
  20212. )
  20213. };
  20214. var pp$7 = Parser.prototype;
  20215. // Convert existing expression atom to assignable pattern
  20216. // if possible.
  20217. pp$7.toAssignable = function(node, isBinding, refDestructuringErrors) {
  20218. if (this.options.ecmaVersion >= 6 && node) {
  20219. switch (node.type) {
  20220. case "Identifier":
  20221. if (this.inAsync && node.name === "await")
  20222. { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); }
  20223. break
  20224. case "ObjectPattern":
  20225. case "ArrayPattern":
  20226. case "AssignmentPattern":
  20227. case "RestElement":
  20228. break
  20229. case "ObjectExpression":
  20230. node.type = "ObjectPattern";
  20231. if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  20232. for (var i = 0, list = node.properties; i < list.length; i += 1) {
  20233. var prop = list[i];
  20234. this.toAssignable(prop, isBinding);
  20235. // Early error:
  20236. // AssignmentRestProperty[Yield, Await] :
  20237. // `...` DestructuringAssignmentTarget[Yield, Await]
  20238. //
  20239. // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|.
  20240. if (
  20241. prop.type === "RestElement" &&
  20242. (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")
  20243. ) {
  20244. this.raise(prop.argument.start, "Unexpected token");
  20245. }
  20246. }
  20247. break
  20248. case "Property":
  20249. // AssignmentProperty has type === "Property"
  20250. if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); }
  20251. this.toAssignable(node.value, isBinding);
  20252. break
  20253. case "ArrayExpression":
  20254. node.type = "ArrayPattern";
  20255. if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  20256. this.toAssignableList(node.elements, isBinding);
  20257. break
  20258. case "SpreadElement":
  20259. node.type = "RestElement";
  20260. this.toAssignable(node.argument, isBinding);
  20261. if (node.argument.type === "AssignmentPattern")
  20262. { this.raise(node.argument.start, "Rest elements cannot have a default value"); }
  20263. break
  20264. case "AssignmentExpression":
  20265. if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); }
  20266. node.type = "AssignmentPattern";
  20267. delete node.operator;
  20268. this.toAssignable(node.left, isBinding);
  20269. break
  20270. case "ParenthesizedExpression":
  20271. this.toAssignable(node.expression, isBinding, refDestructuringErrors);
  20272. break
  20273. case "ChainExpression":
  20274. this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side");
  20275. break
  20276. case "MemberExpression":
  20277. if (!isBinding) { break }
  20278. default:
  20279. this.raise(node.start, "Assigning to rvalue");
  20280. }
  20281. } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
  20282. return node
  20283. };
  20284. // Convert list of expression atoms to binding list.
  20285. pp$7.toAssignableList = function(exprList, isBinding) {
  20286. var end = exprList.length;
  20287. for (var i = 0; i < end; i++) {
  20288. var elt = exprList[i];
  20289. if (elt) { this.toAssignable(elt, isBinding); }
  20290. }
  20291. if (end) {
  20292. var last = exprList[end - 1];
  20293. if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier")
  20294. { this.unexpected(last.argument.start); }
  20295. }
  20296. return exprList
  20297. };
  20298. // Parses spread element.
  20299. pp$7.parseSpread = function(refDestructuringErrors) {
  20300. var node = this.startNode();
  20301. this.next();
  20302. node.argument = this.parseMaybeAssign(false, refDestructuringErrors);
  20303. return this.finishNode(node, "SpreadElement")
  20304. };
  20305. pp$7.parseRestBinding = function() {
  20306. var node = this.startNode();
  20307. this.next();
  20308. // RestElement inside of a function parameter must be an identifier
  20309. if (this.options.ecmaVersion === 6 && this.type !== types$1.name)
  20310. { this.unexpected(); }
  20311. node.argument = this.parseBindingAtom();
  20312. return this.finishNode(node, "RestElement")
  20313. };
  20314. // Parses lvalue (assignable) atom.
  20315. pp$7.parseBindingAtom = function() {
  20316. if (this.options.ecmaVersion >= 6) {
  20317. switch (this.type) {
  20318. case types$1.bracketL:
  20319. var node = this.startNode();
  20320. this.next();
  20321. node.elements = this.parseBindingList(types$1.bracketR, true, true);
  20322. return this.finishNode(node, "ArrayPattern")
  20323. case types$1.braceL:
  20324. return this.parseObj(true)
  20325. }
  20326. }
  20327. return this.parseIdent()
  20328. };
  20329. pp$7.parseBindingList = function(close, allowEmpty, allowTrailingComma, allowModifiers) {
  20330. var elts = [], first = true;
  20331. while (!this.eat(close)) {
  20332. if (first) { first = false; }
  20333. else { this.expect(types$1.comma); }
  20334. if (allowEmpty && this.type === types$1.comma) {
  20335. elts.push(null);
  20336. } else if (allowTrailingComma && this.afterTrailingComma(close)) {
  20337. break
  20338. } else if (this.type === types$1.ellipsis) {
  20339. var rest = this.parseRestBinding();
  20340. this.parseBindingListItem(rest);
  20341. elts.push(rest);
  20342. if (this.type === types$1.comma) { this.raiseRecoverable(this.start, "Comma is not permitted after the rest element"); }
  20343. this.expect(close);
  20344. break
  20345. } else {
  20346. elts.push(this.parseAssignableListItem(allowModifiers));
  20347. }
  20348. }
  20349. return elts
  20350. };
  20351. pp$7.parseAssignableListItem = function(allowModifiers) {
  20352. var elem = this.parseMaybeDefault(this.start, this.startLoc);
  20353. this.parseBindingListItem(elem);
  20354. return elem
  20355. };
  20356. pp$7.parseBindingListItem = function(param) {
  20357. return param
  20358. };
  20359. // Parses assignment pattern around given atom if possible.
  20360. pp$7.parseMaybeDefault = function(startPos, startLoc, left) {
  20361. left = left || this.parseBindingAtom();
  20362. if (this.options.ecmaVersion < 6 || !this.eat(types$1.eq)) { return left }
  20363. var node = this.startNodeAt(startPos, startLoc);
  20364. node.left = left;
  20365. node.right = this.parseMaybeAssign();
  20366. return this.finishNode(node, "AssignmentPattern")
  20367. };
  20368. // The following three functions all verify that a node is an lvalue —
  20369. // something that can be bound, or assigned to. In order to do so, they perform
  20370. // a variety of checks:
  20371. //
  20372. // - Check that none of the bound/assigned-to identifiers are reserved words.
  20373. // - Record name declarations for bindings in the appropriate scope.
  20374. // - Check duplicate argument names, if checkClashes is set.
  20375. //
  20376. // If a complex binding pattern is encountered (e.g., object and array
  20377. // destructuring), the entire pattern is recursively checked.
  20378. //
  20379. // There are three versions of checkLVal*() appropriate for different
  20380. // circumstances:
  20381. //
  20382. // - checkLValSimple() shall be used if the syntactic construct supports
  20383. // nothing other than identifiers and member expressions. Parenthesized
  20384. // expressions are also correctly handled. This is generally appropriate for
  20385. // constructs for which the spec says
  20386. //
  20387. // > It is a Syntax Error if AssignmentTargetType of [the production] is not
  20388. // > simple.
  20389. //
  20390. // It is also appropriate for checking if an identifier is valid and not
  20391. // defined elsewhere, like import declarations or function/class identifiers.
  20392. //
  20393. // Examples where this is used include:
  20394. // a += …;
  20395. // import a from '…';
  20396. // where a is the node to be checked.
  20397. //
  20398. // - checkLValPattern() shall be used if the syntactic construct supports
  20399. // anything checkLValSimple() supports, as well as object and array
  20400. // destructuring patterns. This is generally appropriate for constructs for
  20401. // which the spec says
  20402. //
  20403. // > It is a Syntax Error if [the production] is neither an ObjectLiteral nor
  20404. // > an ArrayLiteral and AssignmentTargetType of [the production] is not
  20405. // > simple.
  20406. //
  20407. // Examples where this is used include:
  20408. // (a = …);
  20409. // const a = …;
  20410. // try { … } catch (a) { … }
  20411. // where a is the node to be checked.
  20412. //
  20413. // - checkLValInnerPattern() shall be used if the syntactic construct supports
  20414. // anything checkLValPattern() supports, as well as default assignment
  20415. // patterns, rest elements, and other constructs that may appear within an
  20416. // object or array destructuring pattern.
  20417. //
  20418. // As a special case, function parameters also use checkLValInnerPattern(),
  20419. // as they also support defaults and rest constructs.
  20420. //
  20421. // These functions deliberately support both assignment and binding constructs,
  20422. // as the logic for both is exceedingly similar. If the node is the target of
  20423. // an assignment, then bindingType should be set to BIND_NONE. Otherwise, it
  20424. // should be set to the appropriate BIND_* constant, like BIND_VAR or
  20425. // BIND_LEXICAL.
  20426. //
  20427. // If the function is called with a non-BIND_NONE bindingType, then
  20428. // additionally a checkClashes object may be specified to allow checking for
  20429. // duplicate argument names. checkClashes is ignored if the provided construct
  20430. // is an assignment (i.e., bindingType is BIND_NONE).
  20431. pp$7.checkLValSimple = function(expr, bindingType, checkClashes) {
  20432. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  20433. var isBind = bindingType !== BIND_NONE;
  20434. switch (expr.type) {
  20435. case "Identifier":
  20436. if (this.strict && this.reservedWordsStrictBind.test(expr.name))
  20437. { this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); }
  20438. if (isBind) {
  20439. if (bindingType === BIND_LEXICAL && expr.name === "let")
  20440. { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); }
  20441. if (checkClashes) {
  20442. if (hasOwn(checkClashes, expr.name))
  20443. { this.raiseRecoverable(expr.start, "Argument name clash"); }
  20444. checkClashes[expr.name] = true;
  20445. }
  20446. if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); }
  20447. }
  20448. break
  20449. case "ChainExpression":
  20450. this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side");
  20451. break
  20452. case "MemberExpression":
  20453. if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); }
  20454. break
  20455. case "ParenthesizedExpression":
  20456. if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); }
  20457. return this.checkLValSimple(expr.expression, bindingType, checkClashes)
  20458. default:
  20459. this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue");
  20460. }
  20461. };
  20462. pp$7.checkLValPattern = function(expr, bindingType, checkClashes) {
  20463. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  20464. switch (expr.type) {
  20465. case "ObjectPattern":
  20466. for (var i = 0, list = expr.properties; i < list.length; i += 1) {
  20467. var prop = list[i];
  20468. this.checkLValInnerPattern(prop, bindingType, checkClashes);
  20469. }
  20470. break
  20471. case "ArrayPattern":
  20472. for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) {
  20473. var elem = list$1[i$1];
  20474. if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); }
  20475. }
  20476. break
  20477. default:
  20478. this.checkLValSimple(expr, bindingType, checkClashes);
  20479. }
  20480. };
  20481. pp$7.checkLValInnerPattern = function(expr, bindingType, checkClashes) {
  20482. if ( bindingType === void 0 ) bindingType = BIND_NONE;
  20483. switch (expr.type) {
  20484. case "Property":
  20485. // AssignmentProperty has type === "Property"
  20486. this.checkLValInnerPattern(expr.value, bindingType, checkClashes);
  20487. break
  20488. case "AssignmentPattern":
  20489. this.checkLValPattern(expr.left, bindingType, checkClashes);
  20490. break
  20491. case "RestElement":
  20492. this.checkLValPattern(expr.argument, bindingType, checkClashes);
  20493. break
  20494. default:
  20495. this.checkLValPattern(expr, bindingType, checkClashes);
  20496. }
  20497. };
  20498. // The algorithm used to determine whether a regexp can appear at a
  20499. // given point in the program is loosely based on sweet.js' approach.
  20500. // See https://github.com/mozilla/sweet.js/wiki/design
  20501. var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) {
  20502. this.token = token;
  20503. this.isExpr = !!isExpr;
  20504. this.preserveSpace = !!preserveSpace;
  20505. this.override = override;
  20506. this.generator = !!generator;
  20507. };
  20508. var types = {
  20509. b_stat: new TokContext("{", false),
  20510. b_expr: new TokContext("{", true),
  20511. b_tmpl: new TokContext("${", false),
  20512. p_stat: new TokContext("(", false),
  20513. p_expr: new TokContext("(", true),
  20514. q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }),
  20515. f_stat: new TokContext("function", false),
  20516. f_expr: new TokContext("function", true),
  20517. f_expr_gen: new TokContext("function", true, false, null, true),
  20518. f_gen: new TokContext("function", false, false, null, true)
  20519. };
  20520. var pp$6 = Parser.prototype;
  20521. pp$6.initialContext = function() {
  20522. return [types.b_stat]
  20523. };
  20524. pp$6.curContext = function() {
  20525. return this.context[this.context.length - 1]
  20526. };
  20527. pp$6.braceIsBlock = function(prevType) {
  20528. var parent = this.curContext();
  20529. if (parent === types.f_expr || parent === types.f_stat)
  20530. { return true }
  20531. if (prevType === types$1.colon && (parent === types.b_stat || parent === types.b_expr))
  20532. { return !parent.isExpr }
  20533. // The check for `tt.name && exprAllowed` detects whether we are
  20534. // after a `yield` or `of` construct. See the `updateContext` for
  20535. // `tt.name`.
  20536. if (prevType === types$1._return || prevType === types$1.name && this.exprAllowed)
  20537. { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }
  20538. if (prevType === types$1._else || prevType === types$1.semi || prevType === types$1.eof || prevType === types$1.parenR || prevType === types$1.arrow)
  20539. { return true }
  20540. if (prevType === types$1.braceL)
  20541. { return parent === types.b_stat }
  20542. if (prevType === types$1._var || prevType === types$1._const || prevType === types$1.name)
  20543. { return false }
  20544. return !this.exprAllowed
  20545. };
  20546. pp$6.inGeneratorContext = function() {
  20547. for (var i = this.context.length - 1; i >= 1; i--) {
  20548. var context = this.context[i];
  20549. if (context.token === "function")
  20550. { return context.generator }
  20551. }
  20552. return false
  20553. };
  20554. pp$6.updateContext = function(prevType) {
  20555. var update, type = this.type;
  20556. if (type.keyword && prevType === types$1.dot)
  20557. { this.exprAllowed = false; }
  20558. else if (update = type.updateContext)
  20559. { update.call(this, prevType); }
  20560. else
  20561. { this.exprAllowed = type.beforeExpr; }
  20562. };
  20563. // Used to handle egde cases when token context could not be inferred correctly during tokenization phase
  20564. pp$6.overrideContext = function(tokenCtx) {
  20565. if (this.curContext() !== tokenCtx) {
  20566. this.context[this.context.length - 1] = tokenCtx;
  20567. }
  20568. };
  20569. // Token-specific context update code
  20570. types$1.parenR.updateContext = types$1.braceR.updateContext = function() {
  20571. if (this.context.length === 1) {
  20572. this.exprAllowed = true;
  20573. return
  20574. }
  20575. var out = this.context.pop();
  20576. if (out === types.b_stat && this.curContext().token === "function") {
  20577. out = this.context.pop();
  20578. }
  20579. this.exprAllowed = !out.isExpr;
  20580. };
  20581. types$1.braceL.updateContext = function(prevType) {
  20582. this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr);
  20583. this.exprAllowed = true;
  20584. };
  20585. types$1.dollarBraceL.updateContext = function() {
  20586. this.context.push(types.b_tmpl);
  20587. this.exprAllowed = true;
  20588. };
  20589. types$1.parenL.updateContext = function(prevType) {
  20590. var statementParens = prevType === types$1._if || prevType === types$1._for || prevType === types$1._with || prevType === types$1._while;
  20591. this.context.push(statementParens ? types.p_stat : types.p_expr);
  20592. this.exprAllowed = true;
  20593. };
  20594. types$1.incDec.updateContext = function() {
  20595. // tokExprAllowed stays unchanged
  20596. };
  20597. types$1._function.updateContext = types$1._class.updateContext = function(prevType) {
  20598. if (prevType.beforeExpr && prevType !== types$1._else &&
  20599. !(prevType === types$1.semi && this.curContext() !== types.p_stat) &&
  20600. !(prevType === types$1._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) &&
  20601. !((prevType === types$1.colon || prevType === types$1.braceL) && this.curContext() === types.b_stat))
  20602. { this.context.push(types.f_expr); }
  20603. else
  20604. { this.context.push(types.f_stat); }
  20605. this.exprAllowed = false;
  20606. };
  20607. types$1.backQuote.updateContext = function() {
  20608. if (this.curContext() === types.q_tmpl)
  20609. { this.context.pop(); }
  20610. else
  20611. { this.context.push(types.q_tmpl); }
  20612. this.exprAllowed = false;
  20613. };
  20614. types$1.star.updateContext = function(prevType) {
  20615. if (prevType === types$1._function) {
  20616. var index = this.context.length - 1;
  20617. if (this.context[index] === types.f_expr)
  20618. { this.context[index] = types.f_expr_gen; }
  20619. else
  20620. { this.context[index] = types.f_gen; }
  20621. }
  20622. this.exprAllowed = true;
  20623. };
  20624. types$1.name.updateContext = function(prevType) {
  20625. var allowed = false;
  20626. if (this.options.ecmaVersion >= 6 && prevType !== types$1.dot) {
  20627. if (this.value === "of" && !this.exprAllowed ||
  20628. this.value === "yield" && this.inGeneratorContext())
  20629. { allowed = true; }
  20630. }
  20631. this.exprAllowed = allowed;
  20632. };
  20633. // A recursive descent parser operates by defining functions for all
  20634. // syntactic elements, and recursively calling those, each function
  20635. // advancing the input stream and returning an AST node. Precedence
  20636. // of constructs (for example, the fact that `!x[1]` means `!(x[1])`
  20637. // instead of `(!x)[1]` is handled by the fact that the parser
  20638. // function that parses unary prefix operators is called first, and
  20639. // in turn calls the function that parses `[]` subscripts — that
  20640. // way, it'll receive the node for `x[1]` already parsed, and wraps
  20641. // *that* in the unary operator node.
  20642. //
  20643. // Acorn uses an [operator precedence parser][opp] to handle binary
  20644. // operator precedence, because it is much more compact than using
  20645. // the technique outlined above, which uses different, nesting
  20646. // functions to specify precedence, for all of the ten binary
  20647. // precedence levels that JavaScript defines.
  20648. //
  20649. // [opp]: http://en.wikipedia.org/wiki/Operator-precedence_parser
  20650. var pp$5 = Parser.prototype;
  20651. // Check if property name clashes with already added.
  20652. // Object/class getters and setters are not allowed to clash —
  20653. // either with each other or with an init property — and in
  20654. // strict mode, init properties are also not allowed to be repeated.
  20655. pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) {
  20656. if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement")
  20657. { return }
  20658. if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand))
  20659. { return }
  20660. var key = prop.key;
  20661. var name;
  20662. switch (key.type) {
  20663. case "Identifier": name = key.name; break
  20664. case "Literal": name = String(key.value); break
  20665. default: return
  20666. }
  20667. var kind = prop.kind;
  20668. if (this.options.ecmaVersion >= 6) {
  20669. if (name === "__proto__" && kind === "init") {
  20670. if (propHash.proto) {
  20671. if (refDestructuringErrors) {
  20672. if (refDestructuringErrors.doubleProto < 0) {
  20673. refDestructuringErrors.doubleProto = key.start;
  20674. }
  20675. } else {
  20676. this.raiseRecoverable(key.start, "Redefinition of __proto__ property");
  20677. }
  20678. }
  20679. propHash.proto = true;
  20680. }
  20681. return
  20682. }
  20683. name = "$" + name;
  20684. var other = propHash[name];
  20685. if (other) {
  20686. var redefinition;
  20687. if (kind === "init") {
  20688. redefinition = this.strict && other.init || other.get || other.set;
  20689. } else {
  20690. redefinition = other.init || other[kind];
  20691. }
  20692. if (redefinition)
  20693. { this.raiseRecoverable(key.start, "Redefinition of property"); }
  20694. } else {
  20695. other = propHash[name] = {
  20696. init: false,
  20697. get: false,
  20698. set: false
  20699. };
  20700. }
  20701. other[kind] = true;
  20702. };
  20703. // ### Expression parsing
  20704. // These nest, from the most general expression type at the top to
  20705. // 'atomic', nondivisible expression types at the bottom. Most of
  20706. // the functions will simply let the function(s) below them parse,
  20707. // and, *if* the syntactic construct they handle is present, wrap
  20708. // the AST node that the inner parser gave them in another node.
  20709. // Parse a full expression. The optional arguments are used to
  20710. // forbid the `in` operator (in for loops initalization expressions)
  20711. // and provide reference for storing '=' operator inside shorthand
  20712. // property assignment in contexts where both object expression
  20713. // and object pattern might appear (so it's possible to raise
  20714. // delayed syntax error at correct position).
  20715. pp$5.parseExpression = function(forInit, refDestructuringErrors) {
  20716. var startPos = this.start, startLoc = this.startLoc;
  20717. var expr = this.parseMaybeAssign(forInit, refDestructuringErrors);
  20718. if (this.type === types$1.comma) {
  20719. var node = this.startNodeAt(startPos, startLoc);
  20720. node.expressions = [expr];
  20721. while (this.eat(types$1.comma)) { node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors)); }
  20722. return this.finishNode(node, "SequenceExpression")
  20723. }
  20724. return expr
  20725. };
  20726. // Parse an assignment expression. This includes applications of
  20727. // operators like `+=`.
  20728. pp$5.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) {
  20729. if (this.isContextual("yield")) {
  20730. if (this.inGenerator) { return this.parseYield(forInit) }
  20731. // The tokenizer will assume an expression is allowed after
  20732. // `yield`, but this isn't that kind of yield
  20733. else { this.exprAllowed = false; }
  20734. }
  20735. var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldDoubleProto = -1;
  20736. if (refDestructuringErrors) {
  20737. oldParenAssign = refDestructuringErrors.parenthesizedAssign;
  20738. oldTrailingComma = refDestructuringErrors.trailingComma;
  20739. oldDoubleProto = refDestructuringErrors.doubleProto;
  20740. refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;
  20741. } else {
  20742. refDestructuringErrors = new DestructuringErrors;
  20743. ownDestructuringErrors = true;
  20744. }
  20745. var startPos = this.start, startLoc = this.startLoc;
  20746. if (this.type === types$1.parenL || this.type === types$1.name) {
  20747. this.potentialArrowAt = this.start;
  20748. this.potentialArrowInForAwait = forInit === "await";
  20749. }
  20750. var left = this.parseMaybeConditional(forInit, refDestructuringErrors);
  20751. if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); }
  20752. if (this.type.isAssign) {
  20753. var node = this.startNodeAt(startPos, startLoc);
  20754. node.operator = this.value;
  20755. if (this.type === types$1.eq)
  20756. { left = this.toAssignable(left, false, refDestructuringErrors); }
  20757. if (!ownDestructuringErrors) {
  20758. refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1;
  20759. }
  20760. if (refDestructuringErrors.shorthandAssign >= left.start)
  20761. { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly
  20762. if (this.type === types$1.eq)
  20763. { this.checkLValPattern(left); }
  20764. else
  20765. { this.checkLValSimple(left); }
  20766. node.left = left;
  20767. this.next();
  20768. node.right = this.parseMaybeAssign(forInit);
  20769. if (oldDoubleProto > -1) { refDestructuringErrors.doubleProto = oldDoubleProto; }
  20770. return this.finishNode(node, "AssignmentExpression")
  20771. } else {
  20772. if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); }
  20773. }
  20774. if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; }
  20775. if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; }
  20776. return left
  20777. };
  20778. // Parse a ternary conditional (`?:`) operator.
  20779. pp$5.parseMaybeConditional = function(forInit, refDestructuringErrors) {
  20780. var startPos = this.start, startLoc = this.startLoc;
  20781. var expr = this.parseExprOps(forInit, refDestructuringErrors);
  20782. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  20783. if (this.eat(types$1.question)) {
  20784. var node = this.startNodeAt(startPos, startLoc);
  20785. node.test = expr;
  20786. node.consequent = this.parseMaybeAssign();
  20787. this.expect(types$1.colon);
  20788. node.alternate = this.parseMaybeAssign(forInit);
  20789. return this.finishNode(node, "ConditionalExpression")
  20790. }
  20791. return expr
  20792. };
  20793. // Start the precedence parser.
  20794. pp$5.parseExprOps = function(forInit, refDestructuringErrors) {
  20795. var startPos = this.start, startLoc = this.startLoc;
  20796. var expr = this.parseMaybeUnary(refDestructuringErrors, false, false, forInit);
  20797. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  20798. return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit)
  20799. };
  20800. // Parse binary operators with the operator precedence parsing
  20801. // algorithm. `left` is the left-hand side of the operator.
  20802. // `minPrec` provides context that allows the function to stop and
  20803. // defer further parser to one of its callers when it encounters an
  20804. // operator that has a lower precedence than the set it is parsing.
  20805. pp$5.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) {
  20806. var prec = this.type.binop;
  20807. if (prec != null && (!forInit || this.type !== types$1._in)) {
  20808. if (prec > minPrec) {
  20809. var logical = this.type === types$1.logicalOR || this.type === types$1.logicalAND;
  20810. var coalesce = this.type === types$1.coalesce;
  20811. if (coalesce) {
  20812. // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions.
  20813. // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error.
  20814. prec = types$1.logicalAND.binop;
  20815. }
  20816. var op = this.value;
  20817. this.next();
  20818. var startPos = this.start, startLoc = this.startLoc;
  20819. var right = this.parseExprOp(this.parseMaybeUnary(null, false, false, forInit), startPos, startLoc, prec, forInit);
  20820. var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce);
  20821. if ((logical && this.type === types$1.coalesce) || (coalesce && (this.type === types$1.logicalOR || this.type === types$1.logicalAND))) {
  20822. this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses");
  20823. }
  20824. return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit)
  20825. }
  20826. }
  20827. return left
  20828. };
  20829. pp$5.buildBinary = function(startPos, startLoc, left, right, op, logical) {
  20830. if (right.type === "PrivateIdentifier") { this.raise(right.start, "Private identifier can only be left side of binary expression"); }
  20831. var node = this.startNodeAt(startPos, startLoc);
  20832. node.left = left;
  20833. node.operator = op;
  20834. node.right = right;
  20835. return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression")
  20836. };
  20837. // Parse unary operators, both prefix and postfix.
  20838. pp$5.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec, forInit) {
  20839. var startPos = this.start, startLoc = this.startLoc, expr;
  20840. if (this.isContextual("await") && this.canAwait) {
  20841. expr = this.parseAwait(forInit);
  20842. sawUnary = true;
  20843. } else if (this.type.prefix) {
  20844. var node = this.startNode(), update = this.type === types$1.incDec;
  20845. node.operator = this.value;
  20846. node.prefix = true;
  20847. this.next();
  20848. node.argument = this.parseMaybeUnary(null, true, update, forInit);
  20849. this.checkExpressionErrors(refDestructuringErrors, true);
  20850. if (update) { this.checkLValSimple(node.argument); }
  20851. else if (this.strict && node.operator === "delete" &&
  20852. node.argument.type === "Identifier")
  20853. { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); }
  20854. else if (node.operator === "delete" && isPrivateFieldAccess(node.argument))
  20855. { this.raiseRecoverable(node.start, "Private fields can not be deleted"); }
  20856. else { sawUnary = true; }
  20857. expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
  20858. } else if (!sawUnary && this.type === types$1.privateId) {
  20859. if ((forInit || this.privateNameStack.length === 0) && this.options.checkPrivateFields) { this.unexpected(); }
  20860. expr = this.parsePrivateIdent();
  20861. // only could be private fields in 'in', such as #x in obj
  20862. if (this.type !== types$1._in) { this.unexpected(); }
  20863. } else {
  20864. expr = this.parseExprSubscripts(refDestructuringErrors, forInit);
  20865. if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
  20866. while (this.type.postfix && !this.canInsertSemicolon()) {
  20867. var node$1 = this.startNodeAt(startPos, startLoc);
  20868. node$1.operator = this.value;
  20869. node$1.prefix = false;
  20870. node$1.argument = expr;
  20871. this.checkLValSimple(expr);
  20872. this.next();
  20873. expr = this.finishNode(node$1, "UpdateExpression");
  20874. }
  20875. }
  20876. if (!incDec && this.eat(types$1.starstar)) {
  20877. if (sawUnary)
  20878. { this.unexpected(this.lastTokStart); }
  20879. else
  20880. { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false, false, forInit), "**", false) }
  20881. } else {
  20882. return expr
  20883. }
  20884. };
  20885. function isPrivateFieldAccess(node) {
  20886. return (
  20887. node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" ||
  20888. node.type === "ChainExpression" && isPrivateFieldAccess(node.expression)
  20889. )
  20890. }
  20891. // Parse call, dot, and `[]`-subscript expressions.
  20892. pp$5.parseExprSubscripts = function(refDestructuringErrors, forInit) {
  20893. var startPos = this.start, startLoc = this.startLoc;
  20894. var expr = this.parseExprAtom(refDestructuringErrors, forInit);
  20895. if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")")
  20896. { return expr }
  20897. var result = this.parseSubscripts(expr, startPos, startLoc, false, forInit);
  20898. if (refDestructuringErrors && result.type === "MemberExpression") {
  20899. if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; }
  20900. if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; }
  20901. if (refDestructuringErrors.trailingComma >= result.start) { refDestructuringErrors.trailingComma = -1; }
  20902. }
  20903. return result
  20904. };
  20905. pp$5.parseSubscripts = function(base, startPos, startLoc, noCalls, forInit) {
  20906. var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" &&
  20907. this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 &&
  20908. this.potentialArrowAt === base.start;
  20909. var optionalChained = false;
  20910. while (true) {
  20911. var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit);
  20912. if (element.optional) { optionalChained = true; }
  20913. if (element === base || element.type === "ArrowFunctionExpression") {
  20914. if (optionalChained) {
  20915. var chainNode = this.startNodeAt(startPos, startLoc);
  20916. chainNode.expression = element;
  20917. element = this.finishNode(chainNode, "ChainExpression");
  20918. }
  20919. return element
  20920. }
  20921. base = element;
  20922. }
  20923. };
  20924. pp$5.shouldParseAsyncArrow = function() {
  20925. return !this.canInsertSemicolon() && this.eat(types$1.arrow)
  20926. };
  20927. pp$5.parseSubscriptAsyncArrow = function(startPos, startLoc, exprList, forInit) {
  20928. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true, forInit)
  20929. };
  20930. pp$5.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) {
  20931. var optionalSupported = this.options.ecmaVersion >= 11;
  20932. var optional = optionalSupported && this.eat(types$1.questionDot);
  20933. if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); }
  20934. var computed = this.eat(types$1.bracketL);
  20935. if (computed || (optional && this.type !== types$1.parenL && this.type !== types$1.backQuote) || this.eat(types$1.dot)) {
  20936. var node = this.startNodeAt(startPos, startLoc);
  20937. node.object = base;
  20938. if (computed) {
  20939. node.property = this.parseExpression();
  20940. this.expect(types$1.bracketR);
  20941. } else if (this.type === types$1.privateId && base.type !== "Super") {
  20942. node.property = this.parsePrivateIdent();
  20943. } else {
  20944. node.property = this.parseIdent(this.options.allowReserved !== "never");
  20945. }
  20946. node.computed = !!computed;
  20947. if (optionalSupported) {
  20948. node.optional = optional;
  20949. }
  20950. base = this.finishNode(node, "MemberExpression");
  20951. } else if (!noCalls && this.eat(types$1.parenL)) {
  20952. var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  20953. this.yieldPos = 0;
  20954. this.awaitPos = 0;
  20955. this.awaitIdentPos = 0;
  20956. var exprList = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);
  20957. if (maybeAsyncArrow && !optional && this.shouldParseAsyncArrow()) {
  20958. this.checkPatternErrors(refDestructuringErrors, false);
  20959. this.checkYieldAwaitInDefaultParams();
  20960. if (this.awaitIdentPos > 0)
  20961. { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); }
  20962. this.yieldPos = oldYieldPos;
  20963. this.awaitPos = oldAwaitPos;
  20964. this.awaitIdentPos = oldAwaitIdentPos;
  20965. return this.parseSubscriptAsyncArrow(startPos, startLoc, exprList, forInit)
  20966. }
  20967. this.checkExpressionErrors(refDestructuringErrors, true);
  20968. this.yieldPos = oldYieldPos || this.yieldPos;
  20969. this.awaitPos = oldAwaitPos || this.awaitPos;
  20970. this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;
  20971. var node$1 = this.startNodeAt(startPos, startLoc);
  20972. node$1.callee = base;
  20973. node$1.arguments = exprList;
  20974. if (optionalSupported) {
  20975. node$1.optional = optional;
  20976. }
  20977. base = this.finishNode(node$1, "CallExpression");
  20978. } else if (this.type === types$1.backQuote) {
  20979. if (optional || optionalChained) {
  20980. this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions");
  20981. }
  20982. var node$2 = this.startNodeAt(startPos, startLoc);
  20983. node$2.tag = base;
  20984. node$2.quasi = this.parseTemplate({isTagged: true});
  20985. base = this.finishNode(node$2, "TaggedTemplateExpression");
  20986. }
  20987. return base
  20988. };
  20989. // Parse an atomic expression — either a single token that is an
  20990. // expression, an expression started by a keyword like `function` or
  20991. // `new`, or an expression wrapped in punctuation like `()`, `[]`,
  20992. // or `{}`.
  20993. pp$5.parseExprAtom = function(refDestructuringErrors, forInit, forNew) {
  20994. // If a division operator appears in an expression position, the
  20995. // tokenizer got confused, and we force it to read a regexp instead.
  20996. if (this.type === types$1.slash) { this.readRegexp(); }
  20997. var node, canBeArrow = this.potentialArrowAt === this.start;
  20998. switch (this.type) {
  20999. case types$1._super:
  21000. if (!this.allowSuper)
  21001. { this.raise(this.start, "'super' keyword outside a method"); }
  21002. node = this.startNode();
  21003. this.next();
  21004. if (this.type === types$1.parenL && !this.allowDirectSuper)
  21005. { this.raise(node.start, "super() call outside constructor of a subclass"); }
  21006. // The `super` keyword can appear at below:
  21007. // SuperProperty:
  21008. // super [ Expression ]
  21009. // super . IdentifierName
  21010. // SuperCall:
  21011. // super ( Arguments )
  21012. if (this.type !== types$1.dot && this.type !== types$1.bracketL && this.type !== types$1.parenL)
  21013. { this.unexpected(); }
  21014. return this.finishNode(node, "Super")
  21015. case types$1._this:
  21016. node = this.startNode();
  21017. this.next();
  21018. return this.finishNode(node, "ThisExpression")
  21019. case types$1.name:
  21020. var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc;
  21021. var id = this.parseIdent(false);
  21022. if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types$1._function)) {
  21023. this.overrideContext(types.f_expr);
  21024. return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true, forInit)
  21025. }
  21026. if (canBeArrow && !this.canInsertSemicolon()) {
  21027. if (this.eat(types$1.arrow))
  21028. { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false, forInit) }
  21029. if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types$1.name && !containsEsc &&
  21030. (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) {
  21031. id = this.parseIdent(false);
  21032. if (this.canInsertSemicolon() || !this.eat(types$1.arrow))
  21033. { this.unexpected(); }
  21034. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true, forInit)
  21035. }
  21036. }
  21037. return id
  21038. case types$1.regexp:
  21039. var value = this.value;
  21040. node = this.parseLiteral(value.value);
  21041. node.regex = {pattern: value.pattern, flags: value.flags};
  21042. return node
  21043. case types$1.num: case types$1.string:
  21044. return this.parseLiteral(this.value)
  21045. case types$1._null: case types$1._true: case types$1._false:
  21046. node = this.startNode();
  21047. node.value = this.type === types$1._null ? null : this.type === types$1._true;
  21048. node.raw = this.type.keyword;
  21049. this.next();
  21050. return this.finishNode(node, "Literal")
  21051. case types$1.parenL:
  21052. var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow, forInit);
  21053. if (refDestructuringErrors) {
  21054. if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))
  21055. { refDestructuringErrors.parenthesizedAssign = start; }
  21056. if (refDestructuringErrors.parenthesizedBind < 0)
  21057. { refDestructuringErrors.parenthesizedBind = start; }
  21058. }
  21059. return expr
  21060. case types$1.bracketL:
  21061. node = this.startNode();
  21062. this.next();
  21063. node.elements = this.parseExprList(types$1.bracketR, true, true, refDestructuringErrors);
  21064. return this.finishNode(node, "ArrayExpression")
  21065. case types$1.braceL:
  21066. this.overrideContext(types.b_expr);
  21067. return this.parseObj(false, refDestructuringErrors)
  21068. case types$1._function:
  21069. node = this.startNode();
  21070. this.next();
  21071. return this.parseFunction(node, 0)
  21072. case types$1._class:
  21073. return this.parseClass(this.startNode(), false)
  21074. case types$1._new:
  21075. return this.parseNew()
  21076. case types$1.backQuote:
  21077. return this.parseTemplate()
  21078. case types$1._import:
  21079. if (this.options.ecmaVersion >= 11) {
  21080. return this.parseExprImport(forNew)
  21081. } else {
  21082. return this.unexpected()
  21083. }
  21084. default:
  21085. return this.parseExprAtomDefault()
  21086. }
  21087. };
  21088. pp$5.parseExprAtomDefault = function() {
  21089. this.unexpected();
  21090. };
  21091. pp$5.parseExprImport = function(forNew) {
  21092. var node = this.startNode();
  21093. // Consume `import` as an identifier for `import.meta`.
  21094. // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`.
  21095. if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); }
  21096. var meta = this.parseIdent(true);
  21097. if (this.type === types$1.parenL && !forNew) {
  21098. return this.parseDynamicImport(node)
  21099. } else if (this.type === types$1.dot) {
  21100. node.meta = meta;
  21101. return this.parseImportMeta(node)
  21102. } else {
  21103. this.unexpected();
  21104. }
  21105. };
  21106. pp$5.parseDynamicImport = function(node) {
  21107. this.next(); // skip `(`
  21108. // Parse node.source.
  21109. node.source = this.parseMaybeAssign();
  21110. // Verify ending.
  21111. if (!this.eat(types$1.parenR)) {
  21112. var errorPos = this.start;
  21113. if (this.eat(types$1.comma) && this.eat(types$1.parenR)) {
  21114. this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()");
  21115. } else {
  21116. this.unexpected(errorPos);
  21117. }
  21118. }
  21119. return this.finishNode(node, "ImportExpression")
  21120. };
  21121. pp$5.parseImportMeta = function(node) {
  21122. this.next(); // skip `.`
  21123. var containsEsc = this.containsEsc;
  21124. node.property = this.parseIdent(true);
  21125. if (node.property.name !== "meta")
  21126. { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); }
  21127. if (containsEsc)
  21128. { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); }
  21129. if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere)
  21130. { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); }
  21131. return this.finishNode(node, "MetaProperty")
  21132. };
  21133. pp$5.parseLiteral = function(value) {
  21134. var node = this.startNode();
  21135. node.value = value;
  21136. node.raw = this.input.slice(this.start, this.end);
  21137. if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); }
  21138. this.next();
  21139. return this.finishNode(node, "Literal")
  21140. };
  21141. pp$5.parseParenExpression = function() {
  21142. this.expect(types$1.parenL);
  21143. var val = this.parseExpression();
  21144. this.expect(types$1.parenR);
  21145. return val
  21146. };
  21147. pp$5.shouldParseArrow = function(exprList) {
  21148. return !this.canInsertSemicolon()
  21149. };
  21150. pp$5.parseParenAndDistinguishExpression = function(canBeArrow, forInit) {
  21151. var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;
  21152. if (this.options.ecmaVersion >= 6) {
  21153. this.next();
  21154. var innerStartPos = this.start, innerStartLoc = this.startLoc;
  21155. var exprList = [], first = true, lastIsComma = false;
  21156. var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart;
  21157. this.yieldPos = 0;
  21158. this.awaitPos = 0;
  21159. // Do not save awaitIdentPos to allow checking awaits nested in parameters
  21160. while (this.type !== types$1.parenR) {
  21161. first ? first = false : this.expect(types$1.comma);
  21162. if (allowTrailingComma && this.afterTrailingComma(types$1.parenR, true)) {
  21163. lastIsComma = true;
  21164. break
  21165. } else if (this.type === types$1.ellipsis) {
  21166. spreadStart = this.start;
  21167. exprList.push(this.parseParenItem(this.parseRestBinding()));
  21168. if (this.type === types$1.comma) {
  21169. this.raiseRecoverable(
  21170. this.start,
  21171. "Comma is not permitted after the rest element"
  21172. );
  21173. }
  21174. break
  21175. } else {
  21176. exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));
  21177. }
  21178. }
  21179. var innerEndPos = this.lastTokEnd, innerEndLoc = this.lastTokEndLoc;
  21180. this.expect(types$1.parenR);
  21181. if (canBeArrow && this.shouldParseArrow(exprList) && this.eat(types$1.arrow)) {
  21182. this.checkPatternErrors(refDestructuringErrors, false);
  21183. this.checkYieldAwaitInDefaultParams();
  21184. this.yieldPos = oldYieldPos;
  21185. this.awaitPos = oldAwaitPos;
  21186. return this.parseParenArrowList(startPos, startLoc, exprList, forInit)
  21187. }
  21188. if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); }
  21189. if (spreadStart) { this.unexpected(spreadStart); }
  21190. this.checkExpressionErrors(refDestructuringErrors, true);
  21191. this.yieldPos = oldYieldPos || this.yieldPos;
  21192. this.awaitPos = oldAwaitPos || this.awaitPos;
  21193. if (exprList.length > 1) {
  21194. val = this.startNodeAt(innerStartPos, innerStartLoc);
  21195. val.expressions = exprList;
  21196. this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
  21197. } else {
  21198. val = exprList[0];
  21199. }
  21200. } else {
  21201. val = this.parseParenExpression();
  21202. }
  21203. if (this.options.preserveParens) {
  21204. var par = this.startNodeAt(startPos, startLoc);
  21205. par.expression = val;
  21206. return this.finishNode(par, "ParenthesizedExpression")
  21207. } else {
  21208. return val
  21209. }
  21210. };
  21211. pp$5.parseParenItem = function(item) {
  21212. return item
  21213. };
  21214. pp$5.parseParenArrowList = function(startPos, startLoc, exprList, forInit) {
  21215. return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, false, forInit)
  21216. };
  21217. // New's precedence is slightly tricky. It must allow its argument to
  21218. // be a `[]` or dot subscript expression, but not a call — at least,
  21219. // not without wrapping it in parentheses. Thus, it uses the noCalls
  21220. // argument to parseSubscripts to prevent it from consuming the
  21221. // argument list.
  21222. var empty = [];
  21223. pp$5.parseNew = function() {
  21224. if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); }
  21225. var node = this.startNode();
  21226. var meta = this.parseIdent(true);
  21227. if (this.options.ecmaVersion >= 6 && this.eat(types$1.dot)) {
  21228. node.meta = meta;
  21229. var containsEsc = this.containsEsc;
  21230. node.property = this.parseIdent(true);
  21231. if (node.property.name !== "target")
  21232. { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); }
  21233. if (containsEsc)
  21234. { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); }
  21235. if (!this.allowNewDotTarget)
  21236. { this.raiseRecoverable(node.start, "'new.target' can only be used in functions and class static block"); }
  21237. return this.finishNode(node, "MetaProperty")
  21238. }
  21239. var startPos = this.start, startLoc = this.startLoc;
  21240. node.callee = this.parseSubscripts(this.parseExprAtom(null, false, true), startPos, startLoc, true, false);
  21241. if (this.eat(types$1.parenL)) { node.arguments = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false); }
  21242. else { node.arguments = empty; }
  21243. return this.finishNode(node, "NewExpression")
  21244. };
  21245. // Parse template expression.
  21246. pp$5.parseTemplateElement = function(ref) {
  21247. var isTagged = ref.isTagged;
  21248. var elem = this.startNode();
  21249. if (this.type === types$1.invalidTemplate) {
  21250. if (!isTagged) {
  21251. this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");
  21252. }
  21253. elem.value = {
  21254. raw: this.value,
  21255. cooked: null
  21256. };
  21257. } else {
  21258. elem.value = {
  21259. raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
  21260. cooked: this.value
  21261. };
  21262. }
  21263. this.next();
  21264. elem.tail = this.type === types$1.backQuote;
  21265. return this.finishNode(elem, "TemplateElement")
  21266. };
  21267. pp$5.parseTemplate = function(ref) {
  21268. if ( ref === void 0 ) ref = {};
  21269. var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false;
  21270. var node = this.startNode();
  21271. this.next();
  21272. node.expressions = [];
  21273. var curElt = this.parseTemplateElement({isTagged: isTagged});
  21274. node.quasis = [curElt];
  21275. while (!curElt.tail) {
  21276. if (this.type === types$1.eof) { this.raise(this.pos, "Unterminated template literal"); }
  21277. this.expect(types$1.dollarBraceL);
  21278. node.expressions.push(this.parseExpression());
  21279. this.expect(types$1.braceR);
  21280. node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged}));
  21281. }
  21282. this.next();
  21283. return this.finishNode(node, "TemplateLiteral")
  21284. };
  21285. pp$5.isAsyncProp = function(prop) {
  21286. return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" &&
  21287. (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)) &&
  21288. !lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
  21289. };
  21290. // Parse an object literal or binding pattern.
  21291. pp$5.parseObj = function(isPattern, refDestructuringErrors) {
  21292. var node = this.startNode(), first = true, propHash = {};
  21293. node.properties = [];
  21294. this.next();
  21295. while (!this.eat(types$1.braceR)) {
  21296. if (!first) {
  21297. this.expect(types$1.comma);
  21298. if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types$1.braceR)) { break }
  21299. } else { first = false; }
  21300. var prop = this.parseProperty(isPattern, refDestructuringErrors);
  21301. if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); }
  21302. node.properties.push(prop);
  21303. }
  21304. return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")
  21305. };
  21306. pp$5.parseProperty = function(isPattern, refDestructuringErrors) {
  21307. var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc;
  21308. if (this.options.ecmaVersion >= 9 && this.eat(types$1.ellipsis)) {
  21309. if (isPattern) {
  21310. prop.argument = this.parseIdent(false);
  21311. if (this.type === types$1.comma) {
  21312. this.raiseRecoverable(this.start, "Comma is not permitted after the rest element");
  21313. }
  21314. return this.finishNode(prop, "RestElement")
  21315. }
  21316. // Parse argument.
  21317. prop.argument = this.parseMaybeAssign(false, refDestructuringErrors);
  21318. // To disallow trailing comma via `this.toAssignable()`.
  21319. if (this.type === types$1.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {
  21320. refDestructuringErrors.trailingComma = this.start;
  21321. }
  21322. // Finish
  21323. return this.finishNode(prop, "SpreadElement")
  21324. }
  21325. if (this.options.ecmaVersion >= 6) {
  21326. prop.method = false;
  21327. prop.shorthand = false;
  21328. if (isPattern || refDestructuringErrors) {
  21329. startPos = this.start;
  21330. startLoc = this.startLoc;
  21331. }
  21332. if (!isPattern)
  21333. { isGenerator = this.eat(types$1.star); }
  21334. }
  21335. var containsEsc = this.containsEsc;
  21336. this.parsePropertyName(prop);
  21337. if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {
  21338. isAsync = true;
  21339. isGenerator = this.options.ecmaVersion >= 9 && this.eat(types$1.star);
  21340. this.parsePropertyName(prop);
  21341. } else {
  21342. isAsync = false;
  21343. }
  21344. this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc);
  21345. return this.finishNode(prop, "Property")
  21346. };
  21347. pp$5.parseGetterSetter = function(prop) {
  21348. prop.kind = prop.key.name;
  21349. this.parsePropertyName(prop);
  21350. prop.value = this.parseMethod(false);
  21351. var paramCount = prop.kind === "get" ? 0 : 1;
  21352. if (prop.value.params.length !== paramCount) {
  21353. var start = prop.value.start;
  21354. if (prop.kind === "get")
  21355. { this.raiseRecoverable(start, "getter should have no params"); }
  21356. else
  21357. { this.raiseRecoverable(start, "setter should have exactly one param"); }
  21358. } else {
  21359. if (prop.kind === "set" && prop.value.params[0].type === "RestElement")
  21360. { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); }
  21361. }
  21362. };
  21363. pp$5.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) {
  21364. if ((isGenerator || isAsync) && this.type === types$1.colon)
  21365. { this.unexpected(); }
  21366. if (this.eat(types$1.colon)) {
  21367. prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);
  21368. prop.kind = "init";
  21369. } else if (this.options.ecmaVersion >= 6 && this.type === types$1.parenL) {
  21370. if (isPattern) { this.unexpected(); }
  21371. prop.kind = "init";
  21372. prop.method = true;
  21373. prop.value = this.parseMethod(isGenerator, isAsync);
  21374. } else if (!isPattern && !containsEsc &&
  21375. this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" &&
  21376. (prop.key.name === "get" || prop.key.name === "set") &&
  21377. (this.type !== types$1.comma && this.type !== types$1.braceR && this.type !== types$1.eq)) {
  21378. if (isGenerator || isAsync) { this.unexpected(); }
  21379. this.parseGetterSetter(prop);
  21380. } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
  21381. if (isGenerator || isAsync) { this.unexpected(); }
  21382. this.checkUnreserved(prop.key);
  21383. if (prop.key.name === "await" && !this.awaitIdentPos)
  21384. { this.awaitIdentPos = startPos; }
  21385. prop.kind = "init";
  21386. if (isPattern) {
  21387. prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
  21388. } else if (this.type === types$1.eq && refDestructuringErrors) {
  21389. if (refDestructuringErrors.shorthandAssign < 0)
  21390. { refDestructuringErrors.shorthandAssign = this.start; }
  21391. prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
  21392. } else {
  21393. prop.value = this.copyNode(prop.key);
  21394. }
  21395. prop.shorthand = true;
  21396. } else { this.unexpected(); }
  21397. };
  21398. pp$5.parsePropertyName = function(prop) {
  21399. if (this.options.ecmaVersion >= 6) {
  21400. if (this.eat(types$1.bracketL)) {
  21401. prop.computed = true;
  21402. prop.key = this.parseMaybeAssign();
  21403. this.expect(types$1.bracketR);
  21404. return prop.key
  21405. } else {
  21406. prop.computed = false;
  21407. }
  21408. }
  21409. return prop.key = this.type === types$1.num || this.type === types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never")
  21410. };
  21411. // Initialize empty function node.
  21412. pp$5.initFunction = function(node) {
  21413. node.id = null;
  21414. if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; }
  21415. if (this.options.ecmaVersion >= 8) { node.async = false; }
  21416. };
  21417. // Parse object or class method.
  21418. pp$5.parseMethod = function(isGenerator, isAsync, allowDirectSuper) {
  21419. var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  21420. this.initFunction(node);
  21421. if (this.options.ecmaVersion >= 6)
  21422. { node.generator = isGenerator; }
  21423. if (this.options.ecmaVersion >= 8)
  21424. { node.async = !!isAsync; }
  21425. this.yieldPos = 0;
  21426. this.awaitPos = 0;
  21427. this.awaitIdentPos = 0;
  21428. this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
  21429. this.expect(types$1.parenL);
  21430. node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8);
  21431. this.checkYieldAwaitInDefaultParams();
  21432. this.parseFunctionBody(node, false, true, false);
  21433. this.yieldPos = oldYieldPos;
  21434. this.awaitPos = oldAwaitPos;
  21435. this.awaitIdentPos = oldAwaitIdentPos;
  21436. return this.finishNode(node, "FunctionExpression")
  21437. };
  21438. // Parse arrow function expression with given parameters.
  21439. pp$5.parseArrowExpression = function(node, params, isAsync, forInit) {
  21440. var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
  21441. this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW);
  21442. this.initFunction(node);
  21443. if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; }
  21444. this.yieldPos = 0;
  21445. this.awaitPos = 0;
  21446. this.awaitIdentPos = 0;
  21447. node.params = this.toAssignableList(params, true);
  21448. this.parseFunctionBody(node, true, false, forInit);
  21449. this.yieldPos = oldYieldPos;
  21450. this.awaitPos = oldAwaitPos;
  21451. this.awaitIdentPos = oldAwaitIdentPos;
  21452. return this.finishNode(node, "ArrowFunctionExpression")
  21453. };
  21454. // Parse function body and check parameters.
  21455. pp$5.parseFunctionBody = function(node, isArrowFunction, isMethod, forInit) {
  21456. var isExpression = isArrowFunction && this.type !== types$1.braceL;
  21457. var oldStrict = this.strict, useStrict = false;
  21458. if (isExpression) {
  21459. node.body = this.parseMaybeAssign(forInit);
  21460. node.expression = true;
  21461. this.checkParams(node, false);
  21462. } else {
  21463. var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);
  21464. if (!oldStrict || nonSimple) {
  21465. useStrict = this.strictDirective(this.end);
  21466. // If this is a strict mode function, verify that argument names
  21467. // are not repeated, and it does not try to bind the words `eval`
  21468. // or `arguments`.
  21469. if (useStrict && nonSimple)
  21470. { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); }
  21471. }
  21472. // Start a new scope with regard to labels and the `inFunction`
  21473. // flag (restore them to their old value afterwards).
  21474. var oldLabels = this.labels;
  21475. this.labels = [];
  21476. if (useStrict) { this.strict = true; }
  21477. // Add the params to varDeclaredNames to ensure that an error is thrown
  21478. // if a let/const declaration in the function clashes with one of the params.
  21479. this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params));
  21480. // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'
  21481. if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); }
  21482. node.body = this.parseBlock(false, undefined, useStrict && !oldStrict);
  21483. node.expression = false;
  21484. this.adaptDirectivePrologue(node.body.body);
  21485. this.labels = oldLabels;
  21486. }
  21487. this.exitScope();
  21488. };
  21489. pp$5.isSimpleParamList = function(params) {
  21490. for (var i = 0, list = params; i < list.length; i += 1)
  21491. {
  21492. var param = list[i];
  21493. if (param.type !== "Identifier") { return false
  21494. } }
  21495. return true
  21496. };
  21497. // Checks function params for various disallowed patterns such as using "eval"
  21498. // or "arguments" and duplicate parameters.
  21499. pp$5.checkParams = function(node, allowDuplicates) {
  21500. var nameHash = Object.create(null);
  21501. for (var i = 0, list = node.params; i < list.length; i += 1)
  21502. {
  21503. var param = list[i];
  21504. this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash);
  21505. }
  21506. };
  21507. // Parses a comma-separated list of expressions, and returns them as
  21508. // an array. `close` is the token type that ends the list, and
  21509. // `allowEmpty` can be turned on to allow subsequent commas with
  21510. // nothing in between them to be parsed as `null` (which is needed
  21511. // for array literals).
  21512. pp$5.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
  21513. var elts = [], first = true;
  21514. while (!this.eat(close)) {
  21515. if (!first) {
  21516. this.expect(types$1.comma);
  21517. if (allowTrailingComma && this.afterTrailingComma(close)) { break }
  21518. } else { first = false; }
  21519. var elt = (void 0);
  21520. if (allowEmpty && this.type === types$1.comma)
  21521. { elt = null; }
  21522. else if (this.type === types$1.ellipsis) {
  21523. elt = this.parseSpread(refDestructuringErrors);
  21524. if (refDestructuringErrors && this.type === types$1.comma && refDestructuringErrors.trailingComma < 0)
  21525. { refDestructuringErrors.trailingComma = this.start; }
  21526. } else {
  21527. elt = this.parseMaybeAssign(false, refDestructuringErrors);
  21528. }
  21529. elts.push(elt);
  21530. }
  21531. return elts
  21532. };
  21533. pp$5.checkUnreserved = function(ref) {
  21534. var start = ref.start;
  21535. var end = ref.end;
  21536. var name = ref.name;
  21537. if (this.inGenerator && name === "yield")
  21538. { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); }
  21539. if (this.inAsync && name === "await")
  21540. { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); }
  21541. if (this.currentThisScope().inClassFieldInit && name === "arguments")
  21542. { this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer"); }
  21543. if (this.inClassStaticBlock && (name === "arguments" || name === "await"))
  21544. { this.raise(start, ("Cannot use " + name + " in class static initialization block")); }
  21545. if (this.keywords.test(name))
  21546. { this.raise(start, ("Unexpected keyword '" + name + "'")); }
  21547. if (this.options.ecmaVersion < 6 &&
  21548. this.input.slice(start, end).indexOf("\\") !== -1) { return }
  21549. var re = this.strict ? this.reservedWordsStrict : this.reservedWords;
  21550. if (re.test(name)) {
  21551. if (!this.inAsync && name === "await")
  21552. { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); }
  21553. this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved"));
  21554. }
  21555. };
  21556. // Parse the next token as an identifier. If `liberal` is true (used
  21557. // when parsing properties), it will also convert keywords into
  21558. // identifiers.
  21559. pp$5.parseIdent = function(liberal) {
  21560. var node = this.parseIdentNode();
  21561. this.next(!!liberal);
  21562. this.finishNode(node, "Identifier");
  21563. if (!liberal) {
  21564. this.checkUnreserved(node);
  21565. if (node.name === "await" && !this.awaitIdentPos)
  21566. { this.awaitIdentPos = node.start; }
  21567. }
  21568. return node
  21569. };
  21570. pp$5.parseIdentNode = function() {
  21571. var node = this.startNode();
  21572. if (this.type === types$1.name) {
  21573. node.name = this.value;
  21574. } else if (this.type.keyword) {
  21575. node.name = this.type.keyword;
  21576. // To fix https://github.com/acornjs/acorn/issues/575
  21577. // `class` and `function` keywords push new context into this.context.
  21578. // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name.
  21579. // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword
  21580. if ((node.name === "class" || node.name === "function") &&
  21581. (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {
  21582. this.context.pop();
  21583. }
  21584. } else {
  21585. this.unexpected();
  21586. }
  21587. return node
  21588. };
  21589. pp$5.parsePrivateIdent = function() {
  21590. var node = this.startNode();
  21591. if (this.type === types$1.privateId) {
  21592. node.name = this.value;
  21593. } else {
  21594. this.unexpected();
  21595. }
  21596. this.next();
  21597. this.finishNode(node, "PrivateIdentifier");
  21598. // For validating existence
  21599. if (this.options.checkPrivateFields) {
  21600. if (this.privateNameStack.length === 0) {
  21601. this.raise(node.start, ("Private field '#" + (node.name) + "' must be declared in an enclosing class"));
  21602. } else {
  21603. this.privateNameStack[this.privateNameStack.length - 1].used.push(node);
  21604. }
  21605. }
  21606. return node
  21607. };
  21608. // Parses yield expression inside generator.
  21609. pp$5.parseYield = function(forInit) {
  21610. if (!this.yieldPos) { this.yieldPos = this.start; }
  21611. var node = this.startNode();
  21612. this.next();
  21613. if (this.type === types$1.semi || this.canInsertSemicolon() || (this.type !== types$1.star && !this.type.startsExpr)) {
  21614. node.delegate = false;
  21615. node.argument = null;
  21616. } else {
  21617. node.delegate = this.eat(types$1.star);
  21618. node.argument = this.parseMaybeAssign(forInit);
  21619. }
  21620. return this.finishNode(node, "YieldExpression")
  21621. };
  21622. pp$5.parseAwait = function(forInit) {
  21623. if (!this.awaitPos) { this.awaitPos = this.start; }
  21624. var node = this.startNode();
  21625. this.next();
  21626. node.argument = this.parseMaybeUnary(null, true, false, forInit);
  21627. return this.finishNode(node, "AwaitExpression")
  21628. };
  21629. var pp$4 = Parser.prototype;
  21630. // This function is used to raise exceptions on parse errors. It
  21631. // takes an offset integer (into the current `input`) to indicate
  21632. // the location of the error, attaches the position to the end
  21633. // of the error message, and then raises a `SyntaxError` with that
  21634. // message.
  21635. pp$4.raise = function(pos, message) {
  21636. var loc = getLineInfo(this.input, pos);
  21637. message += " (" + loc.line + ":" + loc.column + ")";
  21638. var err = new SyntaxError(message);
  21639. err.pos = pos; err.loc = loc; err.raisedAt = this.pos;
  21640. throw err
  21641. };
  21642. pp$4.raiseRecoverable = pp$4.raise;
  21643. pp$4.curPosition = function() {
  21644. if (this.options.locations) {
  21645. return new Position(this.curLine, this.pos - this.lineStart)
  21646. }
  21647. };
  21648. var pp$3 = Parser.prototype;
  21649. var Scope = function Scope(flags) {
  21650. this.flags = flags;
  21651. // A list of var-declared names in the current lexical scope
  21652. this.var = [];
  21653. // A list of lexically-declared names in the current lexical scope
  21654. this.lexical = [];
  21655. // A list of lexically-declared FunctionDeclaration names in the current lexical scope
  21656. this.functions = [];
  21657. // A switch to disallow the identifier reference 'arguments'
  21658. this.inClassFieldInit = false;
  21659. };
  21660. // The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names.
  21661. pp$3.enterScope = function(flags) {
  21662. this.scopeStack.push(new Scope(flags));
  21663. };
  21664. pp$3.exitScope = function() {
  21665. this.scopeStack.pop();
  21666. };
  21667. // The spec says:
  21668. // > At the top level of a function, or script, function declarations are
  21669. // > treated like var declarations rather than like lexical declarations.
  21670. pp$3.treatFunctionsAsVarInScope = function(scope) {
  21671. return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP)
  21672. };
  21673. pp$3.declareName = function(name, bindingType, pos) {
  21674. var redeclared = false;
  21675. if (bindingType === BIND_LEXICAL) {
  21676. var scope = this.currentScope();
  21677. redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
  21678. scope.lexical.push(name);
  21679. if (this.inModule && (scope.flags & SCOPE_TOP))
  21680. { delete this.undefinedExports[name]; }
  21681. } else if (bindingType === BIND_SIMPLE_CATCH) {
  21682. var scope$1 = this.currentScope();
  21683. scope$1.lexical.push(name);
  21684. } else if (bindingType === BIND_FUNCTION) {
  21685. var scope$2 = this.currentScope();
  21686. if (this.treatFunctionsAsVar)
  21687. { redeclared = scope$2.lexical.indexOf(name) > -1; }
  21688. else
  21689. { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; }
  21690. scope$2.functions.push(name);
  21691. } else {
  21692. for (var i = this.scopeStack.length - 1; i >= 0; --i) {
  21693. var scope$3 = this.scopeStack[i];
  21694. if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) ||
  21695. !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) {
  21696. redeclared = true;
  21697. break
  21698. }
  21699. scope$3.var.push(name);
  21700. if (this.inModule && (scope$3.flags & SCOPE_TOP))
  21701. { delete this.undefinedExports[name]; }
  21702. if (scope$3.flags & SCOPE_VAR) { break }
  21703. }
  21704. }
  21705. if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); }
  21706. };
  21707. pp$3.checkLocalExport = function(id) {
  21708. // scope.functions must be empty as Module code is always strict.
  21709. if (this.scopeStack[0].lexical.indexOf(id.name) === -1 &&
  21710. this.scopeStack[0].var.indexOf(id.name) === -1) {
  21711. this.undefinedExports[id.name] = id;
  21712. }
  21713. };
  21714. pp$3.currentScope = function() {
  21715. return this.scopeStack[this.scopeStack.length - 1]
  21716. };
  21717. pp$3.currentVarScope = function() {
  21718. for (var i = this.scopeStack.length - 1;; i--) {
  21719. var scope = this.scopeStack[i];
  21720. if (scope.flags & SCOPE_VAR) { return scope }
  21721. }
  21722. };
  21723. // Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`.
  21724. pp$3.currentThisScope = function() {
  21725. for (var i = this.scopeStack.length - 1;; i--) {
  21726. var scope = this.scopeStack[i];
  21727. if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope }
  21728. }
  21729. };
  21730. var Node = function Node(parser, pos, loc) {
  21731. this.type = "";
  21732. this.start = pos;
  21733. this.end = 0;
  21734. if (parser.options.locations)
  21735. { this.loc = new SourceLocation(parser, loc); }
  21736. if (parser.options.directSourceFile)
  21737. { this.sourceFile = parser.options.directSourceFile; }
  21738. if (parser.options.ranges)
  21739. { this.range = [pos, 0]; }
  21740. };
  21741. // Start an AST node, attaching a start offset.
  21742. var pp$2 = Parser.prototype;
  21743. pp$2.startNode = function() {
  21744. return new Node(this, this.start, this.startLoc)
  21745. };
  21746. pp$2.startNodeAt = function(pos, loc) {
  21747. return new Node(this, pos, loc)
  21748. };
  21749. // Finish an AST node, adding `type` and `end` properties.
  21750. function finishNodeAt(node, type, pos, loc) {
  21751. node.type = type;
  21752. node.end = pos;
  21753. if (this.options.locations)
  21754. { node.loc.end = loc; }
  21755. if (this.options.ranges)
  21756. { node.range[1] = pos; }
  21757. return node
  21758. }
  21759. pp$2.finishNode = function(node, type) {
  21760. return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)
  21761. };
  21762. // Finish node at given position
  21763. pp$2.finishNodeAt = function(node, type, pos, loc) {
  21764. return finishNodeAt.call(this, node, type, pos, loc)
  21765. };
  21766. pp$2.copyNode = function(node) {
  21767. var newNode = new Node(this, node.start, this.startLoc);
  21768. for (var prop in node) { newNode[prop] = node[prop]; }
  21769. return newNode
  21770. };
  21771. // This file contains Unicode properties extracted from the ECMAScript specification.
  21772. // The lists are extracted like so:
  21773. // $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText)
  21774. // #table-binary-unicode-properties
  21775. 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";
  21776. var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic";
  21777. var ecma11BinaryProperties = ecma10BinaryProperties;
  21778. var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict";
  21779. var ecma13BinaryProperties = ecma12BinaryProperties;
  21780. var ecma14BinaryProperties = ecma13BinaryProperties;
  21781. var unicodeBinaryProperties = {
  21782. 9: ecma9BinaryProperties,
  21783. 10: ecma10BinaryProperties,
  21784. 11: ecma11BinaryProperties,
  21785. 12: ecma12BinaryProperties,
  21786. 13: ecma13BinaryProperties,
  21787. 14: ecma14BinaryProperties
  21788. };
  21789. // #table-binary-unicode-properties-of-strings
  21790. 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";
  21791. var unicodeBinaryPropertiesOfStrings = {
  21792. 9: "",
  21793. 10: "",
  21794. 11: "",
  21795. 12: "",
  21796. 13: "",
  21797. 14: ecma14BinaryPropertiesOfStrings
  21798. };
  21799. // #table-unicode-general-category-values
  21800. 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";
  21801. // #table-unicode-script-values
  21802. 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";
  21803. var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";
  21804. var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";
  21805. var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";
  21806. var ecma13ScriptValues = ecma12ScriptValues + " Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith";
  21807. var ecma14ScriptValues = ecma13ScriptValues + " Hrkt Katakana_Or_Hiragana Kawi Nag_Mundari Nagm Unknown Zzzz";
  21808. var unicodeScriptValues = {
  21809. 9: ecma9ScriptValues,
  21810. 10: ecma10ScriptValues,
  21811. 11: ecma11ScriptValues,
  21812. 12: ecma12ScriptValues,
  21813. 13: ecma13ScriptValues,
  21814. 14: ecma14ScriptValues
  21815. };
  21816. var data = {};
  21817. function buildUnicodeData(ecmaVersion) {
  21818. var d = data[ecmaVersion] = {
  21819. binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues),
  21820. binaryOfStrings: wordsRegexp(unicodeBinaryPropertiesOfStrings[ecmaVersion]),
  21821. nonBinary: {
  21822. General_Category: wordsRegexp(unicodeGeneralCategoryValues),
  21823. Script: wordsRegexp(unicodeScriptValues[ecmaVersion])
  21824. }
  21825. };
  21826. d.nonBinary.Script_Extensions = d.nonBinary.Script;
  21827. d.nonBinary.gc = d.nonBinary.General_Category;
  21828. d.nonBinary.sc = d.nonBinary.Script;
  21829. d.nonBinary.scx = d.nonBinary.Script_Extensions;
  21830. }
  21831. for (var i = 0, list = [9, 10, 11, 12, 13, 14]; i < list.length; i += 1) {
  21832. var ecmaVersion = list[i];
  21833. buildUnicodeData(ecmaVersion);
  21834. }
  21835. var pp$1 = Parser.prototype;
  21836. var RegExpValidationState = function RegExpValidationState(parser) {
  21837. this.parser = parser;
  21838. this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : "") + (parser.options.ecmaVersion >= 15 ? "v" : "");
  21839. this.unicodeProperties = data[parser.options.ecmaVersion >= 14 ? 14 : parser.options.ecmaVersion];
  21840. this.source = "";
  21841. this.flags = "";
  21842. this.start = 0;
  21843. this.switchU = false;
  21844. this.switchV = false;
  21845. this.switchN = false;
  21846. this.pos = 0;
  21847. this.lastIntValue = 0;
  21848. this.lastStringValue = "";
  21849. this.lastAssertionIsQuantifiable = false;
  21850. this.numCapturingParens = 0;
  21851. this.maxBackReference = 0;
  21852. this.groupNames = [];
  21853. this.backReferenceNames = [];
  21854. };
  21855. RegExpValidationState.prototype.reset = function reset (start, pattern, flags) {
  21856. var unicodeSets = flags.indexOf("v") !== -1;
  21857. var unicode = flags.indexOf("u") !== -1;
  21858. this.start = start | 0;
  21859. this.source = pattern + "";
  21860. this.flags = flags;
  21861. if (unicodeSets && this.parser.options.ecmaVersion >= 15) {
  21862. this.switchU = true;
  21863. this.switchV = true;
  21864. this.switchN = true;
  21865. } else {
  21866. this.switchU = unicode && this.parser.options.ecmaVersion >= 6;
  21867. this.switchV = false;
  21868. this.switchN = unicode && this.parser.options.ecmaVersion >= 9;
  21869. }
  21870. };
  21871. RegExpValidationState.prototype.raise = function raise (message) {
  21872. this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message));
  21873. };
  21874. // If u flag is given, this returns the code point at the index (it combines a surrogate pair).
  21875. // Otherwise, this returns the code unit of the index (can be a part of a surrogate pair).
  21876. RegExpValidationState.prototype.at = function at (i, forceU) {
  21877. if ( forceU === void 0 ) forceU = false;
  21878. var s = this.source;
  21879. var l = s.length;
  21880. if (i >= l) {
  21881. return -1
  21882. }
  21883. var c = s.charCodeAt(i);
  21884. if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) {
  21885. return c
  21886. }
  21887. var next = s.charCodeAt(i + 1);
  21888. return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c
  21889. };
  21890. RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) {
  21891. if ( forceU === void 0 ) forceU = false;
  21892. var s = this.source;
  21893. var l = s.length;
  21894. if (i >= l) {
  21895. return l
  21896. }
  21897. var c = s.charCodeAt(i), next;
  21898. if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l ||
  21899. (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) {
  21900. return i + 1
  21901. }
  21902. return i + 2
  21903. };
  21904. RegExpValidationState.prototype.current = function current (forceU) {
  21905. if ( forceU === void 0 ) forceU = false;
  21906. return this.at(this.pos, forceU)
  21907. };
  21908. RegExpValidationState.prototype.lookahead = function lookahead (forceU) {
  21909. if ( forceU === void 0 ) forceU = false;
  21910. return this.at(this.nextIndex(this.pos, forceU), forceU)
  21911. };
  21912. RegExpValidationState.prototype.advance = function advance (forceU) {
  21913. if ( forceU === void 0 ) forceU = false;
  21914. this.pos = this.nextIndex(this.pos, forceU);
  21915. };
  21916. RegExpValidationState.prototype.eat = function eat (ch, forceU) {
  21917. if ( forceU === void 0 ) forceU = false;
  21918. if (this.current(forceU) === ch) {
  21919. this.advance(forceU);
  21920. return true
  21921. }
  21922. return false
  21923. };
  21924. RegExpValidationState.prototype.eatChars = function eatChars (chs, forceU) {
  21925. if ( forceU === void 0 ) forceU = false;
  21926. var pos = this.pos;
  21927. for (var i = 0, list = chs; i < list.length; i += 1) {
  21928. var ch = list[i];
  21929. var current = this.at(pos, forceU);
  21930. if (current === -1 || current !== ch) {
  21931. return false
  21932. }
  21933. pos = this.nextIndex(pos, forceU);
  21934. }
  21935. this.pos = pos;
  21936. return true
  21937. };
  21938. /**
  21939. * Validate the flags part of a given RegExpLiteral.
  21940. *
  21941. * @param {RegExpValidationState} state The state to validate RegExp.
  21942. * @returns {void}
  21943. */
  21944. pp$1.validateRegExpFlags = function(state) {
  21945. var validFlags = state.validFlags;
  21946. var flags = state.flags;
  21947. var u = false;
  21948. var v = false;
  21949. for (var i = 0; i < flags.length; i++) {
  21950. var flag = flags.charAt(i);
  21951. if (validFlags.indexOf(flag) === -1) {
  21952. this.raise(state.start, "Invalid regular expression flag");
  21953. }
  21954. if (flags.indexOf(flag, i + 1) > -1) {
  21955. this.raise(state.start, "Duplicate regular expression flag");
  21956. }
  21957. if (flag === "u") { u = true; }
  21958. if (flag === "v") { v = true; }
  21959. }
  21960. if (this.options.ecmaVersion >= 15 && u && v) {
  21961. this.raise(state.start, "Invalid regular expression flag");
  21962. }
  21963. };
  21964. /**
  21965. * Validate the pattern part of a given RegExpLiteral.
  21966. *
  21967. * @param {RegExpValidationState} state The state to validate RegExp.
  21968. * @returns {void}
  21969. */
  21970. pp$1.validateRegExpPattern = function(state) {
  21971. this.regexp_pattern(state);
  21972. // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of
  21973. // parsing contains a |GroupName|, reparse with the goal symbol
  21974. // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError*
  21975. // exception if _P_ did not conform to the grammar, if any elements of _P_
  21976. // were not matched by the parse, or if any Early Error conditions exist.
  21977. if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) {
  21978. state.switchN = true;
  21979. this.regexp_pattern(state);
  21980. }
  21981. };
  21982. // https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern
  21983. pp$1.regexp_pattern = function(state) {
  21984. state.pos = 0;
  21985. state.lastIntValue = 0;
  21986. state.lastStringValue = "";
  21987. state.lastAssertionIsQuantifiable = false;
  21988. state.numCapturingParens = 0;
  21989. state.maxBackReference = 0;
  21990. state.groupNames.length = 0;
  21991. state.backReferenceNames.length = 0;
  21992. this.regexp_disjunction(state);
  21993. if (state.pos !== state.source.length) {
  21994. // Make the same messages as V8.
  21995. if (state.eat(0x29 /* ) */)) {
  21996. state.raise("Unmatched ')'");
  21997. }
  21998. if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) {
  21999. state.raise("Lone quantifier brackets");
  22000. }
  22001. }
  22002. if (state.maxBackReference > state.numCapturingParens) {
  22003. state.raise("Invalid escape");
  22004. }
  22005. for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) {
  22006. var name = list[i];
  22007. if (state.groupNames.indexOf(name) === -1) {
  22008. state.raise("Invalid named capture referenced");
  22009. }
  22010. }
  22011. };
  22012. // https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction
  22013. pp$1.regexp_disjunction = function(state) {
  22014. this.regexp_alternative(state);
  22015. while (state.eat(0x7C /* | */)) {
  22016. this.regexp_alternative(state);
  22017. }
  22018. // Make the same message as V8.
  22019. if (this.regexp_eatQuantifier(state, true)) {
  22020. state.raise("Nothing to repeat");
  22021. }
  22022. if (state.eat(0x7B /* { */)) {
  22023. state.raise("Lone quantifier brackets");
  22024. }
  22025. };
  22026. // https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative
  22027. pp$1.regexp_alternative = function(state) {
  22028. while (state.pos < state.source.length && this.regexp_eatTerm(state))
  22029. { }
  22030. };
  22031. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term
  22032. pp$1.regexp_eatTerm = function(state) {
  22033. if (this.regexp_eatAssertion(state)) {
  22034. // Handle `QuantifiableAssertion Quantifier` alternative.
  22035. // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion
  22036. // is a QuantifiableAssertion.
  22037. if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) {
  22038. // Make the same message as V8.
  22039. if (state.switchU) {
  22040. state.raise("Invalid quantifier");
  22041. }
  22042. }
  22043. return true
  22044. }
  22045. if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) {
  22046. this.regexp_eatQuantifier(state);
  22047. return true
  22048. }
  22049. return false
  22050. };
  22051. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion
  22052. pp$1.regexp_eatAssertion = function(state) {
  22053. var start = state.pos;
  22054. state.lastAssertionIsQuantifiable = false;
  22055. // ^, $
  22056. if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) {
  22057. return true
  22058. }
  22059. // \b \B
  22060. if (state.eat(0x5C /* \ */)) {
  22061. if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) {
  22062. return true
  22063. }
  22064. state.pos = start;
  22065. }
  22066. // Lookahead / Lookbehind
  22067. if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) {
  22068. var lookbehind = false;
  22069. if (this.options.ecmaVersion >= 9) {
  22070. lookbehind = state.eat(0x3C /* < */);
  22071. }
  22072. if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) {
  22073. this.regexp_disjunction(state);
  22074. if (!state.eat(0x29 /* ) */)) {
  22075. state.raise("Unterminated group");
  22076. }
  22077. state.lastAssertionIsQuantifiable = !lookbehind;
  22078. return true
  22079. }
  22080. }
  22081. state.pos = start;
  22082. return false
  22083. };
  22084. // https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier
  22085. pp$1.regexp_eatQuantifier = function(state, noError) {
  22086. if ( noError === void 0 ) noError = false;
  22087. if (this.regexp_eatQuantifierPrefix(state, noError)) {
  22088. state.eat(0x3F /* ? */);
  22089. return true
  22090. }
  22091. return false
  22092. };
  22093. // https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix
  22094. pp$1.regexp_eatQuantifierPrefix = function(state, noError) {
  22095. return (
  22096. state.eat(0x2A /* * */) ||
  22097. state.eat(0x2B /* + */) ||
  22098. state.eat(0x3F /* ? */) ||
  22099. this.regexp_eatBracedQuantifier(state, noError)
  22100. )
  22101. };
  22102. pp$1.regexp_eatBracedQuantifier = function(state, noError) {
  22103. var start = state.pos;
  22104. if (state.eat(0x7B /* { */)) {
  22105. var min = 0, max = -1;
  22106. if (this.regexp_eatDecimalDigits(state)) {
  22107. min = state.lastIntValue;
  22108. if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) {
  22109. max = state.lastIntValue;
  22110. }
  22111. if (state.eat(0x7D /* } */)) {
  22112. // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term
  22113. if (max !== -1 && max < min && !noError) {
  22114. state.raise("numbers out of order in {} quantifier");
  22115. }
  22116. return true
  22117. }
  22118. }
  22119. if (state.switchU && !noError) {
  22120. state.raise("Incomplete quantifier");
  22121. }
  22122. state.pos = start;
  22123. }
  22124. return false
  22125. };
  22126. // https://www.ecma-international.org/ecma-262/8.0/#prod-Atom
  22127. pp$1.regexp_eatAtom = function(state) {
  22128. return (
  22129. this.regexp_eatPatternCharacters(state) ||
  22130. state.eat(0x2E /* . */) ||
  22131. this.regexp_eatReverseSolidusAtomEscape(state) ||
  22132. this.regexp_eatCharacterClass(state) ||
  22133. this.regexp_eatUncapturingGroup(state) ||
  22134. this.regexp_eatCapturingGroup(state)
  22135. )
  22136. };
  22137. pp$1.regexp_eatReverseSolidusAtomEscape = function(state) {
  22138. var start = state.pos;
  22139. if (state.eat(0x5C /* \ */)) {
  22140. if (this.regexp_eatAtomEscape(state)) {
  22141. return true
  22142. }
  22143. state.pos = start;
  22144. }
  22145. return false
  22146. };
  22147. pp$1.regexp_eatUncapturingGroup = function(state) {
  22148. var start = state.pos;
  22149. if (state.eat(0x28 /* ( */)) {
  22150. if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) {
  22151. this.regexp_disjunction(state);
  22152. if (state.eat(0x29 /* ) */)) {
  22153. return true
  22154. }
  22155. state.raise("Unterminated group");
  22156. }
  22157. state.pos = start;
  22158. }
  22159. return false
  22160. };
  22161. pp$1.regexp_eatCapturingGroup = function(state) {
  22162. if (state.eat(0x28 /* ( */)) {
  22163. if (this.options.ecmaVersion >= 9) {
  22164. this.regexp_groupSpecifier(state);
  22165. } else if (state.current() === 0x3F /* ? */) {
  22166. state.raise("Invalid group");
  22167. }
  22168. this.regexp_disjunction(state);
  22169. if (state.eat(0x29 /* ) */)) {
  22170. state.numCapturingParens += 1;
  22171. return true
  22172. }
  22173. state.raise("Unterminated group");
  22174. }
  22175. return false
  22176. };
  22177. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom
  22178. pp$1.regexp_eatExtendedAtom = function(state) {
  22179. return (
  22180. state.eat(0x2E /* . */) ||
  22181. this.regexp_eatReverseSolidusAtomEscape(state) ||
  22182. this.regexp_eatCharacterClass(state) ||
  22183. this.regexp_eatUncapturingGroup(state) ||
  22184. this.regexp_eatCapturingGroup(state) ||
  22185. this.regexp_eatInvalidBracedQuantifier(state) ||
  22186. this.regexp_eatExtendedPatternCharacter(state)
  22187. )
  22188. };
  22189. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier
  22190. pp$1.regexp_eatInvalidBracedQuantifier = function(state) {
  22191. if (this.regexp_eatBracedQuantifier(state, true)) {
  22192. state.raise("Nothing to repeat");
  22193. }
  22194. return false
  22195. };
  22196. // https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter
  22197. pp$1.regexp_eatSyntaxCharacter = function(state) {
  22198. var ch = state.current();
  22199. if (isSyntaxCharacter(ch)) {
  22200. state.lastIntValue = ch;
  22201. state.advance();
  22202. return true
  22203. }
  22204. return false
  22205. };
  22206. function isSyntaxCharacter(ch) {
  22207. return (
  22208. ch === 0x24 /* $ */ ||
  22209. ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ ||
  22210. ch === 0x2E /* . */ ||
  22211. ch === 0x3F /* ? */ ||
  22212. ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ ||
  22213. ch >= 0x7B /* { */ && ch <= 0x7D /* } */
  22214. )
  22215. }
  22216. // https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter
  22217. // But eat eager.
  22218. pp$1.regexp_eatPatternCharacters = function(state) {
  22219. var start = state.pos;
  22220. var ch = 0;
  22221. while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) {
  22222. state.advance();
  22223. }
  22224. return state.pos !== start
  22225. };
  22226. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter
  22227. pp$1.regexp_eatExtendedPatternCharacter = function(state) {
  22228. var ch = state.current();
  22229. if (
  22230. ch !== -1 &&
  22231. ch !== 0x24 /* $ */ &&
  22232. !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) &&
  22233. ch !== 0x2E /* . */ &&
  22234. ch !== 0x3F /* ? */ &&
  22235. ch !== 0x5B /* [ */ &&
  22236. ch !== 0x5E /* ^ */ &&
  22237. ch !== 0x7C /* | */
  22238. ) {
  22239. state.advance();
  22240. return true
  22241. }
  22242. return false
  22243. };
  22244. // GroupSpecifier ::
  22245. // [empty]
  22246. // `?` GroupName
  22247. pp$1.regexp_groupSpecifier = function(state) {
  22248. if (state.eat(0x3F /* ? */)) {
  22249. if (this.regexp_eatGroupName(state)) {
  22250. if (state.groupNames.indexOf(state.lastStringValue) !== -1) {
  22251. state.raise("Duplicate capture group name");
  22252. }
  22253. state.groupNames.push(state.lastStringValue);
  22254. return
  22255. }
  22256. state.raise("Invalid group");
  22257. }
  22258. };
  22259. // GroupName ::
  22260. // `<` RegExpIdentifierName `>`
  22261. // Note: this updates `state.lastStringValue` property with the eaten name.
  22262. pp$1.regexp_eatGroupName = function(state) {
  22263. state.lastStringValue = "";
  22264. if (state.eat(0x3C /* < */)) {
  22265. if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) {
  22266. return true
  22267. }
  22268. state.raise("Invalid capture group name");
  22269. }
  22270. return false
  22271. };
  22272. // RegExpIdentifierName ::
  22273. // RegExpIdentifierStart
  22274. // RegExpIdentifierName RegExpIdentifierPart
  22275. // Note: this updates `state.lastStringValue` property with the eaten name.
  22276. pp$1.regexp_eatRegExpIdentifierName = function(state) {
  22277. state.lastStringValue = "";
  22278. if (this.regexp_eatRegExpIdentifierStart(state)) {
  22279. state.lastStringValue += codePointToString(state.lastIntValue);
  22280. while (this.regexp_eatRegExpIdentifierPart(state)) {
  22281. state.lastStringValue += codePointToString(state.lastIntValue);
  22282. }
  22283. return true
  22284. }
  22285. return false
  22286. };
  22287. // RegExpIdentifierStart ::
  22288. // UnicodeIDStart
  22289. // `$`
  22290. // `_`
  22291. // `\` RegExpUnicodeEscapeSequence[+U]
  22292. pp$1.regexp_eatRegExpIdentifierStart = function(state) {
  22293. var start = state.pos;
  22294. var forceU = this.options.ecmaVersion >= 11;
  22295. var ch = state.current(forceU);
  22296. state.advance(forceU);
  22297. if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
  22298. ch = state.lastIntValue;
  22299. }
  22300. if (isRegExpIdentifierStart(ch)) {
  22301. state.lastIntValue = ch;
  22302. return true
  22303. }
  22304. state.pos = start;
  22305. return false
  22306. };
  22307. function isRegExpIdentifierStart(ch) {
  22308. return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */
  22309. }
  22310. // RegExpIdentifierPart ::
  22311. // UnicodeIDContinue
  22312. // `$`
  22313. // `_`
  22314. // `\` RegExpUnicodeEscapeSequence[+U]
  22315. // <ZWNJ>
  22316. // <ZWJ>
  22317. pp$1.regexp_eatRegExpIdentifierPart = function(state) {
  22318. var start = state.pos;
  22319. var forceU = this.options.ecmaVersion >= 11;
  22320. var ch = state.current(forceU);
  22321. state.advance(forceU);
  22322. if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
  22323. ch = state.lastIntValue;
  22324. }
  22325. if (isRegExpIdentifierPart(ch)) {
  22326. state.lastIntValue = ch;
  22327. return true
  22328. }
  22329. state.pos = start;
  22330. return false
  22331. };
  22332. function isRegExpIdentifierPart(ch) {
  22333. return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* <ZWNJ> */ || ch === 0x200D /* <ZWJ> */
  22334. }
  22335. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape
  22336. pp$1.regexp_eatAtomEscape = function(state) {
  22337. if (
  22338. this.regexp_eatBackReference(state) ||
  22339. this.regexp_eatCharacterClassEscape(state) ||
  22340. this.regexp_eatCharacterEscape(state) ||
  22341. (state.switchN && this.regexp_eatKGroupName(state))
  22342. ) {
  22343. return true
  22344. }
  22345. if (state.switchU) {
  22346. // Make the same message as V8.
  22347. if (state.current() === 0x63 /* c */) {
  22348. state.raise("Invalid unicode escape");
  22349. }
  22350. state.raise("Invalid escape");
  22351. }
  22352. return false
  22353. };
  22354. pp$1.regexp_eatBackReference = function(state) {
  22355. var start = state.pos;
  22356. if (this.regexp_eatDecimalEscape(state)) {
  22357. var n = state.lastIntValue;
  22358. if (state.switchU) {
  22359. // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape
  22360. if (n > state.maxBackReference) {
  22361. state.maxBackReference = n;
  22362. }
  22363. return true
  22364. }
  22365. if (n <= state.numCapturingParens) {
  22366. return true
  22367. }
  22368. state.pos = start;
  22369. }
  22370. return false
  22371. };
  22372. pp$1.regexp_eatKGroupName = function(state) {
  22373. if (state.eat(0x6B /* k */)) {
  22374. if (this.regexp_eatGroupName(state)) {
  22375. state.backReferenceNames.push(state.lastStringValue);
  22376. return true
  22377. }
  22378. state.raise("Invalid named reference");
  22379. }
  22380. return false
  22381. };
  22382. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape
  22383. pp$1.regexp_eatCharacterEscape = function(state) {
  22384. return (
  22385. this.regexp_eatControlEscape(state) ||
  22386. this.regexp_eatCControlLetter(state) ||
  22387. this.regexp_eatZero(state) ||
  22388. this.regexp_eatHexEscapeSequence(state) ||
  22389. this.regexp_eatRegExpUnicodeEscapeSequence(state, false) ||
  22390. (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) ||
  22391. this.regexp_eatIdentityEscape(state)
  22392. )
  22393. };
  22394. pp$1.regexp_eatCControlLetter = function(state) {
  22395. var start = state.pos;
  22396. if (state.eat(0x63 /* c */)) {
  22397. if (this.regexp_eatControlLetter(state)) {
  22398. return true
  22399. }
  22400. state.pos = start;
  22401. }
  22402. return false
  22403. };
  22404. pp$1.regexp_eatZero = function(state) {
  22405. if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) {
  22406. state.lastIntValue = 0;
  22407. state.advance();
  22408. return true
  22409. }
  22410. return false
  22411. };
  22412. // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape
  22413. pp$1.regexp_eatControlEscape = function(state) {
  22414. var ch = state.current();
  22415. if (ch === 0x74 /* t */) {
  22416. state.lastIntValue = 0x09; /* \t */
  22417. state.advance();
  22418. return true
  22419. }
  22420. if (ch === 0x6E /* n */) {
  22421. state.lastIntValue = 0x0A; /* \n */
  22422. state.advance();
  22423. return true
  22424. }
  22425. if (ch === 0x76 /* v */) {
  22426. state.lastIntValue = 0x0B; /* \v */
  22427. state.advance();
  22428. return true
  22429. }
  22430. if (ch === 0x66 /* f */) {
  22431. state.lastIntValue = 0x0C; /* \f */
  22432. state.advance();
  22433. return true
  22434. }
  22435. if (ch === 0x72 /* r */) {
  22436. state.lastIntValue = 0x0D; /* \r */
  22437. state.advance();
  22438. return true
  22439. }
  22440. return false
  22441. };
  22442. // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter
  22443. pp$1.regexp_eatControlLetter = function(state) {
  22444. var ch = state.current();
  22445. if (isControlLetter(ch)) {
  22446. state.lastIntValue = ch % 0x20;
  22447. state.advance();
  22448. return true
  22449. }
  22450. return false
  22451. };
  22452. function isControlLetter(ch) {
  22453. return (
  22454. (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) ||
  22455. (ch >= 0x61 /* a */ && ch <= 0x7A /* z */)
  22456. )
  22457. }
  22458. // https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence
  22459. pp$1.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) {
  22460. if ( forceU === void 0 ) forceU = false;
  22461. var start = state.pos;
  22462. var switchU = forceU || state.switchU;
  22463. if (state.eat(0x75 /* u */)) {
  22464. if (this.regexp_eatFixedHexDigits(state, 4)) {
  22465. var lead = state.lastIntValue;
  22466. if (switchU && lead >= 0xD800 && lead <= 0xDBFF) {
  22467. var leadSurrogateEnd = state.pos;
  22468. if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) {
  22469. var trail = state.lastIntValue;
  22470. if (trail >= 0xDC00 && trail <= 0xDFFF) {
  22471. state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
  22472. return true
  22473. }
  22474. }
  22475. state.pos = leadSurrogateEnd;
  22476. state.lastIntValue = lead;
  22477. }
  22478. return true
  22479. }
  22480. if (
  22481. switchU &&
  22482. state.eat(0x7B /* { */) &&
  22483. this.regexp_eatHexDigits(state) &&
  22484. state.eat(0x7D /* } */) &&
  22485. isValidUnicode(state.lastIntValue)
  22486. ) {
  22487. return true
  22488. }
  22489. if (switchU) {
  22490. state.raise("Invalid unicode escape");
  22491. }
  22492. state.pos = start;
  22493. }
  22494. return false
  22495. };
  22496. function isValidUnicode(ch) {
  22497. return ch >= 0 && ch <= 0x10FFFF
  22498. }
  22499. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape
  22500. pp$1.regexp_eatIdentityEscape = function(state) {
  22501. if (state.switchU) {
  22502. if (this.regexp_eatSyntaxCharacter(state)) {
  22503. return true
  22504. }
  22505. if (state.eat(0x2F /* / */)) {
  22506. state.lastIntValue = 0x2F; /* / */
  22507. return true
  22508. }
  22509. return false
  22510. }
  22511. var ch = state.current();
  22512. if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) {
  22513. state.lastIntValue = ch;
  22514. state.advance();
  22515. return true
  22516. }
  22517. return false
  22518. };
  22519. // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape
  22520. pp$1.regexp_eatDecimalEscape = function(state) {
  22521. state.lastIntValue = 0;
  22522. var ch = state.current();
  22523. if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) {
  22524. do {
  22525. state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
  22526. state.advance();
  22527. } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */)
  22528. return true
  22529. }
  22530. return false
  22531. };
  22532. // Return values used by character set parsing methods, needed to
  22533. // forbid negation of sets that can match strings.
  22534. var CharSetNone = 0; // Nothing parsed
  22535. var CharSetOk = 1; // Construct parsed, cannot contain strings
  22536. var CharSetString = 2; // Construct parsed, can contain strings
  22537. // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape
  22538. pp$1.regexp_eatCharacterClassEscape = function(state) {
  22539. var ch = state.current();
  22540. if (isCharacterClassEscape(ch)) {
  22541. state.lastIntValue = -1;
  22542. state.advance();
  22543. return CharSetOk
  22544. }
  22545. var negate = false;
  22546. if (
  22547. state.switchU &&
  22548. this.options.ecmaVersion >= 9 &&
  22549. ((negate = ch === 0x50 /* P */) || ch === 0x70 /* p */)
  22550. ) {
  22551. state.lastIntValue = -1;
  22552. state.advance();
  22553. var result;
  22554. if (
  22555. state.eat(0x7B /* { */) &&
  22556. (result = this.regexp_eatUnicodePropertyValueExpression(state)) &&
  22557. state.eat(0x7D /* } */)
  22558. ) {
  22559. if (negate && result === CharSetString) { state.raise("Invalid property name"); }
  22560. return result
  22561. }
  22562. state.raise("Invalid property name");
  22563. }
  22564. return CharSetNone
  22565. };
  22566. function isCharacterClassEscape(ch) {
  22567. return (
  22568. ch === 0x64 /* d */ ||
  22569. ch === 0x44 /* D */ ||
  22570. ch === 0x73 /* s */ ||
  22571. ch === 0x53 /* S */ ||
  22572. ch === 0x77 /* w */ ||
  22573. ch === 0x57 /* W */
  22574. )
  22575. }
  22576. // UnicodePropertyValueExpression ::
  22577. // UnicodePropertyName `=` UnicodePropertyValue
  22578. // LoneUnicodePropertyNameOrValue
  22579. pp$1.regexp_eatUnicodePropertyValueExpression = function(state) {
  22580. var start = state.pos;
  22581. // UnicodePropertyName `=` UnicodePropertyValue
  22582. if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) {
  22583. var name = state.lastStringValue;
  22584. if (this.regexp_eatUnicodePropertyValue(state)) {
  22585. var value = state.lastStringValue;
  22586. this.regexp_validateUnicodePropertyNameAndValue(state, name, value);
  22587. return CharSetOk
  22588. }
  22589. }
  22590. state.pos = start;
  22591. // LoneUnicodePropertyNameOrValue
  22592. if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {
  22593. var nameOrValue = state.lastStringValue;
  22594. return this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue)
  22595. }
  22596. return CharSetNone
  22597. };
  22598. pp$1.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {
  22599. if (!hasOwn(state.unicodeProperties.nonBinary, name))
  22600. { state.raise("Invalid property name"); }
  22601. if (!state.unicodeProperties.nonBinary[name].test(value))
  22602. { state.raise("Invalid property value"); }
  22603. };
  22604. pp$1.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) {
  22605. if (state.unicodeProperties.binary.test(nameOrValue)) { return CharSetOk }
  22606. if (state.switchV && state.unicodeProperties.binaryOfStrings.test(nameOrValue)) { return CharSetString }
  22607. state.raise("Invalid property name");
  22608. };
  22609. // UnicodePropertyName ::
  22610. // UnicodePropertyNameCharacters
  22611. pp$1.regexp_eatUnicodePropertyName = function(state) {
  22612. var ch = 0;
  22613. state.lastStringValue = "";
  22614. while (isUnicodePropertyNameCharacter(ch = state.current())) {
  22615. state.lastStringValue += codePointToString(ch);
  22616. state.advance();
  22617. }
  22618. return state.lastStringValue !== ""
  22619. };
  22620. function isUnicodePropertyNameCharacter(ch) {
  22621. return isControlLetter(ch) || ch === 0x5F /* _ */
  22622. }
  22623. // UnicodePropertyValue ::
  22624. // UnicodePropertyValueCharacters
  22625. pp$1.regexp_eatUnicodePropertyValue = function(state) {
  22626. var ch = 0;
  22627. state.lastStringValue = "";
  22628. while (isUnicodePropertyValueCharacter(ch = state.current())) {
  22629. state.lastStringValue += codePointToString(ch);
  22630. state.advance();
  22631. }
  22632. return state.lastStringValue !== ""
  22633. };
  22634. function isUnicodePropertyValueCharacter(ch) {
  22635. return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch)
  22636. }
  22637. // LoneUnicodePropertyNameOrValue ::
  22638. // UnicodePropertyValueCharacters
  22639. pp$1.regexp_eatLoneUnicodePropertyNameOrValue = function(state) {
  22640. return this.regexp_eatUnicodePropertyValue(state)
  22641. };
  22642. // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass
  22643. pp$1.regexp_eatCharacterClass = function(state) {
  22644. if (state.eat(0x5B /* [ */)) {
  22645. var negate = state.eat(0x5E /* ^ */);
  22646. var result = this.regexp_classContents(state);
  22647. if (!state.eat(0x5D /* ] */))
  22648. { state.raise("Unterminated character class"); }
  22649. if (negate && result === CharSetString)
  22650. { state.raise("Negated character class may contain strings"); }
  22651. return true
  22652. }
  22653. return false
  22654. };
  22655. // https://tc39.es/ecma262/#prod-ClassContents
  22656. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges
  22657. pp$1.regexp_classContents = function(state) {
  22658. if (state.current() === 0x5D /* ] */) { return CharSetOk }
  22659. if (state.switchV) { return this.regexp_classSetExpression(state) }
  22660. this.regexp_nonEmptyClassRanges(state);
  22661. return CharSetOk
  22662. };
  22663. // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges
  22664. // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash
  22665. pp$1.regexp_nonEmptyClassRanges = function(state) {
  22666. while (this.regexp_eatClassAtom(state)) {
  22667. var left = state.lastIntValue;
  22668. if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) {
  22669. var right = state.lastIntValue;
  22670. if (state.switchU && (left === -1 || right === -1)) {
  22671. state.raise("Invalid character class");
  22672. }
  22673. if (left !== -1 && right !== -1 && left > right) {
  22674. state.raise("Range out of order in character class");
  22675. }
  22676. }
  22677. }
  22678. };
  22679. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom
  22680. // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash
  22681. pp$1.regexp_eatClassAtom = function(state) {
  22682. var start = state.pos;
  22683. if (state.eat(0x5C /* \ */)) {
  22684. if (this.regexp_eatClassEscape(state)) {
  22685. return true
  22686. }
  22687. if (state.switchU) {
  22688. // Make the same message as V8.
  22689. var ch$1 = state.current();
  22690. if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) {
  22691. state.raise("Invalid class escape");
  22692. }
  22693. state.raise("Invalid escape");
  22694. }
  22695. state.pos = start;
  22696. }
  22697. var ch = state.current();
  22698. if (ch !== 0x5D /* ] */) {
  22699. state.lastIntValue = ch;
  22700. state.advance();
  22701. return true
  22702. }
  22703. return false
  22704. };
  22705. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape
  22706. pp$1.regexp_eatClassEscape = function(state) {
  22707. var start = state.pos;
  22708. if (state.eat(0x62 /* b */)) {
  22709. state.lastIntValue = 0x08; /* <BS> */
  22710. return true
  22711. }
  22712. if (state.switchU && state.eat(0x2D /* - */)) {
  22713. state.lastIntValue = 0x2D; /* - */
  22714. return true
  22715. }
  22716. if (!state.switchU && state.eat(0x63 /* c */)) {
  22717. if (this.regexp_eatClassControlLetter(state)) {
  22718. return true
  22719. }
  22720. state.pos = start;
  22721. }
  22722. return (
  22723. this.regexp_eatCharacterClassEscape(state) ||
  22724. this.regexp_eatCharacterEscape(state)
  22725. )
  22726. };
  22727. // https://tc39.es/ecma262/#prod-ClassSetExpression
  22728. // https://tc39.es/ecma262/#prod-ClassUnion
  22729. // https://tc39.es/ecma262/#prod-ClassIntersection
  22730. // https://tc39.es/ecma262/#prod-ClassSubtraction
  22731. pp$1.regexp_classSetExpression = function(state) {
  22732. var result = CharSetOk, subResult;
  22733. if (this.regexp_eatClassSetRange(state)) ; else if (subResult = this.regexp_eatClassSetOperand(state)) {
  22734. if (subResult === CharSetString) { result = CharSetString; }
  22735. // https://tc39.es/ecma262/#prod-ClassIntersection
  22736. var start = state.pos;
  22737. while (state.eatChars([0x26, 0x26] /* && */)) {
  22738. if (
  22739. state.current() !== 0x26 /* & */ &&
  22740. (subResult = this.regexp_eatClassSetOperand(state))
  22741. ) {
  22742. if (subResult !== CharSetString) { result = CharSetOk; }
  22743. continue
  22744. }
  22745. state.raise("Invalid character in character class");
  22746. }
  22747. if (start !== state.pos) { return result }
  22748. // https://tc39.es/ecma262/#prod-ClassSubtraction
  22749. while (state.eatChars([0x2D, 0x2D] /* -- */)) {
  22750. if (this.regexp_eatClassSetOperand(state)) { continue }
  22751. state.raise("Invalid character in character class");
  22752. }
  22753. if (start !== state.pos) { return result }
  22754. } else {
  22755. state.raise("Invalid character in character class");
  22756. }
  22757. // https://tc39.es/ecma262/#prod-ClassUnion
  22758. for (;;) {
  22759. if (this.regexp_eatClassSetRange(state)) { continue }
  22760. subResult = this.regexp_eatClassSetOperand(state);
  22761. if (!subResult) { return result }
  22762. if (subResult === CharSetString) { result = CharSetString; }
  22763. }
  22764. };
  22765. // https://tc39.es/ecma262/#prod-ClassSetRange
  22766. pp$1.regexp_eatClassSetRange = function(state) {
  22767. var start = state.pos;
  22768. if (this.regexp_eatClassSetCharacter(state)) {
  22769. var left = state.lastIntValue;
  22770. if (state.eat(0x2D /* - */) && this.regexp_eatClassSetCharacter(state)) {
  22771. var right = state.lastIntValue;
  22772. if (left !== -1 && right !== -1 && left > right) {
  22773. state.raise("Range out of order in character class");
  22774. }
  22775. return true
  22776. }
  22777. state.pos = start;
  22778. }
  22779. return false
  22780. };
  22781. // https://tc39.es/ecma262/#prod-ClassSetOperand
  22782. pp$1.regexp_eatClassSetOperand = function(state) {
  22783. if (this.regexp_eatClassSetCharacter(state)) { return CharSetOk }
  22784. return this.regexp_eatClassStringDisjunction(state) || this.regexp_eatNestedClass(state)
  22785. };
  22786. // https://tc39.es/ecma262/#prod-NestedClass
  22787. pp$1.regexp_eatNestedClass = function(state) {
  22788. var start = state.pos;
  22789. if (state.eat(0x5B /* [ */)) {
  22790. var negate = state.eat(0x5E /* ^ */);
  22791. var result = this.regexp_classContents(state);
  22792. if (state.eat(0x5D /* ] */)) {
  22793. if (negate && result === CharSetString) {
  22794. state.raise("Negated character class may contain strings");
  22795. }
  22796. return result
  22797. }
  22798. state.pos = start;
  22799. }
  22800. if (state.eat(0x5C /* \ */)) {
  22801. var result$1 = this.regexp_eatCharacterClassEscape(state);
  22802. if (result$1) {
  22803. return result$1
  22804. }
  22805. state.pos = start;
  22806. }
  22807. return null
  22808. };
  22809. // https://tc39.es/ecma262/#prod-ClassStringDisjunction
  22810. pp$1.regexp_eatClassStringDisjunction = function(state) {
  22811. var start = state.pos;
  22812. if (state.eatChars([0x5C, 0x71] /* \q */)) {
  22813. if (state.eat(0x7B /* { */)) {
  22814. var result = this.regexp_classStringDisjunctionContents(state);
  22815. if (state.eat(0x7D /* } */)) {
  22816. return result
  22817. }
  22818. } else {
  22819. // Make the same message as V8.
  22820. state.raise("Invalid escape");
  22821. }
  22822. state.pos = start;
  22823. }
  22824. return null
  22825. };
  22826. // https://tc39.es/ecma262/#prod-ClassStringDisjunctionContents
  22827. pp$1.regexp_classStringDisjunctionContents = function(state) {
  22828. var result = this.regexp_classString(state);
  22829. while (state.eat(0x7C /* | */)) {
  22830. if (this.regexp_classString(state) === CharSetString) { result = CharSetString; }
  22831. }
  22832. return result
  22833. };
  22834. // https://tc39.es/ecma262/#prod-ClassString
  22835. // https://tc39.es/ecma262/#prod-NonEmptyClassString
  22836. pp$1.regexp_classString = function(state) {
  22837. var count = 0;
  22838. while (this.regexp_eatClassSetCharacter(state)) { count++; }
  22839. return count === 1 ? CharSetOk : CharSetString
  22840. };
  22841. // https://tc39.es/ecma262/#prod-ClassSetCharacter
  22842. pp$1.regexp_eatClassSetCharacter = function(state) {
  22843. var start = state.pos;
  22844. if (state.eat(0x5C /* \ */)) {
  22845. if (
  22846. this.regexp_eatCharacterEscape(state) ||
  22847. this.regexp_eatClassSetReservedPunctuator(state)
  22848. ) {
  22849. return true
  22850. }
  22851. if (state.eat(0x62 /* b */)) {
  22852. state.lastIntValue = 0x08; /* <BS> */
  22853. return true
  22854. }
  22855. state.pos = start;
  22856. return false
  22857. }
  22858. var ch = state.current();
  22859. if (ch < 0 || ch === state.lookahead() && isClassSetReservedDoublePunctuatorCharacter(ch)) { return false }
  22860. if (isClassSetSyntaxCharacter(ch)) { return false }
  22861. state.advance();
  22862. state.lastIntValue = ch;
  22863. return true
  22864. };
  22865. // https://tc39.es/ecma262/#prod-ClassSetReservedDoublePunctuator
  22866. function isClassSetReservedDoublePunctuatorCharacter(ch) {
  22867. return (
  22868. ch === 0x21 /* ! */ ||
  22869. ch >= 0x23 /* # */ && ch <= 0x26 /* & */ ||
  22870. ch >= 0x2A /* * */ && ch <= 0x2C /* , */ ||
  22871. ch === 0x2E /* . */ ||
  22872. ch >= 0x3A /* : */ && ch <= 0x40 /* @ */ ||
  22873. ch === 0x5E /* ^ */ ||
  22874. ch === 0x60 /* ` */ ||
  22875. ch === 0x7E /* ~ */
  22876. )
  22877. }
  22878. // https://tc39.es/ecma262/#prod-ClassSetSyntaxCharacter
  22879. function isClassSetSyntaxCharacter(ch) {
  22880. return (
  22881. ch === 0x28 /* ( */ ||
  22882. ch === 0x29 /* ) */ ||
  22883. ch === 0x2D /* - */ ||
  22884. ch === 0x2F /* / */ ||
  22885. ch >= 0x5B /* [ */ && ch <= 0x5D /* ] */ ||
  22886. ch >= 0x7B /* { */ && ch <= 0x7D /* } */
  22887. )
  22888. }
  22889. // https://tc39.es/ecma262/#prod-ClassSetReservedPunctuator
  22890. pp$1.regexp_eatClassSetReservedPunctuator = function(state) {
  22891. var ch = state.current();
  22892. if (isClassSetReservedPunctuator(ch)) {
  22893. state.lastIntValue = ch;
  22894. state.advance();
  22895. return true
  22896. }
  22897. return false
  22898. };
  22899. // https://tc39.es/ecma262/#prod-ClassSetReservedPunctuator
  22900. function isClassSetReservedPunctuator(ch) {
  22901. return (
  22902. ch === 0x21 /* ! */ ||
  22903. ch === 0x23 /* # */ ||
  22904. ch === 0x25 /* % */ ||
  22905. ch === 0x26 /* & */ ||
  22906. ch === 0x2C /* , */ ||
  22907. ch === 0x2D /* - */ ||
  22908. ch >= 0x3A /* : */ && ch <= 0x3E /* > */ ||
  22909. ch === 0x40 /* @ */ ||
  22910. ch === 0x60 /* ` */ ||
  22911. ch === 0x7E /* ~ */
  22912. )
  22913. }
  22914. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter
  22915. pp$1.regexp_eatClassControlLetter = function(state) {
  22916. var ch = state.current();
  22917. if (isDecimalDigit(ch) || ch === 0x5F /* _ */) {
  22918. state.lastIntValue = ch % 0x20;
  22919. state.advance();
  22920. return true
  22921. }
  22922. return false
  22923. };
  22924. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
  22925. pp$1.regexp_eatHexEscapeSequence = function(state) {
  22926. var start = state.pos;
  22927. if (state.eat(0x78 /* x */)) {
  22928. if (this.regexp_eatFixedHexDigits(state, 2)) {
  22929. return true
  22930. }
  22931. if (state.switchU) {
  22932. state.raise("Invalid escape");
  22933. }
  22934. state.pos = start;
  22935. }
  22936. return false
  22937. };
  22938. // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits
  22939. pp$1.regexp_eatDecimalDigits = function(state) {
  22940. var start = state.pos;
  22941. var ch = 0;
  22942. state.lastIntValue = 0;
  22943. while (isDecimalDigit(ch = state.current())) {
  22944. state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
  22945. state.advance();
  22946. }
  22947. return state.pos !== start
  22948. };
  22949. function isDecimalDigit(ch) {
  22950. return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */
  22951. }
  22952. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits
  22953. pp$1.regexp_eatHexDigits = function(state) {
  22954. var start = state.pos;
  22955. var ch = 0;
  22956. state.lastIntValue = 0;
  22957. while (isHexDigit(ch = state.current())) {
  22958. state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
  22959. state.advance();
  22960. }
  22961. return state.pos !== start
  22962. };
  22963. function isHexDigit(ch) {
  22964. return (
  22965. (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) ||
  22966. (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) ||
  22967. (ch >= 0x61 /* a */ && ch <= 0x66 /* f */)
  22968. )
  22969. }
  22970. function hexToInt(ch) {
  22971. if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) {
  22972. return 10 + (ch - 0x41 /* A */)
  22973. }
  22974. if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) {
  22975. return 10 + (ch - 0x61 /* a */)
  22976. }
  22977. return ch - 0x30 /* 0 */
  22978. }
  22979. // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence
  22980. // Allows only 0-377(octal) i.e. 0-255(decimal).
  22981. pp$1.regexp_eatLegacyOctalEscapeSequence = function(state) {
  22982. if (this.regexp_eatOctalDigit(state)) {
  22983. var n1 = state.lastIntValue;
  22984. if (this.regexp_eatOctalDigit(state)) {
  22985. var n2 = state.lastIntValue;
  22986. if (n1 <= 3 && this.regexp_eatOctalDigit(state)) {
  22987. state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue;
  22988. } else {
  22989. state.lastIntValue = n1 * 8 + n2;
  22990. }
  22991. } else {
  22992. state.lastIntValue = n1;
  22993. }
  22994. return true
  22995. }
  22996. return false
  22997. };
  22998. // https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit
  22999. pp$1.regexp_eatOctalDigit = function(state) {
  23000. var ch = state.current();
  23001. if (isOctalDigit(ch)) {
  23002. state.lastIntValue = ch - 0x30; /* 0 */
  23003. state.advance();
  23004. return true
  23005. }
  23006. state.lastIntValue = 0;
  23007. return false
  23008. };
  23009. function isOctalDigit(ch) {
  23010. return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */
  23011. }
  23012. // https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits
  23013. // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit
  23014. // And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
  23015. pp$1.regexp_eatFixedHexDigits = function(state, length) {
  23016. var start = state.pos;
  23017. state.lastIntValue = 0;
  23018. for (var i = 0; i < length; ++i) {
  23019. var ch = state.current();
  23020. if (!isHexDigit(ch)) {
  23021. state.pos = start;
  23022. return false
  23023. }
  23024. state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
  23025. state.advance();
  23026. }
  23027. return true
  23028. };
  23029. // Object type used to represent tokens. Note that normally, tokens
  23030. // simply exist as properties on the parser object. This is only
  23031. // used for the onToken callback and the external tokenizer.
  23032. var Token = function Token(p) {
  23033. this.type = p.type;
  23034. this.value = p.value;
  23035. this.start = p.start;
  23036. this.end = p.end;
  23037. if (p.options.locations)
  23038. { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); }
  23039. if (p.options.ranges)
  23040. { this.range = [p.start, p.end]; }
  23041. };
  23042. // ## Tokenizer
  23043. var pp = Parser.prototype;
  23044. // Move to the next token
  23045. pp.next = function(ignoreEscapeSequenceInKeyword) {
  23046. if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc)
  23047. { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); }
  23048. if (this.options.onToken)
  23049. { this.options.onToken(new Token(this)); }
  23050. this.lastTokEnd = this.end;
  23051. this.lastTokStart = this.start;
  23052. this.lastTokEndLoc = this.endLoc;
  23053. this.lastTokStartLoc = this.startLoc;
  23054. this.nextToken();
  23055. };
  23056. pp.getToken = function() {
  23057. this.next();
  23058. return new Token(this)
  23059. };
  23060. // If we're in an ES6 environment, make parsers iterable
  23061. if (typeof Symbol !== "undefined")
  23062. { pp[Symbol.iterator] = function() {
  23063. var this$1$1 = this;
  23064. return {
  23065. next: function () {
  23066. var token = this$1$1.getToken();
  23067. return {
  23068. done: token.type === types$1.eof,
  23069. value: token
  23070. }
  23071. }
  23072. }
  23073. }; }
  23074. // Toggle strict mode. Re-reads the next number or string to please
  23075. // pedantic tests (`"use strict"; 010;` should fail).
  23076. // Read a single token, updating the parser object's token-related
  23077. // properties.
  23078. pp.nextToken = function() {
  23079. var curContext = this.curContext();
  23080. if (!curContext || !curContext.preserveSpace) { this.skipSpace(); }
  23081. this.start = this.pos;
  23082. if (this.options.locations) { this.startLoc = this.curPosition(); }
  23083. if (this.pos >= this.input.length) { return this.finishToken(types$1.eof) }
  23084. if (curContext.override) { return curContext.override(this) }
  23085. else { this.readToken(this.fullCharCodeAtPos()); }
  23086. };
  23087. pp.readToken = function(code) {
  23088. // Identifier or keyword. '\uXXXX' sequences are allowed in
  23089. // identifiers, so '\' also dispatches to that.
  23090. if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)
  23091. { return this.readWord() }
  23092. return this.getTokenFromCode(code)
  23093. };
  23094. pp.fullCharCodeAtPos = function() {
  23095. var code = this.input.charCodeAt(this.pos);
  23096. if (code <= 0xd7ff || code >= 0xdc00) { return code }
  23097. var next = this.input.charCodeAt(this.pos + 1);
  23098. return next <= 0xdbff || next >= 0xe000 ? code : (code << 10) + next - 0x35fdc00
  23099. };
  23100. pp.skipBlockComment = function() {
  23101. var startLoc = this.options.onComment && this.curPosition();
  23102. var start = this.pos, end = this.input.indexOf("*/", this.pos += 2);
  23103. if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); }
  23104. this.pos = end + 2;
  23105. if (this.options.locations) {
  23106. for (var nextBreak = (void 0), pos = start; (nextBreak = nextLineBreak(this.input, pos, this.pos)) > -1;) {
  23107. ++this.curLine;
  23108. pos = this.lineStart = nextBreak;
  23109. }
  23110. }
  23111. if (this.options.onComment)
  23112. { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,
  23113. startLoc, this.curPosition()); }
  23114. };
  23115. pp.skipLineComment = function(startSkip) {
  23116. var start = this.pos;
  23117. var startLoc = this.options.onComment && this.curPosition();
  23118. var ch = this.input.charCodeAt(this.pos += startSkip);
  23119. while (this.pos < this.input.length && !isNewLine(ch)) {
  23120. ch = this.input.charCodeAt(++this.pos);
  23121. }
  23122. if (this.options.onComment)
  23123. { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos,
  23124. startLoc, this.curPosition()); }
  23125. };
  23126. // Called at the start of the parse and after every token. Skips
  23127. // whitespace and comments, and.
  23128. pp.skipSpace = function() {
  23129. loop: while (this.pos < this.input.length) {
  23130. var ch = this.input.charCodeAt(this.pos);
  23131. switch (ch) {
  23132. case 32: case 160: // ' '
  23133. ++this.pos;
  23134. break
  23135. case 13:
  23136. if (this.input.charCodeAt(this.pos + 1) === 10) {
  23137. ++this.pos;
  23138. }
  23139. case 10: case 8232: case 8233:
  23140. ++this.pos;
  23141. if (this.options.locations) {
  23142. ++this.curLine;
  23143. this.lineStart = this.pos;
  23144. }
  23145. break
  23146. case 47: // '/'
  23147. switch (this.input.charCodeAt(this.pos + 1)) {
  23148. case 42: // '*'
  23149. this.skipBlockComment();
  23150. break
  23151. case 47:
  23152. this.skipLineComment(2);
  23153. break
  23154. default:
  23155. break loop
  23156. }
  23157. break
  23158. default:
  23159. if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
  23160. ++this.pos;
  23161. } else {
  23162. break loop
  23163. }
  23164. }
  23165. }
  23166. };
  23167. // Called at the end of every token. Sets `end`, `val`, and
  23168. // maintains `context` and `exprAllowed`, and skips the space after
  23169. // the token, so that the next one's `start` will point at the
  23170. // right position.
  23171. pp.finishToken = function(type, val) {
  23172. this.end = this.pos;
  23173. if (this.options.locations) { this.endLoc = this.curPosition(); }
  23174. var prevType = this.type;
  23175. this.type = type;
  23176. this.value = val;
  23177. this.updateContext(prevType);
  23178. };
  23179. // ### Token reading
  23180. // This is the function that is called to fetch the next token. It
  23181. // is somewhat obscure, because it works in character codes rather
  23182. // than characters, and because operator parsing has been inlined
  23183. // into it.
  23184. //
  23185. // All in the name of speed.
  23186. //
  23187. pp.readToken_dot = function() {
  23188. var next = this.input.charCodeAt(this.pos + 1);
  23189. if (next >= 48 && next <= 57) { return this.readNumber(true) }
  23190. var next2 = this.input.charCodeAt(this.pos + 2);
  23191. if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'
  23192. this.pos += 3;
  23193. return this.finishToken(types$1.ellipsis)
  23194. } else {
  23195. ++this.pos;
  23196. return this.finishToken(types$1.dot)
  23197. }
  23198. };
  23199. pp.readToken_slash = function() { // '/'
  23200. var next = this.input.charCodeAt(this.pos + 1);
  23201. if (this.exprAllowed) { ++this.pos; return this.readRegexp() }
  23202. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  23203. return this.finishOp(types$1.slash, 1)
  23204. };
  23205. pp.readToken_mult_modulo_exp = function(code) { // '%*'
  23206. var next = this.input.charCodeAt(this.pos + 1);
  23207. var size = 1;
  23208. var tokentype = code === 42 ? types$1.star : types$1.modulo;
  23209. // exponentiation operator ** and **=
  23210. if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) {
  23211. ++size;
  23212. tokentype = types$1.starstar;
  23213. next = this.input.charCodeAt(this.pos + 2);
  23214. }
  23215. if (next === 61) { return this.finishOp(types$1.assign, size + 1) }
  23216. return this.finishOp(tokentype, size)
  23217. };
  23218. pp.readToken_pipe_amp = function(code) { // '|&'
  23219. var next = this.input.charCodeAt(this.pos + 1);
  23220. if (next === code) {
  23221. if (this.options.ecmaVersion >= 12) {
  23222. var next2 = this.input.charCodeAt(this.pos + 2);
  23223. if (next2 === 61) { return this.finishOp(types$1.assign, 3) }
  23224. }
  23225. return this.finishOp(code === 124 ? types$1.logicalOR : types$1.logicalAND, 2)
  23226. }
  23227. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  23228. return this.finishOp(code === 124 ? types$1.bitwiseOR : types$1.bitwiseAND, 1)
  23229. };
  23230. pp.readToken_caret = function() { // '^'
  23231. var next = this.input.charCodeAt(this.pos + 1);
  23232. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  23233. return this.finishOp(types$1.bitwiseXOR, 1)
  23234. };
  23235. pp.readToken_plus_min = function(code) { // '+-'
  23236. var next = this.input.charCodeAt(this.pos + 1);
  23237. if (next === code) {
  23238. if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 &&
  23239. (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {
  23240. // A `-->` line comment
  23241. this.skipLineComment(3);
  23242. this.skipSpace();
  23243. return this.nextToken()
  23244. }
  23245. return this.finishOp(types$1.incDec, 2)
  23246. }
  23247. if (next === 61) { return this.finishOp(types$1.assign, 2) }
  23248. return this.finishOp(types$1.plusMin, 1)
  23249. };
  23250. pp.readToken_lt_gt = function(code) { // '<>'
  23251. var next = this.input.charCodeAt(this.pos + 1);
  23252. var size = 1;
  23253. if (next === code) {
  23254. size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
  23255. if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types$1.assign, size + 1) }
  23256. return this.finishOp(types$1.bitShift, size)
  23257. }
  23258. if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 &&
  23259. this.input.charCodeAt(this.pos + 3) === 45) {
  23260. // `<!--`, an XML-style comment that should be interpreted as a line comment
  23261. this.skipLineComment(4);
  23262. this.skipSpace();
  23263. return this.nextToken()
  23264. }
  23265. if (next === 61) { size = 2; }
  23266. return this.finishOp(types$1.relational, size)
  23267. };
  23268. pp.readToken_eq_excl = function(code) { // '=!'
  23269. var next = this.input.charCodeAt(this.pos + 1);
  23270. if (next === 61) { return this.finishOp(types$1.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2) }
  23271. if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { // '=>'
  23272. this.pos += 2;
  23273. return this.finishToken(types$1.arrow)
  23274. }
  23275. return this.finishOp(code === 61 ? types$1.eq : types$1.prefix, 1)
  23276. };
  23277. pp.readToken_question = function() { // '?'
  23278. var ecmaVersion = this.options.ecmaVersion;
  23279. if (ecmaVersion >= 11) {
  23280. var next = this.input.charCodeAt(this.pos + 1);
  23281. if (next === 46) {
  23282. var next2 = this.input.charCodeAt(this.pos + 2);
  23283. if (next2 < 48 || next2 > 57) { return this.finishOp(types$1.questionDot, 2) }
  23284. }
  23285. if (next === 63) {
  23286. if (ecmaVersion >= 12) {
  23287. var next2$1 = this.input.charCodeAt(this.pos + 2);
  23288. if (next2$1 === 61) { return this.finishOp(types$1.assign, 3) }
  23289. }
  23290. return this.finishOp(types$1.coalesce, 2)
  23291. }
  23292. }
  23293. return this.finishOp(types$1.question, 1)
  23294. };
  23295. pp.readToken_numberSign = function() { // '#'
  23296. var ecmaVersion = this.options.ecmaVersion;
  23297. var code = 35; // '#'
  23298. if (ecmaVersion >= 13) {
  23299. ++this.pos;
  23300. code = this.fullCharCodeAtPos();
  23301. if (isIdentifierStart(code, true) || code === 92 /* '\' */) {
  23302. return this.finishToken(types$1.privateId, this.readWord1())
  23303. }
  23304. }
  23305. this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
  23306. };
  23307. pp.getTokenFromCode = function(code) {
  23308. switch (code) {
  23309. // The interpretation of a dot depends on whether it is followed
  23310. // by a digit or another two dots.
  23311. case 46: // '.'
  23312. return this.readToken_dot()
  23313. // Punctuation tokens.
  23314. case 40: ++this.pos; return this.finishToken(types$1.parenL)
  23315. case 41: ++this.pos; return this.finishToken(types$1.parenR)
  23316. case 59: ++this.pos; return this.finishToken(types$1.semi)
  23317. case 44: ++this.pos; return this.finishToken(types$1.comma)
  23318. case 91: ++this.pos; return this.finishToken(types$1.bracketL)
  23319. case 93: ++this.pos; return this.finishToken(types$1.bracketR)
  23320. case 123: ++this.pos; return this.finishToken(types$1.braceL)
  23321. case 125: ++this.pos; return this.finishToken(types$1.braceR)
  23322. case 58: ++this.pos; return this.finishToken(types$1.colon)
  23323. case 96: // '`'
  23324. if (this.options.ecmaVersion < 6) { break }
  23325. ++this.pos;
  23326. return this.finishToken(types$1.backQuote)
  23327. case 48: // '0'
  23328. var next = this.input.charCodeAt(this.pos + 1);
  23329. if (next === 120 || next === 88) { return this.readRadixNumber(16) } // '0x', '0X' - hex number
  23330. if (this.options.ecmaVersion >= 6) {
  23331. if (next === 111 || next === 79) { return this.readRadixNumber(8) } // '0o', '0O' - octal number
  23332. if (next === 98 || next === 66) { return this.readRadixNumber(2) } // '0b', '0B' - binary number
  23333. }
  23334. // Anything else beginning with a digit is an integer, octal
  23335. // number, or float.
  23336. case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9
  23337. return this.readNumber(false)
  23338. // Quotes produce strings.
  23339. case 34: case 39: // '"', "'"
  23340. return this.readString(code)
  23341. // Operators are parsed inline in tiny state machines. '=' (61) is
  23342. // often referred to. `finishOp` simply skips the amount of
  23343. // characters it is given as second argument, and returns a token
  23344. // of the type given by its first argument.
  23345. case 47: // '/'
  23346. return this.readToken_slash()
  23347. case 37: case 42: // '%*'
  23348. return this.readToken_mult_modulo_exp(code)
  23349. case 124: case 38: // '|&'
  23350. return this.readToken_pipe_amp(code)
  23351. case 94: // '^'
  23352. return this.readToken_caret()
  23353. case 43: case 45: // '+-'
  23354. return this.readToken_plus_min(code)
  23355. case 60: case 62: // '<>'
  23356. return this.readToken_lt_gt(code)
  23357. case 61: case 33: // '=!'
  23358. return this.readToken_eq_excl(code)
  23359. case 63: // '?'
  23360. return this.readToken_question()
  23361. case 126: // '~'
  23362. return this.finishOp(types$1.prefix, 1)
  23363. case 35: // '#'
  23364. return this.readToken_numberSign()
  23365. }
  23366. this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
  23367. };
  23368. pp.finishOp = function(type, size) {
  23369. var str = this.input.slice(this.pos, this.pos + size);
  23370. this.pos += size;
  23371. return this.finishToken(type, str)
  23372. };
  23373. pp.readRegexp = function() {
  23374. var escaped, inClass, start = this.pos;
  23375. for (;;) {
  23376. if (this.pos >= this.input.length) { this.raise(start, "Unterminated regular expression"); }
  23377. var ch = this.input.charAt(this.pos);
  23378. if (lineBreak.test(ch)) { this.raise(start, "Unterminated regular expression"); }
  23379. if (!escaped) {
  23380. if (ch === "[") { inClass = true; }
  23381. else if (ch === "]" && inClass) { inClass = false; }
  23382. else if (ch === "/" && !inClass) { break }
  23383. escaped = ch === "\\";
  23384. } else { escaped = false; }
  23385. ++this.pos;
  23386. }
  23387. var pattern = this.input.slice(start, this.pos);
  23388. ++this.pos;
  23389. var flagsStart = this.pos;
  23390. var flags = this.readWord1();
  23391. if (this.containsEsc) { this.unexpected(flagsStart); }
  23392. // Validate pattern
  23393. var state = this.regexpState || (this.regexpState = new RegExpValidationState(this));
  23394. state.reset(start, pattern, flags);
  23395. this.validateRegExpFlags(state);
  23396. this.validateRegExpPattern(state);
  23397. // Create Literal#value property value.
  23398. var value = null;
  23399. try {
  23400. value = new RegExp(pattern, flags);
  23401. } catch (e) {
  23402. // ESTree requires null if it failed to instantiate RegExp object.
  23403. // https://github.com/estree/estree/blob/a27003adf4fd7bfad44de9cef372a2eacd527b1c/es5.md#regexpliteral
  23404. }
  23405. return this.finishToken(types$1.regexp, {pattern: pattern, flags: flags, value: value})
  23406. };
  23407. // Read an integer in the given radix. Return null if zero digits
  23408. // were read, the integer value otherwise. When `len` is given, this
  23409. // will return `null` unless the integer has exactly `len` digits.
  23410. pp.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) {
  23411. // `len` is used for character escape sequences. In that case, disallow separators.
  23412. var allowSeparators = this.options.ecmaVersion >= 12 && len === undefined;
  23413. // `maybeLegacyOctalNumericLiteral` is true if it doesn't have prefix (0x,0o,0b)
  23414. // and isn't fraction part nor exponent part. In that case, if the first digit
  23415. // is zero then disallow separators.
  23416. var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48;
  23417. var start = this.pos, total = 0, lastCode = 0;
  23418. for (var i = 0, e = len == null ? Infinity : len; i < e; ++i, ++this.pos) {
  23419. var code = this.input.charCodeAt(this.pos), val = (void 0);
  23420. if (allowSeparators && code === 95) {
  23421. if (isLegacyOctalNumericLiteral) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals"); }
  23422. if (lastCode === 95) { this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore"); }
  23423. if (i === 0) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits"); }
  23424. lastCode = code;
  23425. continue
  23426. }
  23427. if (code >= 97) { val = code - 97 + 10; } // a
  23428. else if (code >= 65) { val = code - 65 + 10; } // A
  23429. else if (code >= 48 && code <= 57) { val = code - 48; } // 0-9
  23430. else { val = Infinity; }
  23431. if (val >= radix) { break }
  23432. lastCode = code;
  23433. total = total * radix + val;
  23434. }
  23435. if (allowSeparators && lastCode === 95) { this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits"); }
  23436. if (this.pos === start || len != null && this.pos - start !== len) { return null }
  23437. return total
  23438. };
  23439. function stringToNumber(str, isLegacyOctalNumericLiteral) {
  23440. if (isLegacyOctalNumericLiteral) {
  23441. return parseInt(str, 8)
  23442. }
  23443. // `parseFloat(value)` stops parsing at the first numeric separator then returns a wrong value.
  23444. return parseFloat(str.replace(/_/g, ""))
  23445. }
  23446. function stringToBigInt(str) {
  23447. if (typeof BigInt !== "function") {
  23448. return null
  23449. }
  23450. // `BigInt(value)` throws syntax error if the string contains numeric separators.
  23451. return BigInt(str.replace(/_/g, ""))
  23452. }
  23453. pp.readRadixNumber = function(radix) {
  23454. var start = this.pos;
  23455. this.pos += 2; // 0x
  23456. var val = this.readInt(radix);
  23457. if (val == null) { this.raise(this.start + 2, "Expected number in radix " + radix); }
  23458. if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
  23459. val = stringToBigInt(this.input.slice(start, this.pos));
  23460. ++this.pos;
  23461. } else if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  23462. return this.finishToken(types$1.num, val)
  23463. };
  23464. // Read an integer, octal integer, or floating-point number.
  23465. pp.readNumber = function(startsWithDot) {
  23466. var start = this.pos;
  23467. if (!startsWithDot && this.readInt(10, undefined, true) === null) { this.raise(start, "Invalid number"); }
  23468. var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;
  23469. if (octal && this.strict) { this.raise(start, "Invalid number"); }
  23470. var next = this.input.charCodeAt(this.pos);
  23471. if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {
  23472. var val$1 = stringToBigInt(this.input.slice(start, this.pos));
  23473. ++this.pos;
  23474. if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  23475. return this.finishToken(types$1.num, val$1)
  23476. }
  23477. if (octal && /[89]/.test(this.input.slice(start, this.pos))) { octal = false; }
  23478. if (next === 46 && !octal) { // '.'
  23479. ++this.pos;
  23480. this.readInt(10);
  23481. next = this.input.charCodeAt(this.pos);
  23482. }
  23483. if ((next === 69 || next === 101) && !octal) { // 'eE'
  23484. next = this.input.charCodeAt(++this.pos);
  23485. if (next === 43 || next === 45) { ++this.pos; } // '+-'
  23486. if (this.readInt(10) === null) { this.raise(start, "Invalid number"); }
  23487. }
  23488. if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
  23489. var val = stringToNumber(this.input.slice(start, this.pos), octal);
  23490. return this.finishToken(types$1.num, val)
  23491. };
  23492. // Read a string value, interpreting backslash-escapes.
  23493. pp.readCodePoint = function() {
  23494. var ch = this.input.charCodeAt(this.pos), code;
  23495. if (ch === 123) { // '{'
  23496. if (this.options.ecmaVersion < 6) { this.unexpected(); }
  23497. var codePos = ++this.pos;
  23498. code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
  23499. ++this.pos;
  23500. if (code > 0x10FFFF) { this.invalidStringToken(codePos, "Code point out of bounds"); }
  23501. } else {
  23502. code = this.readHexChar(4);
  23503. }
  23504. return code
  23505. };
  23506. pp.readString = function(quote) {
  23507. var out = "", chunkStart = ++this.pos;
  23508. for (;;) {
  23509. if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated string constant"); }
  23510. var ch = this.input.charCodeAt(this.pos);
  23511. if (ch === quote) { break }
  23512. if (ch === 92) { // '\'
  23513. out += this.input.slice(chunkStart, this.pos);
  23514. out += this.readEscapedChar(false);
  23515. chunkStart = this.pos;
  23516. } else if (ch === 0x2028 || ch === 0x2029) {
  23517. if (this.options.ecmaVersion < 10) { this.raise(this.start, "Unterminated string constant"); }
  23518. ++this.pos;
  23519. if (this.options.locations) {
  23520. this.curLine++;
  23521. this.lineStart = this.pos;
  23522. }
  23523. } else {
  23524. if (isNewLine(ch)) { this.raise(this.start, "Unterminated string constant"); }
  23525. ++this.pos;
  23526. }
  23527. }
  23528. out += this.input.slice(chunkStart, this.pos++);
  23529. return this.finishToken(types$1.string, out)
  23530. };
  23531. // Reads template string tokens.
  23532. var INVALID_TEMPLATE_ESCAPE_ERROR = {};
  23533. pp.tryReadTemplateToken = function() {
  23534. this.inTemplateElement = true;
  23535. try {
  23536. this.readTmplToken();
  23537. } catch (err) {
  23538. if (err === INVALID_TEMPLATE_ESCAPE_ERROR) {
  23539. this.readInvalidTemplateToken();
  23540. } else {
  23541. throw err
  23542. }
  23543. }
  23544. this.inTemplateElement = false;
  23545. };
  23546. pp.invalidStringToken = function(position, message) {
  23547. if (this.inTemplateElement && this.options.ecmaVersion >= 9) {
  23548. throw INVALID_TEMPLATE_ESCAPE_ERROR
  23549. } else {
  23550. this.raise(position, message);
  23551. }
  23552. };
  23553. pp.readTmplToken = function() {
  23554. var out = "", chunkStart = this.pos;
  23555. for (;;) {
  23556. if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated template"); }
  23557. var ch = this.input.charCodeAt(this.pos);
  23558. if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) { // '`', '${'
  23559. if (this.pos === this.start && (this.type === types$1.template || this.type === types$1.invalidTemplate)) {
  23560. if (ch === 36) {
  23561. this.pos += 2;
  23562. return this.finishToken(types$1.dollarBraceL)
  23563. } else {
  23564. ++this.pos;
  23565. return this.finishToken(types$1.backQuote)
  23566. }
  23567. }
  23568. out += this.input.slice(chunkStart, this.pos);
  23569. return this.finishToken(types$1.template, out)
  23570. }
  23571. if (ch === 92) { // '\'
  23572. out += this.input.slice(chunkStart, this.pos);
  23573. out += this.readEscapedChar(true);
  23574. chunkStart = this.pos;
  23575. } else if (isNewLine(ch)) {
  23576. out += this.input.slice(chunkStart, this.pos);
  23577. ++this.pos;
  23578. switch (ch) {
  23579. case 13:
  23580. if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; }
  23581. case 10:
  23582. out += "\n";
  23583. break
  23584. default:
  23585. out += String.fromCharCode(ch);
  23586. break
  23587. }
  23588. if (this.options.locations) {
  23589. ++this.curLine;
  23590. this.lineStart = this.pos;
  23591. }
  23592. chunkStart = this.pos;
  23593. } else {
  23594. ++this.pos;
  23595. }
  23596. }
  23597. };
  23598. // Reads a template token to search for the end, without validating any escape sequences
  23599. pp.readInvalidTemplateToken = function() {
  23600. for (; this.pos < this.input.length; this.pos++) {
  23601. switch (this.input[this.pos]) {
  23602. case "\\":
  23603. ++this.pos;
  23604. break
  23605. case "$":
  23606. if (this.input[this.pos + 1] !== "{") {
  23607. break
  23608. }
  23609. // falls through
  23610. case "`":
  23611. return this.finishToken(types$1.invalidTemplate, this.input.slice(this.start, this.pos))
  23612. // no default
  23613. }
  23614. }
  23615. this.raise(this.start, "Unterminated template");
  23616. };
  23617. // Used to read escaped characters
  23618. pp.readEscapedChar = function(inTemplate) {
  23619. var ch = this.input.charCodeAt(++this.pos);
  23620. ++this.pos;
  23621. switch (ch) {
  23622. case 110: return "\n" // 'n' -> '\n'
  23623. case 114: return "\r" // 'r' -> '\r'
  23624. case 120: return String.fromCharCode(this.readHexChar(2)) // 'x'
  23625. case 117: return codePointToString(this.readCodePoint()) // 'u'
  23626. case 116: return "\t" // 't' -> '\t'
  23627. case 98: return "\b" // 'b' -> '\b'
  23628. case 118: return "\u000b" // 'v' -> '\u000b'
  23629. case 102: return "\f" // 'f' -> '\f'
  23630. case 13: if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; } // '\r\n'
  23631. case 10: // ' \n'
  23632. if (this.options.locations) { this.lineStart = this.pos; ++this.curLine; }
  23633. return ""
  23634. case 56:
  23635. case 57:
  23636. if (this.strict) {
  23637. this.invalidStringToken(
  23638. this.pos - 1,
  23639. "Invalid escape sequence"
  23640. );
  23641. }
  23642. if (inTemplate) {
  23643. var codePos = this.pos - 1;
  23644. this.invalidStringToken(
  23645. codePos,
  23646. "Invalid escape sequence in template string"
  23647. );
  23648. }
  23649. default:
  23650. if (ch >= 48 && ch <= 55) {
  23651. var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
  23652. var octal = parseInt(octalStr, 8);
  23653. if (octal > 255) {
  23654. octalStr = octalStr.slice(0, -1);
  23655. octal = parseInt(octalStr, 8);
  23656. }
  23657. this.pos += octalStr.length - 1;
  23658. ch = this.input.charCodeAt(this.pos);
  23659. if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) {
  23660. this.invalidStringToken(
  23661. this.pos - 1 - octalStr.length,
  23662. inTemplate
  23663. ? "Octal literal in template string"
  23664. : "Octal literal in strict mode"
  23665. );
  23666. }
  23667. return String.fromCharCode(octal)
  23668. }
  23669. if (isNewLine(ch)) {
  23670. // Unicode new line characters after \ get removed from output in both
  23671. // template literals and strings
  23672. return ""
  23673. }
  23674. return String.fromCharCode(ch)
  23675. }
  23676. };
  23677. // Used to read character escape sequences ('\x', '\u', '\U').
  23678. pp.readHexChar = function(len) {
  23679. var codePos = this.pos;
  23680. var n = this.readInt(16, len);
  23681. if (n === null) { this.invalidStringToken(codePos, "Bad character escape sequence"); }
  23682. return n
  23683. };
  23684. // Read an identifier, and return it as a string. Sets `this.containsEsc`
  23685. // to whether the word contained a '\u' escape.
  23686. //
  23687. // Incrementally adds only escaped chars, adding other chunks as-is
  23688. // as a micro-optimization.
  23689. pp.readWord1 = function() {
  23690. this.containsEsc = false;
  23691. var word = "", first = true, chunkStart = this.pos;
  23692. var astral = this.options.ecmaVersion >= 6;
  23693. while (this.pos < this.input.length) {
  23694. var ch = this.fullCharCodeAtPos();
  23695. if (isIdentifierChar(ch, astral)) {
  23696. this.pos += ch <= 0xffff ? 1 : 2;
  23697. } else if (ch === 92) { // "\"
  23698. this.containsEsc = true;
  23699. word += this.input.slice(chunkStart, this.pos);
  23700. var escStart = this.pos;
  23701. if (this.input.charCodeAt(++this.pos) !== 117) // "u"
  23702. { this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX"); }
  23703. ++this.pos;
  23704. var esc = this.readCodePoint();
  23705. if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral))
  23706. { this.invalidStringToken(escStart, "Invalid Unicode escape"); }
  23707. word += codePointToString(esc);
  23708. chunkStart = this.pos;
  23709. } else {
  23710. break
  23711. }
  23712. first = false;
  23713. }
  23714. return word + this.input.slice(chunkStart, this.pos)
  23715. };
  23716. // Read an identifier or keyword token. Will check for reserved
  23717. // words when necessary.
  23718. pp.readWord = function() {
  23719. var word = this.readWord1();
  23720. var type = types$1.name;
  23721. if (this.keywords.test(word)) {
  23722. type = keywords[word];
  23723. }
  23724. return this.finishToken(type, word)
  23725. };
  23726. // Acorn is a tiny, fast JavaScript parser written in JavaScript.
  23727. //
  23728. // Acorn was written by Marijn Haverbeke, Ingvar Stepanyan, and
  23729. // various contributors and released under an MIT license.
  23730. //
  23731. // Git repositories for Acorn are available at
  23732. //
  23733. // http://marijnhaverbeke.nl/git/acorn
  23734. // https://github.com/acornjs/acorn.git
  23735. //
  23736. // Please use the [github bug tracker][ghbt] to report issues.
  23737. //
  23738. // [ghbt]: https://github.com/acornjs/acorn/issues
  23739. //
  23740. // [walk]: util/walk.js
  23741. var version = "8.10.0";
  23742. Parser.acorn = {
  23743. Parser: Parser,
  23744. version: version,
  23745. defaultOptions: defaultOptions,
  23746. Position: Position,
  23747. SourceLocation: SourceLocation,
  23748. getLineInfo: getLineInfo,
  23749. Node: Node,
  23750. TokenType: TokenType,
  23751. tokTypes: types$1,
  23752. keywordTypes: keywords,
  23753. TokContext: TokContext,
  23754. tokContexts: types,
  23755. isIdentifierChar: isIdentifierChar,
  23756. isIdentifierStart: isIdentifierStart,
  23757. Token: Token,
  23758. isNewLine: isNewLine,
  23759. lineBreak: lineBreak,
  23760. lineBreakG: lineBreakG,
  23761. nonASCIIwhitespace: nonASCIIwhitespace
  23762. };
  23763. // The main exported interface (under `self.acorn` when in the
  23764. // browser) is a `parse` function that takes a code string and
  23765. // returns an abstract syntax tree as specified by [Mozilla parser
  23766. // API][api].
  23767. //
  23768. // [api]: https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API
  23769. function parse(input, options) {
  23770. return Parser.parse(input, options)
  23771. }
  23772. // This function tries to parse a single expression at a given
  23773. // offset in a string. Useful for parsing mixed-language formats
  23774. // that embed JavaScript expressions.
  23775. function parseExpressionAt(input, pos, options) {
  23776. return Parser.parseExpressionAt(input, pos, options)
  23777. }
  23778. // Acorn is organized as a tokenizer and a recursive-descent parser.
  23779. // The `tokenizer` export provides an interface to the tokenizer.
  23780. function tokenizer(input, options) {
  23781. return Parser.tokenizer(input, options)
  23782. }
  23783. const _acorn = /*#__PURE__*/Object.defineProperty({
  23784. __proto__: null,
  23785. Node,
  23786. Parser,
  23787. Position,
  23788. SourceLocation,
  23789. TokContext,
  23790. Token,
  23791. TokenType,
  23792. defaultOptions,
  23793. getLineInfo,
  23794. isIdentifierChar,
  23795. isIdentifierStart,
  23796. isNewLine,
  23797. keywordTypes: keywords,
  23798. lineBreak,
  23799. lineBreakG,
  23800. nonASCIIwhitespace,
  23801. parse,
  23802. parseExpressionAt,
  23803. tokContexts: types,
  23804. tokTypes: types$1,
  23805. tokenizer,
  23806. version
  23807. }, Symbol.toStringTag, { value: 'Module' });
  23808. function flru (max) {
  23809. var num, curr, prev;
  23810. var limit = max || 1;
  23811. function keep(key, value) {
  23812. if (++num > limit) {
  23813. prev = curr;
  23814. reset(1);
  23815. ++num;
  23816. }
  23817. curr[key] = value;
  23818. }
  23819. function reset(isPartial) {
  23820. num = 0;
  23821. curr = Object.create(null);
  23822. isPartial || (prev=Object.create(null));
  23823. }
  23824. reset();
  23825. return {
  23826. clear: reset,
  23827. has: function (key) {
  23828. return curr[key] !== void 0 || prev[key] !== void 0;
  23829. },
  23830. get: function (key) {
  23831. var val = curr[key];
  23832. if (val !== void 0) return val;
  23833. if ((val=prev[key]) !== void 0) {
  23834. keep(key, val);
  23835. return val;
  23836. }
  23837. },
  23838. set: function (key, value) {
  23839. if (curr[key] !== void 0) {
  23840. curr[key] = value;
  23841. } else {
  23842. keep(key, value);
  23843. }
  23844. }
  23845. };
  23846. }
  23847. function resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, assertions) {
  23848. let skipped = null;
  23849. let replaceContext = null;
  23850. if (skip) {
  23851. skipped = new Set();
  23852. for (const skippedCall of skip) {
  23853. if (source === skippedCall.source && importer === skippedCall.importer) {
  23854. skipped.add(skippedCall.plugin);
  23855. }
  23856. }
  23857. replaceContext = (pluginContext, plugin) => ({
  23858. ...pluginContext,
  23859. resolve: (source, importer, { assertions, custom, isEntry, skipSelf } = BLANK) => moduleLoaderResolveId(source, importer, custom, isEntry, assertions || EMPTY_OBJECT, skipSelf ? [...skip, { importer, plugin, source }] : skip)
  23860. });
  23861. }
  23862. return pluginDriver.hookFirstAndGetPlugin('resolveId', [source, importer, { assertions, custom: customOptions, isEntry }], replaceContext, skipped);
  23863. }
  23864. async function resolveId(source, importer, preserveSymlinks, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, assertions) {
  23865. const pluginResult = await resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, assertions);
  23866. if (pluginResult != null) {
  23867. const [resolveIdResult, plugin] = pluginResult;
  23868. if (typeof resolveIdResult === 'object' && !resolveIdResult.resolvedBy) {
  23869. return {
  23870. ...resolveIdResult,
  23871. resolvedBy: plugin.name
  23872. };
  23873. }
  23874. if (typeof resolveIdResult === 'string') {
  23875. return {
  23876. id: resolveIdResult,
  23877. resolvedBy: plugin.name
  23878. };
  23879. }
  23880. return resolveIdResult;
  23881. }
  23882. // external modules (non-entry modules that start with neither '.' or '/')
  23883. // are skipped at this stage.
  23884. if (importer !== undefined && !isAbsolute(source) && source[0] !== '.')
  23885. return null;
  23886. // `resolve` processes paths from right to left, prepending them until an
  23887. // absolute path is created. Absolute importees therefore shortcircuit the
  23888. // resolve call and require no special handing on our part.
  23889. // See https://nodejs.org/api/path.html#path_path_resolve_paths
  23890. return addJsExtensionIfNecessary(importer ? node_path.resolve(node_path.dirname(importer), source) : node_path.resolve(source), preserveSymlinks);
  23891. }
  23892. async function addJsExtensionIfNecessary(file, preserveSymlinks) {
  23893. return ((await findFile(file, preserveSymlinks)) ??
  23894. (await findFile(file + '.mjs', preserveSymlinks)) ??
  23895. (await findFile(file + '.js', preserveSymlinks)));
  23896. }
  23897. async function findFile(file, preserveSymlinks) {
  23898. try {
  23899. const stats = await promises.lstat(file);
  23900. if (!preserveSymlinks && stats.isSymbolicLink())
  23901. return await findFile(await promises.realpath(file), preserveSymlinks);
  23902. if ((preserveSymlinks && stats.isSymbolicLink()) || stats.isFile()) {
  23903. // check case
  23904. const name = node_path.basename(file);
  23905. const files = await promises.readdir(node_path.dirname(file));
  23906. if (files.includes(name))
  23907. return file;
  23908. }
  23909. }
  23910. catch {
  23911. // suppress
  23912. }
  23913. }
  23914. async function transform(source, module, pluginDriver, log) {
  23915. const id = module.id;
  23916. const sourcemapChain = [];
  23917. let originalSourcemap = source.map === null ? null : decodedSourcemap(source.map);
  23918. const originalCode = source.code;
  23919. let ast = source.ast;
  23920. const transformDependencies = [];
  23921. const emittedFiles = [];
  23922. let customTransformCache = false;
  23923. const useCustomTransformCache = () => (customTransformCache = true);
  23924. let pluginName = '';
  23925. let currentSource = source.code;
  23926. function transformReducer(previousCode, result, plugin) {
  23927. let code;
  23928. let map;
  23929. if (typeof result === 'string') {
  23930. code = result;
  23931. }
  23932. else if (result && typeof result === 'object') {
  23933. module.updateOptions(result);
  23934. if (result.code == null) {
  23935. if (result.map || result.ast) {
  23936. log(LOGLEVEL_WARN, logNoTransformMapOrAstWithoutCode(plugin.name));
  23937. }
  23938. return previousCode;
  23939. }
  23940. ({ code, map, ast } = result);
  23941. }
  23942. else {
  23943. return previousCode;
  23944. }
  23945. // strict null check allows 'null' maps to not be pushed to the chain,
  23946. // while 'undefined' gets the missing map warning
  23947. if (map !== null) {
  23948. sourcemapChain.push(decodedSourcemap(typeof map === 'string' ? JSON.parse(map) : map) || {
  23949. missing: true,
  23950. plugin: plugin.name
  23951. });
  23952. }
  23953. currentSource = code;
  23954. return code;
  23955. }
  23956. const getLogHandler = (handler) => (log, pos) => {
  23957. log = normalizeLog(log);
  23958. if (pos)
  23959. augmentCodeLocation(log, pos, currentSource, id);
  23960. log.id = id;
  23961. log.hook = 'transform';
  23962. handler(log);
  23963. };
  23964. let code;
  23965. try {
  23966. code = await pluginDriver.hookReduceArg0('transform', [currentSource, id], transformReducer, (pluginContext, plugin) => {
  23967. pluginName = plugin.name;
  23968. return {
  23969. ...pluginContext,
  23970. addWatchFile(id) {
  23971. transformDependencies.push(id);
  23972. pluginContext.addWatchFile(id);
  23973. },
  23974. cache: customTransformCache
  23975. ? pluginContext.cache
  23976. : getTrackedPluginCache(pluginContext.cache, useCustomTransformCache),
  23977. debug: getLogHandler(pluginContext.debug),
  23978. emitFile(emittedFile) {
  23979. emittedFiles.push(emittedFile);
  23980. return pluginDriver.emitFile(emittedFile);
  23981. },
  23982. error(error_, pos) {
  23983. if (typeof error_ === 'string')
  23984. error_ = { message: error_ };
  23985. if (pos)
  23986. augmentCodeLocation(error_, pos, currentSource, id);
  23987. error_.id = id;
  23988. error_.hook = 'transform';
  23989. return pluginContext.error(error_);
  23990. },
  23991. getCombinedSourcemap() {
  23992. const combinedMap = collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, log);
  23993. if (!combinedMap) {
  23994. const magicString = new MagicString(originalCode);
  23995. return magicString.generateMap({ hires: true, includeContent: true, source: id });
  23996. }
  23997. if (originalSourcemap !== combinedMap) {
  23998. originalSourcemap = combinedMap;
  23999. sourcemapChain.length = 0;
  24000. }
  24001. return new SourceMap({
  24002. ...combinedMap,
  24003. file: null,
  24004. sourcesContent: combinedMap.sourcesContent
  24005. });
  24006. },
  24007. info: getLogHandler(pluginContext.info),
  24008. setAssetSource() {
  24009. return this.error(logInvalidSetAssetSourceCall());
  24010. },
  24011. warn: getLogHandler(pluginContext.warn)
  24012. };
  24013. });
  24014. }
  24015. catch (error_) {
  24016. return error(logPluginError(error_, pluginName, { hook: 'transform', id }));
  24017. }
  24018. if (!customTransformCache && // files emitted by a transform hook need to be emitted again if the hook is skipped
  24019. emittedFiles.length > 0)
  24020. module.transformFiles = emittedFiles;
  24021. return {
  24022. ast,
  24023. code,
  24024. customTransformCache,
  24025. originalCode,
  24026. originalSourcemap,
  24027. sourcemapChain,
  24028. transformDependencies
  24029. };
  24030. }
  24031. const RESOLVE_DEPENDENCIES = 'resolveDependencies';
  24032. class ModuleLoader {
  24033. constructor(graph, modulesById, options, pluginDriver) {
  24034. this.graph = graph;
  24035. this.modulesById = modulesById;
  24036. this.options = options;
  24037. this.pluginDriver = pluginDriver;
  24038. this.implicitEntryModules = new Set();
  24039. this.indexedEntryModules = [];
  24040. this.latestLoadModulesPromise = Promise.resolve();
  24041. this.moduleLoadPromises = new Map();
  24042. this.modulesWithLoadedDependencies = new Set();
  24043. this.nextChunkNamePriority = 0;
  24044. this.nextEntryModuleIndex = 0;
  24045. this.resolveId = async (source, importer, customOptions, isEntry, assertions, skip = null) => this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(this.options.external(source, importer, false)
  24046. ? false
  24047. : await resolveId(source, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, skip, customOptions, typeof isEntry === 'boolean' ? isEntry : !importer, assertions), importer, source), assertions);
  24048. this.hasModuleSideEffects = options.treeshake
  24049. ? options.treeshake.moduleSideEffects
  24050. : () => true;
  24051. }
  24052. async addAdditionalModules(unresolvedModules, isAddForManualChunks) {
  24053. const result = this.extendLoadModulesPromise(Promise.all(unresolvedModules.map(id => this.loadEntryModule(id, false, undefined, null, isAddForManualChunks))));
  24054. await this.awaitLoadModulesPromise();
  24055. return result;
  24056. }
  24057. async addEntryModules(unresolvedEntryModules, isUserDefined) {
  24058. const firstEntryModuleIndex = this.nextEntryModuleIndex;
  24059. this.nextEntryModuleIndex += unresolvedEntryModules.length;
  24060. const firstChunkNamePriority = this.nextChunkNamePriority;
  24061. this.nextChunkNamePriority += unresolvedEntryModules.length;
  24062. const newEntryModules = await this.extendLoadModulesPromise(Promise.all(unresolvedEntryModules.map(({ id, importer }) => this.loadEntryModule(id, true, importer, null))).then(entryModules => {
  24063. for (const [index, entryModule] of entryModules.entries()) {
  24064. entryModule.isUserDefinedEntryPoint =
  24065. entryModule.isUserDefinedEntryPoint || isUserDefined;
  24066. addChunkNamesToModule(entryModule, unresolvedEntryModules[index], isUserDefined, firstChunkNamePriority + index);
  24067. const existingIndexedModule = this.indexedEntryModules.find(indexedModule => indexedModule.module === entryModule);
  24068. if (existingIndexedModule) {
  24069. existingIndexedModule.index = Math.min(existingIndexedModule.index, firstEntryModuleIndex + index);
  24070. }
  24071. else {
  24072. this.indexedEntryModules.push({
  24073. index: firstEntryModuleIndex + index,
  24074. module: entryModule
  24075. });
  24076. }
  24077. }
  24078. this.indexedEntryModules.sort(({ index: indexA }, { index: indexB }) => indexA > indexB ? 1 : -1);
  24079. return entryModules;
  24080. }));
  24081. await this.awaitLoadModulesPromise();
  24082. return {
  24083. entryModules: this.indexedEntryModules.map(({ module }) => module),
  24084. implicitEntryModules: [...this.implicitEntryModules],
  24085. newEntryModules
  24086. };
  24087. }
  24088. async emitChunk({ fileName, id, importer, name, implicitlyLoadedAfterOneOf, preserveSignature }) {
  24089. const unresolvedModule = {
  24090. fileName: fileName || null,
  24091. id,
  24092. importer,
  24093. name: name || null
  24094. };
  24095. const module = implicitlyLoadedAfterOneOf
  24096. ? await this.addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfterOneOf)
  24097. : (await this.addEntryModules([unresolvedModule], false)).newEntryModules[0];
  24098. if (preserveSignature != null) {
  24099. module.preserveSignature = preserveSignature;
  24100. }
  24101. return module;
  24102. }
  24103. async preloadModule(resolvedId) {
  24104. const module = await this.fetchModule(this.getResolvedIdWithDefaults(resolvedId, EMPTY_OBJECT), undefined, false, resolvedId.resolveDependencies ? RESOLVE_DEPENDENCIES : true);
  24105. return module.info;
  24106. }
  24107. addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfter) {
  24108. const chunkNamePriority = this.nextChunkNamePriority++;
  24109. return this.extendLoadModulesPromise(this.loadEntryModule(unresolvedModule.id, false, unresolvedModule.importer, null).then(async (entryModule) => {
  24110. addChunkNamesToModule(entryModule, unresolvedModule, false, chunkNamePriority);
  24111. if (!entryModule.info.isEntry) {
  24112. this.implicitEntryModules.add(entryModule);
  24113. const implicitlyLoadedAfterModules = await Promise.all(implicitlyLoadedAfter.map(id => this.loadEntryModule(id, false, unresolvedModule.importer, entryModule.id)));
  24114. for (const module of implicitlyLoadedAfterModules) {
  24115. entryModule.implicitlyLoadedAfter.add(module);
  24116. }
  24117. for (const dependant of entryModule.implicitlyLoadedAfter) {
  24118. dependant.implicitlyLoadedBefore.add(entryModule);
  24119. }
  24120. }
  24121. return entryModule;
  24122. }));
  24123. }
  24124. async addModuleSource(id, importer, module) {
  24125. let source;
  24126. try {
  24127. source = await this.graph.fileOperationQueue.run(async () => (await this.pluginDriver.hookFirst('load', [id])) ?? (await promises.readFile(id, 'utf8')));
  24128. }
  24129. catch (error_) {
  24130. let message = `Could not load ${id}`;
  24131. if (importer)
  24132. message += ` (imported by ${relativeId(importer)})`;
  24133. message += `: ${error_.message}`;
  24134. error_.message = message;
  24135. throw error_;
  24136. }
  24137. const sourceDescription = typeof source === 'string'
  24138. ? { code: source }
  24139. : source != null && typeof source === 'object' && typeof source.code === 'string'
  24140. ? source
  24141. : error(logBadLoader(id));
  24142. const cachedModule = this.graph.cachedModules.get(id);
  24143. if (cachedModule &&
  24144. !cachedModule.customTransformCache &&
  24145. cachedModule.originalCode === sourceDescription.code &&
  24146. !(await this.pluginDriver.hookFirst('shouldTransformCachedModule', [
  24147. {
  24148. ast: cachedModule.ast,
  24149. code: cachedModule.code,
  24150. id: cachedModule.id,
  24151. meta: cachedModule.meta,
  24152. moduleSideEffects: cachedModule.moduleSideEffects,
  24153. resolvedSources: cachedModule.resolvedIds,
  24154. syntheticNamedExports: cachedModule.syntheticNamedExports
  24155. }
  24156. ]))) {
  24157. if (cachedModule.transformFiles) {
  24158. for (const emittedFile of cachedModule.transformFiles)
  24159. this.pluginDriver.emitFile(emittedFile);
  24160. }
  24161. module.setSource(cachedModule);
  24162. }
  24163. else {
  24164. module.updateOptions(sourceDescription);
  24165. module.setSource(await transform(sourceDescription, module, this.pluginDriver, this.options.onLog));
  24166. }
  24167. }
  24168. async awaitLoadModulesPromise() {
  24169. let startingPromise;
  24170. do {
  24171. startingPromise = this.latestLoadModulesPromise;
  24172. await startingPromise;
  24173. } while (startingPromise !== this.latestLoadModulesPromise);
  24174. }
  24175. extendLoadModulesPromise(loadNewModulesPromise) {
  24176. this.latestLoadModulesPromise = Promise.all([
  24177. loadNewModulesPromise,
  24178. this.latestLoadModulesPromise
  24179. ]);
  24180. this.latestLoadModulesPromise.catch(() => {
  24181. /* Avoid unhandled Promise rejections */
  24182. });
  24183. return loadNewModulesPromise;
  24184. }
  24185. async fetchDynamicDependencies(module, resolveDynamicImportPromises) {
  24186. const dependencies = await Promise.all(resolveDynamicImportPromises.map(resolveDynamicImportPromise => resolveDynamicImportPromise.then(async ([dynamicImport, resolvedId]) => {
  24187. if (resolvedId === null)
  24188. return null;
  24189. if (typeof resolvedId === 'string') {
  24190. dynamicImport.resolution = resolvedId;
  24191. return null;
  24192. }
  24193. return (dynamicImport.resolution = await this.fetchResolvedDependency(relativeId(resolvedId.id), module.id, resolvedId));
  24194. })));
  24195. for (const dependency of dependencies) {
  24196. if (dependency) {
  24197. module.dynamicDependencies.add(dependency);
  24198. dependency.dynamicImporters.push(module.id);
  24199. }
  24200. }
  24201. }
  24202. // If this is a preload, then this method always waits for the dependencies of
  24203. // the module to be resolved.
  24204. // Otherwise, if the module does not exist, it waits for the module and all
  24205. // its dependencies to be loaded.
  24206. // Otherwise, it returns immediately.
  24207. async fetchModule({ assertions, id, meta, moduleSideEffects, syntheticNamedExports }, importer, isEntry, isPreload) {
  24208. const existingModule = this.modulesById.get(id);
  24209. if (existingModule instanceof Module) {
  24210. if (importer && doAssertionsDiffer(assertions, existingModule.info.assertions)) {
  24211. this.options.onLog(LOGLEVEL_WARN, logInconsistentImportAssertions(existingModule.info.assertions, assertions, id, importer));
  24212. }
  24213. await this.handleExistingModule(existingModule, isEntry, isPreload);
  24214. return existingModule;
  24215. }
  24216. if (existingModule instanceof ExternalModule) {
  24217. return error(logExternalModulesCannotBeTransformedToModules(existingModule.id));
  24218. }
  24219. const module = new Module(this.graph, id, this.options, isEntry, moduleSideEffects, syntheticNamedExports, meta, assertions);
  24220. this.modulesById.set(id, module);
  24221. this.graph.watchFiles[id] = true;
  24222. const loadPromise = this.addModuleSource(id, importer, module).then(() => [
  24223. this.getResolveStaticDependencyPromises(module),
  24224. this.getResolveDynamicImportPromises(module),
  24225. loadAndResolveDependenciesPromise
  24226. ]);
  24227. const loadAndResolveDependenciesPromise = waitForDependencyResolution(loadPromise).then(() => this.pluginDriver.hookParallel('moduleParsed', [module.info]));
  24228. loadAndResolveDependenciesPromise.catch(() => {
  24229. /* avoid unhandled promise rejections */
  24230. });
  24231. this.moduleLoadPromises.set(module, loadPromise);
  24232. const resolveDependencyPromises = await loadPromise;
  24233. if (!isPreload) {
  24234. await this.fetchModuleDependencies(module, ...resolveDependencyPromises);
  24235. }
  24236. else if (isPreload === RESOLVE_DEPENDENCIES) {
  24237. await loadAndResolveDependenciesPromise;
  24238. }
  24239. return module;
  24240. }
  24241. async fetchModuleDependencies(module, resolveStaticDependencyPromises, resolveDynamicDependencyPromises, loadAndResolveDependenciesPromise) {
  24242. if (this.modulesWithLoadedDependencies.has(module)) {
  24243. return;
  24244. }
  24245. this.modulesWithLoadedDependencies.add(module);
  24246. await Promise.all([
  24247. this.fetchStaticDependencies(module, resolveStaticDependencyPromises),
  24248. this.fetchDynamicDependencies(module, resolveDynamicDependencyPromises)
  24249. ]);
  24250. module.linkImports();
  24251. // To handle errors when resolving dependencies or in moduleParsed
  24252. await loadAndResolveDependenciesPromise;
  24253. }
  24254. fetchResolvedDependency(source, importer, resolvedId) {
  24255. if (resolvedId.external) {
  24256. const { assertions, external, id, moduleSideEffects, meta } = resolvedId;
  24257. let externalModule = this.modulesById.get(id);
  24258. if (!externalModule) {
  24259. externalModule = new ExternalModule(this.options, id, moduleSideEffects, meta, external !== 'absolute' && isAbsolute(id), assertions);
  24260. this.modulesById.set(id, externalModule);
  24261. }
  24262. else if (!(externalModule instanceof ExternalModule)) {
  24263. return error(logInternalIdCannotBeExternal(source, importer));
  24264. }
  24265. else if (doAssertionsDiffer(externalModule.info.assertions, assertions)) {
  24266. this.options.onLog(LOGLEVEL_WARN, logInconsistentImportAssertions(externalModule.info.assertions, assertions, source, importer));
  24267. }
  24268. return Promise.resolve(externalModule);
  24269. }
  24270. return this.fetchModule(resolvedId, importer, false, false);
  24271. }
  24272. async fetchStaticDependencies(module, resolveStaticDependencyPromises) {
  24273. for (const dependency of await Promise.all(resolveStaticDependencyPromises.map(resolveStaticDependencyPromise => resolveStaticDependencyPromise.then(([source, resolvedId]) => this.fetchResolvedDependency(source, module.id, resolvedId))))) {
  24274. module.dependencies.add(dependency);
  24275. dependency.importers.push(module.id);
  24276. }
  24277. if (!this.options.treeshake || module.info.moduleSideEffects === 'no-treeshake') {
  24278. for (const dependency of module.dependencies) {
  24279. if (dependency instanceof Module) {
  24280. dependency.importedFromNotTreeshaken = true;
  24281. }
  24282. }
  24283. }
  24284. }
  24285. getNormalizedResolvedIdWithoutDefaults(resolveIdResult, importer, source) {
  24286. const { makeAbsoluteExternalsRelative } = this.options;
  24287. if (resolveIdResult) {
  24288. if (typeof resolveIdResult === 'object') {
  24289. const external = resolveIdResult.external || this.options.external(resolveIdResult.id, importer, true);
  24290. return {
  24291. ...resolveIdResult,
  24292. external: external &&
  24293. (external === 'relative' ||
  24294. !isAbsolute(resolveIdResult.id) ||
  24295. (external === true &&
  24296. isNotAbsoluteExternal(resolveIdResult.id, source, makeAbsoluteExternalsRelative)) ||
  24297. 'absolute')
  24298. };
  24299. }
  24300. const external = this.options.external(resolveIdResult, importer, true);
  24301. return {
  24302. external: external &&
  24303. (isNotAbsoluteExternal(resolveIdResult, source, makeAbsoluteExternalsRelative) ||
  24304. 'absolute'),
  24305. id: external && makeAbsoluteExternalsRelative
  24306. ? normalizeRelativeExternalId(resolveIdResult, importer)
  24307. : resolveIdResult
  24308. };
  24309. }
  24310. const id = makeAbsoluteExternalsRelative
  24311. ? normalizeRelativeExternalId(source, importer)
  24312. : source;
  24313. if (resolveIdResult !== false && !this.options.external(id, importer, true)) {
  24314. return null;
  24315. }
  24316. return {
  24317. external: isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) || 'absolute',
  24318. id
  24319. };
  24320. }
  24321. getResolveDynamicImportPromises(module) {
  24322. return module.dynamicImports.map(async (dynamicImport) => {
  24323. const resolvedId = await this.resolveDynamicImport(module, typeof dynamicImport.argument === 'string'
  24324. ? dynamicImport.argument
  24325. : dynamicImport.argument.esTreeNode, module.id, getAssertionsFromImportExpression(dynamicImport.node));
  24326. if (resolvedId && typeof resolvedId === 'object') {
  24327. dynamicImport.id = resolvedId.id;
  24328. }
  24329. return [dynamicImport, resolvedId];
  24330. });
  24331. }
  24332. getResolveStaticDependencyPromises(module) {
  24333. // eslint-disable-next-line unicorn/prefer-spread
  24334. return Array.from(module.sourcesWithAssertions, async ([source, assertions]) => [
  24335. source,
  24336. (module.resolvedIds[source] =
  24337. module.resolvedIds[source] ||
  24338. this.handleInvalidResolvedId(await this.resolveId(source, module.id, EMPTY_OBJECT, false, assertions), source, module.id, assertions))
  24339. ]);
  24340. }
  24341. getResolvedIdWithDefaults(resolvedId, assertions) {
  24342. if (!resolvedId) {
  24343. return null;
  24344. }
  24345. const external = resolvedId.external || false;
  24346. return {
  24347. assertions: resolvedId.assertions || assertions,
  24348. external,
  24349. id: resolvedId.id,
  24350. meta: resolvedId.meta || {},
  24351. moduleSideEffects: resolvedId.moduleSideEffects ?? this.hasModuleSideEffects(resolvedId.id, !!external),
  24352. resolvedBy: resolvedId.resolvedBy ?? 'rollup',
  24353. syntheticNamedExports: resolvedId.syntheticNamedExports ?? false
  24354. };
  24355. }
  24356. async handleExistingModule(module, isEntry, isPreload) {
  24357. const loadPromise = this.moduleLoadPromises.get(module);
  24358. if (isPreload) {
  24359. return isPreload === RESOLVE_DEPENDENCIES
  24360. ? waitForDependencyResolution(loadPromise)
  24361. : loadPromise;
  24362. }
  24363. if (isEntry) {
  24364. module.info.isEntry = true;
  24365. this.implicitEntryModules.delete(module);
  24366. for (const dependant of module.implicitlyLoadedAfter) {
  24367. dependant.implicitlyLoadedBefore.delete(module);
  24368. }
  24369. module.implicitlyLoadedAfter.clear();
  24370. }
  24371. return this.fetchModuleDependencies(module, ...(await loadPromise));
  24372. }
  24373. handleInvalidResolvedId(resolvedId, source, importer, assertions) {
  24374. if (resolvedId === null) {
  24375. if (isRelative(source)) {
  24376. return error(logUnresolvedImport(source, importer));
  24377. }
  24378. this.options.onLog(LOGLEVEL_WARN, logUnresolvedImportTreatedAsExternal(source, importer));
  24379. return {
  24380. assertions,
  24381. external: true,
  24382. id: source,
  24383. meta: {},
  24384. moduleSideEffects: this.hasModuleSideEffects(source, true),
  24385. resolvedBy: 'rollup',
  24386. syntheticNamedExports: false
  24387. };
  24388. }
  24389. else if (resolvedId.external && resolvedId.syntheticNamedExports) {
  24390. this.options.onLog(LOGLEVEL_WARN, logExternalSyntheticExports(source, importer));
  24391. }
  24392. return resolvedId;
  24393. }
  24394. async loadEntryModule(unresolvedId, isEntry, importer, implicitlyLoadedBefore, isLoadForManualChunks = false) {
  24395. const resolveIdResult = await resolveId(unresolvedId, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, null, EMPTY_OBJECT, true, EMPTY_OBJECT);
  24396. if (resolveIdResult == null) {
  24397. return error(implicitlyLoadedBefore === null
  24398. ? logUnresolvedEntry(unresolvedId)
  24399. : logUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore));
  24400. }
  24401. const isExternalModules = typeof resolveIdResult === 'object' && resolveIdResult.external;
  24402. if (resolveIdResult === false || isExternalModules) {
  24403. return error(implicitlyLoadedBefore === null
  24404. ? isExternalModules && isLoadForManualChunks
  24405. ? logExternalModulesCannotBeIncludedInManualChunks(unresolvedId)
  24406. : logEntryCannotBeExternal(unresolvedId)
  24407. : logImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore));
  24408. }
  24409. return this.fetchModule(this.getResolvedIdWithDefaults(typeof resolveIdResult === 'object'
  24410. ? resolveIdResult
  24411. : { id: resolveIdResult }, EMPTY_OBJECT), undefined, isEntry, false);
  24412. }
  24413. async resolveDynamicImport(module, specifier, importer, assertions) {
  24414. const resolution = await this.pluginDriver.hookFirst('resolveDynamicImport', [
  24415. specifier,
  24416. importer,
  24417. { assertions }
  24418. ]);
  24419. if (typeof specifier !== 'string') {
  24420. if (typeof resolution === 'string') {
  24421. return resolution;
  24422. }
  24423. if (!resolution) {
  24424. return null;
  24425. }
  24426. return this.getResolvedIdWithDefaults(resolution, assertions);
  24427. }
  24428. if (resolution == null) {
  24429. const existingResolution = module.resolvedIds[specifier];
  24430. if (existingResolution) {
  24431. if (doAssertionsDiffer(existingResolution.assertions, assertions)) {
  24432. this.options.onLog(LOGLEVEL_WARN, logInconsistentImportAssertions(existingResolution.assertions, assertions, specifier, importer));
  24433. }
  24434. return existingResolution;
  24435. }
  24436. return (module.resolvedIds[specifier] = this.handleInvalidResolvedId(await this.resolveId(specifier, module.id, EMPTY_OBJECT, false, assertions), specifier, module.id, assertions));
  24437. }
  24438. return this.handleInvalidResolvedId(this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(resolution, importer, specifier), assertions), specifier, importer, assertions);
  24439. }
  24440. }
  24441. function normalizeRelativeExternalId(source, importer) {
  24442. return isRelative(source)
  24443. ? importer
  24444. ? node_path.resolve(importer, '..', source)
  24445. : node_path.resolve(source)
  24446. : source;
  24447. }
  24448. function addChunkNamesToModule(module, { fileName, name }, isUserDefined, priority) {
  24449. if (fileName !== null) {
  24450. module.chunkFileNames.add(fileName);
  24451. }
  24452. else if (name !== null) {
  24453. // Always keep chunkNames sorted by priority
  24454. let namePosition = 0;
  24455. while (module.chunkNames[namePosition]?.priority < priority)
  24456. namePosition++;
  24457. module.chunkNames.splice(namePosition, 0, { isUserDefined, name, priority });
  24458. }
  24459. }
  24460. function isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) {
  24461. return (makeAbsoluteExternalsRelative === true ||
  24462. (makeAbsoluteExternalsRelative === 'ifRelativeSource' && isRelative(source)) ||
  24463. !isAbsolute(id));
  24464. }
  24465. async function waitForDependencyResolution(loadPromise) {
  24466. const [resolveStaticDependencyPromises, resolveDynamicImportPromises] = await loadPromise;
  24467. return Promise.all([...resolveStaticDependencyPromises, ...resolveDynamicImportPromises]);
  24468. }
  24469. class GlobalScope extends Scope$1 {
  24470. constructor() {
  24471. super();
  24472. this.parent = null;
  24473. this.variables.set('undefined', new UndefinedVariable());
  24474. }
  24475. findVariable(name) {
  24476. let variable = this.variables.get(name);
  24477. if (!variable) {
  24478. variable = new GlobalVariable(name);
  24479. this.variables.set(name, variable);
  24480. }
  24481. return variable;
  24482. }
  24483. }
  24484. class Queue {
  24485. constructor(maxParallel) {
  24486. this.maxParallel = maxParallel;
  24487. this.queue = [];
  24488. this.workerCount = 0;
  24489. }
  24490. run(task) {
  24491. return new Promise((resolve, reject) => {
  24492. this.queue.push({ reject, resolve, task });
  24493. this.work();
  24494. });
  24495. }
  24496. async work() {
  24497. if (this.workerCount >= this.maxParallel)
  24498. return;
  24499. this.workerCount++;
  24500. let entry;
  24501. while ((entry = this.queue.shift())) {
  24502. const { reject, resolve, task } = entry;
  24503. try {
  24504. const result = await task();
  24505. resolve(result);
  24506. }
  24507. catch (error) {
  24508. reject(error);
  24509. }
  24510. }
  24511. this.workerCount--;
  24512. }
  24513. }
  24514. function normalizeEntryModules(entryModules) {
  24515. if (Array.isArray(entryModules)) {
  24516. return entryModules.map(id => ({
  24517. fileName: null,
  24518. id,
  24519. implicitlyLoadedAfter: [],
  24520. importer: undefined,
  24521. name: null
  24522. }));
  24523. }
  24524. return Object.entries(entryModules).map(([name, id]) => ({
  24525. fileName: null,
  24526. id,
  24527. implicitlyLoadedAfter: [],
  24528. importer: undefined,
  24529. name
  24530. }));
  24531. }
  24532. class Graph {
  24533. constructor(options, watcher) {
  24534. this.options = options;
  24535. this.astLru = flru(5);
  24536. this.cachedModules = new Map();
  24537. this.deoptimizationTracker = new PathTracker();
  24538. this.entryModules = [];
  24539. this.modulesById = new Map();
  24540. this.needsTreeshakingPass = false;
  24541. this.phase = BuildPhase.LOAD_AND_PARSE;
  24542. this.scope = new GlobalScope();
  24543. this.watchFiles = Object.create(null);
  24544. this.watchMode = false;
  24545. this.externalModules = [];
  24546. this.implicitEntryModules = [];
  24547. this.modules = [];
  24548. this.getModuleInfo = (moduleId) => {
  24549. const foundModule = this.modulesById.get(moduleId);
  24550. if (!foundModule)
  24551. return null;
  24552. return foundModule.info;
  24553. };
  24554. if (options.cache !== false) {
  24555. if (options.cache?.modules) {
  24556. for (const module of options.cache.modules)
  24557. this.cachedModules.set(module.id, module);
  24558. }
  24559. this.pluginCache = options.cache?.plugins || Object.create(null);
  24560. // increment access counter
  24561. for (const name in this.pluginCache) {
  24562. const cache = this.pluginCache[name];
  24563. for (const value of Object.values(cache))
  24564. value[0]++;
  24565. }
  24566. }
  24567. if (watcher) {
  24568. this.watchMode = true;
  24569. const handleChange = (...parameters) => this.pluginDriver.hookParallel('watchChange', parameters);
  24570. const handleClose = () => this.pluginDriver.hookParallel('closeWatcher', []);
  24571. watcher.onCurrentRun('change', handleChange);
  24572. watcher.onCurrentRun('close', handleClose);
  24573. }
  24574. this.pluginDriver = new PluginDriver(this, options, options.plugins, this.pluginCache);
  24575. this.acornParser = Parser.extend(...options.acornInjectPlugins);
  24576. this.moduleLoader = new ModuleLoader(this, this.modulesById, this.options, this.pluginDriver);
  24577. this.fileOperationQueue = new Queue(options.maxParallelFileOps);
  24578. this.pureFunctions = getPureFunctions(options);
  24579. }
  24580. async build() {
  24581. timeStart('generate module graph', 2);
  24582. await this.generateModuleGraph();
  24583. timeEnd('generate module graph', 2);
  24584. timeStart('sort and bind modules', 2);
  24585. this.phase = BuildPhase.ANALYSE;
  24586. this.sortModules();
  24587. timeEnd('sort and bind modules', 2);
  24588. timeStart('mark included statements', 2);
  24589. this.includeStatements();
  24590. timeEnd('mark included statements', 2);
  24591. this.phase = BuildPhase.GENERATE;
  24592. }
  24593. contextParse(code, options = {}) {
  24594. const onCommentOrig = options.onComment;
  24595. const comments = [];
  24596. options.onComment =
  24597. onCommentOrig && typeof onCommentOrig == 'function'
  24598. ? (block, text, start, end, ...parameters) => {
  24599. comments.push({ end, start, type: block ? 'Block' : 'Line', value: text });
  24600. return onCommentOrig.call(options, block, text, start, end, ...parameters);
  24601. }
  24602. : comments;
  24603. const ast = this.acornParser.parse(code, {
  24604. ...this.options.acorn,
  24605. ...options
  24606. });
  24607. if (typeof onCommentOrig == 'object') {
  24608. onCommentOrig.push(...comments);
  24609. }
  24610. options.onComment = onCommentOrig;
  24611. addAnnotations(comments, ast, code);
  24612. return ast;
  24613. }
  24614. getCache() {
  24615. // handle plugin cache eviction
  24616. for (const name in this.pluginCache) {
  24617. const cache = this.pluginCache[name];
  24618. let allDeleted = true;
  24619. for (const [key, value] of Object.entries(cache)) {
  24620. if (value[0] >= this.options.experimentalCacheExpiry)
  24621. delete cache[key];
  24622. else
  24623. allDeleted = false;
  24624. }
  24625. if (allDeleted)
  24626. delete this.pluginCache[name];
  24627. }
  24628. return {
  24629. modules: this.modules.map(module => module.toJSON()),
  24630. plugins: this.pluginCache
  24631. };
  24632. }
  24633. async generateModuleGraph() {
  24634. ({ entryModules: this.entryModules, implicitEntryModules: this.implicitEntryModules } =
  24635. await this.moduleLoader.addEntryModules(normalizeEntryModules(this.options.input), true));
  24636. if (this.entryModules.length === 0) {
  24637. throw new Error('You must supply options.input to rollup');
  24638. }
  24639. for (const module of this.modulesById.values()) {
  24640. if (module instanceof Module) {
  24641. this.modules.push(module);
  24642. }
  24643. else {
  24644. this.externalModules.push(module);
  24645. }
  24646. }
  24647. }
  24648. includeStatements() {
  24649. const entryModules = [...this.entryModules, ...this.implicitEntryModules];
  24650. for (const module of entryModules) {
  24651. markModuleAndImpureDependenciesAsExecuted(module);
  24652. }
  24653. if (this.options.treeshake) {
  24654. let treeshakingPass = 1;
  24655. do {
  24656. timeStart(`treeshaking pass ${treeshakingPass}`, 3);
  24657. this.needsTreeshakingPass = false;
  24658. for (const module of this.modules) {
  24659. if (module.isExecuted) {
  24660. if (module.info.moduleSideEffects === 'no-treeshake') {
  24661. module.includeAllInBundle();
  24662. }
  24663. else {
  24664. module.include();
  24665. }
  24666. }
  24667. }
  24668. if (treeshakingPass === 1) {
  24669. // We only include exports after the first pass to avoid issues with
  24670. // the TDZ detection logic
  24671. for (const module of entryModules) {
  24672. if (module.preserveSignature !== false) {
  24673. module.includeAllExports(false);
  24674. this.needsTreeshakingPass = true;
  24675. }
  24676. }
  24677. }
  24678. timeEnd(`treeshaking pass ${treeshakingPass++}`, 3);
  24679. } while (this.needsTreeshakingPass);
  24680. }
  24681. else {
  24682. for (const module of this.modules)
  24683. module.includeAllInBundle();
  24684. }
  24685. for (const externalModule of this.externalModules)
  24686. externalModule.warnUnusedImports();
  24687. for (const module of this.implicitEntryModules) {
  24688. for (const dependant of module.implicitlyLoadedAfter) {
  24689. if (!(dependant.info.isEntry || dependant.isIncluded())) {
  24690. error(logImplicitDependantIsNotIncluded(dependant));
  24691. }
  24692. }
  24693. }
  24694. }
  24695. sortModules() {
  24696. const { orderedModules, cyclePaths } = analyseModuleExecution(this.entryModules);
  24697. for (const cyclePath of cyclePaths) {
  24698. this.options.onLog(LOGLEVEL_WARN, logCircularDependency(cyclePath));
  24699. }
  24700. this.modules = orderedModules;
  24701. for (const module of this.modules) {
  24702. module.bindReferences();
  24703. }
  24704. this.warnForMissingExports();
  24705. }
  24706. warnForMissingExports() {
  24707. for (const module of this.modules) {
  24708. for (const importDescription of module.importDescriptions.values()) {
  24709. if (importDescription.name !== '*' &&
  24710. !importDescription.module.getVariableForExportName(importDescription.name)[0]) {
  24711. module.log(LOGLEVEL_WARN, logMissingExport(importDescription.name, module.id, importDescription.module.id), importDescription.start);
  24712. }
  24713. }
  24714. }
  24715. }
  24716. }
  24717. function formatAction([pluginName, hookName, parameters]) {
  24718. const action = `(${pluginName}) ${hookName}`;
  24719. const s = JSON.stringify;
  24720. switch (hookName) {
  24721. case 'resolveId': {
  24722. return `${action} ${s(parameters[0])} ${s(parameters[1])}`;
  24723. }
  24724. case 'load': {
  24725. return `${action} ${s(parameters[0])}`;
  24726. }
  24727. case 'transform': {
  24728. return `${action} ${s(parameters[1])}`;
  24729. }
  24730. case 'shouldTransformCachedModule': {
  24731. return `${action} ${s(parameters[0].id)}`;
  24732. }
  24733. case 'moduleParsed': {
  24734. return `${action} ${s(parameters[0].id)}`;
  24735. }
  24736. }
  24737. return action;
  24738. }
  24739. let handleBeforeExit = null;
  24740. const rejectByPluginDriver = new Map();
  24741. async function catchUnfinishedHookActions(pluginDriver, callback) {
  24742. const emptyEventLoopPromise = new Promise((_, reject) => {
  24743. rejectByPluginDriver.set(pluginDriver, reject);
  24744. if (!handleBeforeExit) {
  24745. // We only ever create a single event listener to avoid max listener and
  24746. // other issues
  24747. handleBeforeExit = () => {
  24748. for (const [pluginDriver, reject] of rejectByPluginDriver) {
  24749. const unfulfilledActions = pluginDriver.getUnfulfilledHookActions();
  24750. reject(new Error(`Unexpected early exit. This happens when Promises returned by plugins cannot resolve. Unfinished hook action(s) on exit:\n` +
  24751. [...unfulfilledActions].map(formatAction).join('\n')));
  24752. }
  24753. };
  24754. process$1.once('beforeExit', handleBeforeExit);
  24755. }
  24756. });
  24757. try {
  24758. return await Promise.race([callback(), emptyEventLoopPromise]);
  24759. }
  24760. finally {
  24761. rejectByPluginDriver.delete(pluginDriver);
  24762. if (rejectByPluginDriver.size === 0) {
  24763. process$1.off('beforeExit', handleBeforeExit);
  24764. handleBeforeExit = null;
  24765. }
  24766. }
  24767. }
  24768. const leftCurlyBrace = "{".charCodeAt(0);
  24769. const space = " ".charCodeAt(0);
  24770. const keyword = "assert";
  24771. const FUNC_STATEMENT = 1, FUNC_NULLABLE_ID = 4;
  24772. function importAssertions(Parser) {
  24773. // Use supplied version acorn version if present, to avoid
  24774. // reference mismatches due to different acorn versions. This
  24775. // allows this plugin to be used with Rollup which supplies
  24776. // its own internal version of acorn and thereby sidesteps
  24777. // the package manager.
  24778. const acorn = Parser.acorn || _acorn;
  24779. const { tokTypes: tt, TokenType } = acorn;
  24780. return class extends Parser {
  24781. constructor(...args) {
  24782. super(...args);
  24783. this.assertToken = new TokenType(keyword);
  24784. }
  24785. _codeAt(i) {
  24786. return this.input.charCodeAt(i);
  24787. }
  24788. _eat(t) {
  24789. if (this.type !== t) {
  24790. this.unexpected();
  24791. }
  24792. this.next();
  24793. }
  24794. readToken(code) {
  24795. let i = 0;
  24796. for (; i < keyword.length; i++) {
  24797. if (this._codeAt(this.pos + i) !== keyword.charCodeAt(i)) {
  24798. return super.readToken(code);
  24799. }
  24800. }
  24801. // ensure that the keyword is at the correct location
  24802. // ie `assert{...` or `assert {...`
  24803. for (;; i++) {
  24804. if (this._codeAt(this.pos + i) === leftCurlyBrace) {
  24805. // Found '{'
  24806. break;
  24807. } else if (this._codeAt(this.pos + i) === space) {
  24808. // white space is allowed between `assert` and `{`, so continue.
  24809. continue;
  24810. } else {
  24811. return super.readToken(code);
  24812. }
  24813. }
  24814. // If we're inside a dynamic import expression we'll parse
  24815. // the `assert` keyword as a standard object property name
  24816. // ie `import(""./foo.json", { assert: { type: "json" } })`
  24817. if (this.type.label === "{") {
  24818. return super.readToken(code);
  24819. }
  24820. this.pos += keyword.length;
  24821. return this.finishToken(this.assertToken);
  24822. }
  24823. parseDynamicImport(node) {
  24824. this.next(); // skip `(`
  24825. // Parse node.source.
  24826. node.source = this.parseMaybeAssign();
  24827. if (this.eat(tt.comma)) {
  24828. const obj = this.parseObj(false);
  24829. node.arguments = [obj];
  24830. }
  24831. this._eat(tt.parenR);
  24832. return this.finishNode(node, "ImportExpression");
  24833. }
  24834. // ported from acorn/src/statement.js pp.parseExport
  24835. parseExport(node, exports) {
  24836. this.next();
  24837. // export * from '...'
  24838. if (this.eat(tt.star)) {
  24839. if (this.options.ecmaVersion >= 11) {
  24840. if (this.eatContextual("as")) {
  24841. node.exported = this.parseIdent(true);
  24842. this.checkExport(exports, node.exported.name, this.lastTokStart);
  24843. } else {
  24844. node.exported = null;
  24845. }
  24846. }
  24847. this.expectContextual("from");
  24848. if (this.type !== tt.string) { this.unexpected(); }
  24849. node.source = this.parseExprAtom();
  24850. if (this.type === this.assertToken || this.type === tt._with) {
  24851. this.next();
  24852. const assertions = this.parseImportAssertions();
  24853. if (assertions) {
  24854. node.assertions = assertions;
  24855. }
  24856. }
  24857. this.semicolon();
  24858. return this.finishNode(node, "ExportAllDeclaration")
  24859. }
  24860. if (this.eat(tt._default)) { // export default ...
  24861. this.checkExport(exports, "default", this.lastTokStart);
  24862. var isAsync;
  24863. if (this.type === tt._function || (isAsync = this.isAsyncFunction())) {
  24864. var fNode = this.startNode();
  24865. this.next();
  24866. if (isAsync) { this.next(); }
  24867. node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync);
  24868. } else if (this.type === tt._class) {
  24869. var cNode = this.startNode();
  24870. node.declaration = this.parseClass(cNode, "nullableID");
  24871. } else {
  24872. node.declaration = this.parseMaybeAssign();
  24873. this.semicolon();
  24874. }
  24875. return this.finishNode(node, "ExportDefaultDeclaration")
  24876. }
  24877. // export var|const|let|function|class ...
  24878. if (this.shouldParseExportStatement()) {
  24879. node.declaration = this.parseStatement(null);
  24880. if (node.declaration.type === "VariableDeclaration")
  24881. { this.checkVariableExport(exports, node.declaration.declarations); }
  24882. else
  24883. { this.checkExport(exports, node.declaration.id.name, node.declaration.id.start); }
  24884. node.specifiers = [];
  24885. node.source = null;
  24886. } else { // export { x, y as z } [from '...']
  24887. node.declaration = null;
  24888. node.specifiers = this.parseExportSpecifiers(exports);
  24889. if (this.eatContextual("from")) {
  24890. if (this.type !== tt.string) { this.unexpected(); }
  24891. node.source = this.parseExprAtom();
  24892. if (this.type === this.assertToken || this.type === tt._with) {
  24893. this.next();
  24894. const assertions = this.parseImportAssertions();
  24895. if (assertions) {
  24896. node.assertions = assertions;
  24897. }
  24898. }
  24899. } else {
  24900. for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
  24901. // check for keywords used as local names
  24902. var spec = list[i];
  24903. this.checkUnreserved(spec.local);
  24904. // check if export is defined
  24905. this.checkLocalExport(spec.local);
  24906. }
  24907. node.source = null;
  24908. }
  24909. this.semicolon();
  24910. }
  24911. return this.finishNode(node, "ExportNamedDeclaration")
  24912. }
  24913. parseImport(node) {
  24914. this.next();
  24915. // import '...'
  24916. if (this.type === tt.string) {
  24917. node.specifiers = [];
  24918. node.source = this.parseExprAtom();
  24919. } else {
  24920. node.specifiers = this.parseImportSpecifiers();
  24921. this.expectContextual("from");
  24922. node.source =
  24923. this.type === tt.string ? this.parseExprAtom() : this.unexpected();
  24924. }
  24925. if (this.type === this.assertToken || this.type == tt._with) {
  24926. this.next();
  24927. const assertions = this.parseImportAssertions();
  24928. if (assertions) {
  24929. node.assertions = assertions;
  24930. }
  24931. }
  24932. this.semicolon();
  24933. return this.finishNode(node, "ImportDeclaration");
  24934. }
  24935. parseImportAssertions() {
  24936. this._eat(tt.braceL);
  24937. const attrs = this.parseAssertEntries();
  24938. this._eat(tt.braceR);
  24939. return attrs;
  24940. }
  24941. parseAssertEntries() {
  24942. const attrs = [];
  24943. const attrNames = new Set();
  24944. do {
  24945. if (this.type === tt.braceR) {
  24946. break;
  24947. }
  24948. const node = this.startNode();
  24949. // parse AssertionKey : IdentifierName, StringLiteral
  24950. let assertionKeyNode;
  24951. if (this.type === tt.string) {
  24952. assertionKeyNode = this.parseLiteral(this.value);
  24953. } else {
  24954. assertionKeyNode = this.parseIdent(true);
  24955. }
  24956. this.next();
  24957. node.key = assertionKeyNode;
  24958. // check if we already have an entry for an attribute
  24959. // if a duplicate entry is found, throw an error
  24960. // for now this logic will come into play only when someone declares `type` twice
  24961. if (attrNames.has(node.key.name)) {
  24962. this.raise(this.pos, "Duplicated key in assertions");
  24963. }
  24964. attrNames.add(node.key.name);
  24965. if (this.type !== tt.string) {
  24966. this.raise(
  24967. this.pos,
  24968. "Only string is supported as an assertion value"
  24969. );
  24970. }
  24971. node.value = this.parseLiteral(this.value);
  24972. attrs.push(this.finishNode(node, "ImportAttribute"));
  24973. } while (this.eat(tt.comma));
  24974. return attrs;
  24975. }
  24976. };
  24977. }
  24978. async function normalizeInputOptions(config, watchMode) {
  24979. // These are options that may trigger special warnings or behaviour later
  24980. // if the user did not select an explicit value
  24981. const unsetOptions = new Set();
  24982. const context = config.context ?? 'undefined';
  24983. const plugins = await normalizePluginOption(config.plugins);
  24984. const logLevel = config.logLevel || LOGLEVEL_INFO;
  24985. const onLog = getLogger(plugins, getOnLog(config, logLevel), watchMode, logLevel);
  24986. const strictDeprecations = config.strictDeprecations || false;
  24987. const maxParallelFileOps = getMaxParallelFileOps(config, onLog, strictDeprecations);
  24988. const options = {
  24989. acorn: getAcorn(config),
  24990. acornInjectPlugins: getAcornInjectPlugins(config),
  24991. cache: getCache(config),
  24992. context,
  24993. experimentalCacheExpiry: config.experimentalCacheExpiry ?? 10,
  24994. experimentalLogSideEffects: config.experimentalLogSideEffects || false,
  24995. external: getIdMatcher(config.external),
  24996. inlineDynamicImports: getInlineDynamicImports$1(config, onLog, strictDeprecations),
  24997. input: getInput(config),
  24998. logLevel,
  24999. makeAbsoluteExternalsRelative: config.makeAbsoluteExternalsRelative ?? 'ifRelativeSource',
  25000. manualChunks: getManualChunks$1(config, onLog, strictDeprecations),
  25001. maxParallelFileOps,
  25002. maxParallelFileReads: maxParallelFileOps,
  25003. moduleContext: getModuleContext(config, context),
  25004. onLog,
  25005. onwarn: warning => onLog(LOGLEVEL_WARN, warning),
  25006. perf: config.perf || false,
  25007. plugins,
  25008. preserveEntrySignatures: config.preserveEntrySignatures ?? 'exports-only',
  25009. preserveModules: getPreserveModules$1(config, onLog, strictDeprecations),
  25010. preserveSymlinks: config.preserveSymlinks || false,
  25011. shimMissingExports: config.shimMissingExports || false,
  25012. strictDeprecations,
  25013. treeshake: getTreeshake(config)
  25014. };
  25015. warnUnknownOptions(config, [...Object.keys(options), 'watch'], 'input options', onLog, /^(output)$/);
  25016. return { options, unsetOptions };
  25017. }
  25018. const getAcorn = (config) => ({
  25019. ecmaVersion: 'latest',
  25020. sourceType: 'module',
  25021. ...config.acorn
  25022. });
  25023. const getAcornInjectPlugins = (config) => [
  25024. importAssertions,
  25025. ...ensureArray$1(config.acornInjectPlugins)
  25026. ];
  25027. const getCache = (config) => config.cache === true // `true` is the default
  25028. ? undefined
  25029. : config.cache?.cache || config.cache;
  25030. const getIdMatcher = (option) => {
  25031. if (option === true) {
  25032. return () => true;
  25033. }
  25034. if (typeof option === 'function') {
  25035. return (id, ...parameters) => (!id.startsWith('\0') && option(id, ...parameters)) || false;
  25036. }
  25037. if (option) {
  25038. const ids = new Set();
  25039. const matchers = [];
  25040. for (const value of ensureArray$1(option)) {
  25041. if (value instanceof RegExp) {
  25042. matchers.push(value);
  25043. }
  25044. else {
  25045. ids.add(value);
  25046. }
  25047. }
  25048. return (id, ..._arguments) => ids.has(id) || matchers.some(matcher => matcher.test(id));
  25049. }
  25050. return () => false;
  25051. };
  25052. const getInlineDynamicImports$1 = (config, log, strictDeprecations) => {
  25053. const configInlineDynamicImports = config.inlineDynamicImports;
  25054. if (configInlineDynamicImports) {
  25055. warnDeprecationWithOptions('The "inlineDynamicImports" option is deprecated. Use the "output.inlineDynamicImports" option instead.', URL_OUTPUT_INLINEDYNAMICIMPORTS, true, log, strictDeprecations);
  25056. }
  25057. return configInlineDynamicImports;
  25058. };
  25059. const getInput = (config) => {
  25060. const configInput = config.input;
  25061. return configInput == null ? [] : typeof configInput === 'string' ? [configInput] : configInput;
  25062. };
  25063. const getManualChunks$1 = (config, log, strictDeprecations) => {
  25064. const configManualChunks = config.manualChunks;
  25065. if (configManualChunks) {
  25066. warnDeprecationWithOptions('The "manualChunks" option is deprecated. Use the "output.manualChunks" option instead.', URL_OUTPUT_MANUALCHUNKS, true, log, strictDeprecations);
  25067. }
  25068. return configManualChunks;
  25069. };
  25070. const getMaxParallelFileOps = (config, log, strictDeprecations) => {
  25071. const maxParallelFileReads = config.maxParallelFileReads;
  25072. if (typeof maxParallelFileReads === 'number') {
  25073. warnDeprecationWithOptions('The "maxParallelFileReads" option is deprecated. Use the "maxParallelFileOps" option instead.', URL_MAXPARALLELFILEOPS, true, log, strictDeprecations);
  25074. }
  25075. const maxParallelFileOps = config.maxParallelFileOps ?? maxParallelFileReads;
  25076. if (typeof maxParallelFileOps === 'number') {
  25077. if (maxParallelFileOps <= 0)
  25078. return Infinity;
  25079. return maxParallelFileOps;
  25080. }
  25081. return 20;
  25082. };
  25083. const getModuleContext = (config, context) => {
  25084. const configModuleContext = config.moduleContext;
  25085. if (typeof configModuleContext === 'function') {
  25086. return id => configModuleContext(id) ?? context;
  25087. }
  25088. if (configModuleContext) {
  25089. const contextByModuleId = Object.create(null);
  25090. for (const [key, moduleContext] of Object.entries(configModuleContext)) {
  25091. contextByModuleId[node_path.resolve(key)] = moduleContext;
  25092. }
  25093. return id => contextByModuleId[id] ?? context;
  25094. }
  25095. return () => context;
  25096. };
  25097. const getPreserveModules$1 = (config, log, strictDeprecations) => {
  25098. const configPreserveModules = config.preserveModules;
  25099. if (configPreserveModules) {
  25100. warnDeprecationWithOptions('The "preserveModules" option is deprecated. Use the "output.preserveModules" option instead.', URL_OUTPUT_PRESERVEMODULES, true, log, strictDeprecations);
  25101. }
  25102. return configPreserveModules;
  25103. };
  25104. const getTreeshake = (config) => {
  25105. const configTreeshake = config.treeshake;
  25106. if (configTreeshake === false) {
  25107. return false;
  25108. }
  25109. const configWithPreset = getOptionWithPreset(config.treeshake, treeshakePresets, 'treeshake', URL_TREESHAKE, 'false, true, ');
  25110. return {
  25111. annotations: configWithPreset.annotations !== false,
  25112. correctVarValueBeforeDeclaration: configWithPreset.correctVarValueBeforeDeclaration === true,
  25113. manualPureFunctions: configWithPreset.manualPureFunctions ?? EMPTY_ARRAY,
  25114. moduleSideEffects: getHasModuleSideEffects(configWithPreset.moduleSideEffects),
  25115. propertyReadSideEffects: configWithPreset.propertyReadSideEffects === 'always'
  25116. ? 'always'
  25117. : configWithPreset.propertyReadSideEffects !== false,
  25118. tryCatchDeoptimization: configWithPreset.tryCatchDeoptimization !== false,
  25119. unknownGlobalSideEffects: configWithPreset.unknownGlobalSideEffects !== false
  25120. };
  25121. };
  25122. const getHasModuleSideEffects = (moduleSideEffectsOption) => {
  25123. if (typeof moduleSideEffectsOption === 'boolean') {
  25124. return () => moduleSideEffectsOption;
  25125. }
  25126. if (moduleSideEffectsOption === 'no-external') {
  25127. return (_id, external) => !external;
  25128. }
  25129. if (typeof moduleSideEffectsOption === 'function') {
  25130. return (id, external) => id.startsWith('\0') ? true : moduleSideEffectsOption(id, external) !== false;
  25131. }
  25132. if (Array.isArray(moduleSideEffectsOption)) {
  25133. const ids = new Set(moduleSideEffectsOption);
  25134. return id => ids.has(id);
  25135. }
  25136. if (moduleSideEffectsOption) {
  25137. error(logInvalidOption('treeshake.moduleSideEffects', URL_TREESHAKE_MODULESIDEEFFECTS, 'please use one of false, "no-external", a function or an array'));
  25138. }
  25139. return () => true;
  25140. };
  25141. // https://datatracker.ietf.org/doc/html/rfc2396
  25142. // eslint-disable-next-line no-control-regex
  25143. const INVALID_CHAR_REGEX = /[\u0000-\u001F"#$&*+,:;<=>?[\]^`{|}\u007F]/g;
  25144. const DRIVE_LETTER_REGEX = /^[a-z]:/i;
  25145. function sanitizeFileName(name) {
  25146. const match = DRIVE_LETTER_REGEX.exec(name);
  25147. const driveLetter = match ? match[0] : '';
  25148. // A `:` is only allowed as part of a windows drive letter (ex: C:\foo)
  25149. // Otherwise, avoid them because they can refer to NTFS alternate data streams.
  25150. return driveLetter + name.slice(driveLetter.length).replace(INVALID_CHAR_REGEX, '_');
  25151. }
  25152. async function normalizeOutputOptions(config, inputOptions, unsetInputOptions) {
  25153. // These are options that may trigger special warnings or behaviour later
  25154. // if the user did not select an explicit value
  25155. const unsetOptions = new Set(unsetInputOptions);
  25156. const compact = config.compact || false;
  25157. const format = getFormat(config);
  25158. const inlineDynamicImports = getInlineDynamicImports(config, inputOptions);
  25159. const preserveModules = getPreserveModules(config, inlineDynamicImports, inputOptions);
  25160. const file = getFile(config, preserveModules, inputOptions);
  25161. const preferConst = getPreferConst(config, inputOptions);
  25162. const generatedCode = getGeneratedCode(config, preferConst);
  25163. const outputOptions = {
  25164. amd: getAmd(config),
  25165. assetFileNames: config.assetFileNames ?? 'assets/[name]-[hash][extname]',
  25166. banner: getAddon(config, 'banner'),
  25167. chunkFileNames: config.chunkFileNames ?? '[name]-[hash].js',
  25168. compact,
  25169. dir: getDir(config, file),
  25170. dynamicImportFunction: getDynamicImportFunction(config, inputOptions, format),
  25171. dynamicImportInCjs: config.dynamicImportInCjs ?? true,
  25172. entryFileNames: getEntryFileNames(config, unsetOptions),
  25173. esModule: config.esModule ?? 'if-default-prop',
  25174. experimentalDeepDynamicChunkOptimization: getExperimentalDeepDynamicChunkOptimization(config, inputOptions),
  25175. experimentalMinChunkSize: config.experimentalMinChunkSize ?? 1,
  25176. exports: getExports(config, unsetOptions),
  25177. extend: config.extend || false,
  25178. externalImportAssertions: config.externalImportAssertions ?? true,
  25179. externalLiveBindings: config.externalLiveBindings ?? true,
  25180. file,
  25181. footer: getAddon(config, 'footer'),
  25182. format,
  25183. freeze: config.freeze ?? true,
  25184. generatedCode,
  25185. globals: config.globals || {},
  25186. hoistTransitiveImports: config.hoistTransitiveImports ?? true,
  25187. indent: getIndent(config, compact),
  25188. inlineDynamicImports,
  25189. interop: getInterop(config),
  25190. intro: getAddon(config, 'intro'),
  25191. manualChunks: getManualChunks(config, inlineDynamicImports, preserveModules, inputOptions),
  25192. minifyInternalExports: getMinifyInternalExports(config, format, compact),
  25193. name: config.name,
  25194. namespaceToStringTag: getNamespaceToStringTag(config, generatedCode, inputOptions),
  25195. noConflict: config.noConflict || false,
  25196. outro: getAddon(config, 'outro'),
  25197. paths: config.paths || {},
  25198. plugins: await normalizePluginOption(config.plugins),
  25199. preferConst,
  25200. preserveModules,
  25201. preserveModulesRoot: getPreserveModulesRoot(config),
  25202. sanitizeFileName: typeof config.sanitizeFileName === 'function'
  25203. ? config.sanitizeFileName
  25204. : config.sanitizeFileName === false
  25205. ? id => id
  25206. : sanitizeFileName,
  25207. sourcemap: config.sourcemap || false,
  25208. sourcemapBaseUrl: getSourcemapBaseUrl(config),
  25209. sourcemapExcludeSources: config.sourcemapExcludeSources || false,
  25210. sourcemapFile: config.sourcemapFile,
  25211. sourcemapFileNames: getSourcemapFileNames(config, unsetOptions),
  25212. sourcemapIgnoreList: typeof config.sourcemapIgnoreList === 'function'
  25213. ? config.sourcemapIgnoreList
  25214. : config.sourcemapIgnoreList === false
  25215. ? () => false
  25216. : relativeSourcePath => relativeSourcePath.includes('node_modules'),
  25217. sourcemapPathTransform: config.sourcemapPathTransform,
  25218. strict: config.strict ?? true,
  25219. systemNullSetters: config.systemNullSetters ?? true,
  25220. validate: config.validate || false
  25221. };
  25222. warnUnknownOptions(config, Object.keys(outputOptions), 'output options', inputOptions.onLog);
  25223. return { options: outputOptions, unsetOptions };
  25224. }
  25225. const getFile = (config, preserveModules, inputOptions) => {
  25226. const { file } = config;
  25227. if (typeof file === 'string') {
  25228. if (preserveModules) {
  25229. return error(logInvalidOption('output.file', URL_OUTPUT_DIR, 'you must set "output.dir" instead of "output.file" when using the "output.preserveModules" option'));
  25230. }
  25231. if (!Array.isArray(inputOptions.input))
  25232. return error(logInvalidOption('output.file', URL_OUTPUT_DIR, 'you must set "output.dir" instead of "output.file" when providing named inputs'));
  25233. }
  25234. return file;
  25235. };
  25236. const getFormat = (config) => {
  25237. const configFormat = config.format;
  25238. switch (configFormat) {
  25239. case undefined:
  25240. case 'es':
  25241. case 'esm':
  25242. case 'module': {
  25243. return 'es';
  25244. }
  25245. case 'cjs':
  25246. case 'commonjs': {
  25247. return 'cjs';
  25248. }
  25249. case 'system':
  25250. case 'systemjs': {
  25251. return 'system';
  25252. }
  25253. case 'amd':
  25254. case 'iife':
  25255. case 'umd': {
  25256. return configFormat;
  25257. }
  25258. default: {
  25259. return error(logInvalidOption('output.format', URL_OUTPUT_FORMAT, `Valid values are "amd", "cjs", "system", "es", "iife" or "umd"`, configFormat));
  25260. }
  25261. }
  25262. };
  25263. const getInlineDynamicImports = (config, inputOptions) => {
  25264. const inlineDynamicImports = (config.inlineDynamicImports ?? inputOptions.inlineDynamicImports) || false;
  25265. const { input } = inputOptions;
  25266. if (inlineDynamicImports && (Array.isArray(input) ? input : Object.keys(input)).length > 1) {
  25267. return error(logInvalidOption('output.inlineDynamicImports', URL_OUTPUT_INLINEDYNAMICIMPORTS, 'multiple inputs are not supported when "output.inlineDynamicImports" is true'));
  25268. }
  25269. return inlineDynamicImports;
  25270. };
  25271. const getPreserveModules = (config, inlineDynamicImports, inputOptions) => {
  25272. const preserveModules = (config.preserveModules ?? inputOptions.preserveModules) || false;
  25273. if (preserveModules) {
  25274. if (inlineDynamicImports) {
  25275. return error(logInvalidOption('output.inlineDynamicImports', URL_OUTPUT_INLINEDYNAMICIMPORTS, `this option is not supported for "output.preserveModules"`));
  25276. }
  25277. if (inputOptions.preserveEntrySignatures === false) {
  25278. return error(logInvalidOption('preserveEntrySignatures', URL_PRESERVEENTRYSIGNATURES, 'setting this option to false is not supported for "output.preserveModules"'));
  25279. }
  25280. }
  25281. return preserveModules;
  25282. };
  25283. const getPreferConst = (config, inputOptions) => {
  25284. const configPreferConst = config.preferConst;
  25285. if (configPreferConst != null) {
  25286. warnDeprecation(`The "output.preferConst" option is deprecated. Use the "output.generatedCode.constBindings" option instead.`, URL_OUTPUT_GENERATEDCODE_CONSTBINDINGS, true, inputOptions);
  25287. }
  25288. return !!configPreferConst;
  25289. };
  25290. const getPreserveModulesRoot = (config) => {
  25291. const { preserveModulesRoot } = config;
  25292. if (preserveModulesRoot === null || preserveModulesRoot === undefined) {
  25293. return undefined;
  25294. }
  25295. return node_path.resolve(preserveModulesRoot);
  25296. };
  25297. const getAmd = (config) => {
  25298. const mergedOption = {
  25299. autoId: false,
  25300. basePath: '',
  25301. define: 'define',
  25302. forceJsExtensionForImports: false,
  25303. ...config.amd
  25304. };
  25305. if ((mergedOption.autoId || mergedOption.basePath) && mergedOption.id) {
  25306. return error(logInvalidOption('output.amd.id', URL_OUTPUT_AMD_ID, 'this option cannot be used together with "output.amd.autoId"/"output.amd.basePath"'));
  25307. }
  25308. if (mergedOption.basePath && !mergedOption.autoId) {
  25309. return error(logInvalidOption('output.amd.basePath', URL_OUTPUT_AMD_BASEPATH, 'this option only works with "output.amd.autoId"'));
  25310. }
  25311. return mergedOption.autoId
  25312. ? {
  25313. autoId: true,
  25314. basePath: mergedOption.basePath,
  25315. define: mergedOption.define,
  25316. forceJsExtensionForImports: mergedOption.forceJsExtensionForImports
  25317. }
  25318. : {
  25319. autoId: false,
  25320. define: mergedOption.define,
  25321. forceJsExtensionForImports: mergedOption.forceJsExtensionForImports,
  25322. id: mergedOption.id
  25323. };
  25324. };
  25325. const getAddon = (config, name) => {
  25326. const configAddon = config[name];
  25327. if (typeof configAddon === 'function') {
  25328. return configAddon;
  25329. }
  25330. return () => configAddon || '';
  25331. };
  25332. // eslint-disable-next-line unicorn/prevent-abbreviations
  25333. const getDir = (config, file) => {
  25334. const { dir } = config;
  25335. if (typeof dir === 'string' && typeof file === 'string') {
  25336. 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'));
  25337. }
  25338. return dir;
  25339. };
  25340. const getDynamicImportFunction = (config, inputOptions, format) => {
  25341. const configDynamicImportFunction = config.dynamicImportFunction;
  25342. if (configDynamicImportFunction) {
  25343. warnDeprecation(`The "output.dynamicImportFunction" option is deprecated. Use the "renderDynamicImport" plugin hook instead.`, URL_RENDERDYNAMICIMPORT, true, inputOptions);
  25344. if (format !== 'es') {
  25345. inputOptions.onLog(LOGLEVEL_WARN, logInvalidOption('output.dynamicImportFunction', URL_OUTPUT_DYNAMICIMPORTFUNCTION, 'this option is ignored for formats other than "es"'));
  25346. }
  25347. }
  25348. return configDynamicImportFunction;
  25349. };
  25350. const getEntryFileNames = (config, unsetOptions) => {
  25351. const configEntryFileNames = config.entryFileNames;
  25352. if (configEntryFileNames == null) {
  25353. unsetOptions.add('entryFileNames');
  25354. }
  25355. return configEntryFileNames ?? '[name].js';
  25356. };
  25357. function getExperimentalDeepDynamicChunkOptimization(config, inputOptions) {
  25358. const configExperimentalDeepDynamicChunkOptimization = config.experimentalDeepDynamicChunkOptimization;
  25359. if (configExperimentalDeepDynamicChunkOptimization != null) {
  25360. 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);
  25361. }
  25362. return configExperimentalDeepDynamicChunkOptimization || false;
  25363. }
  25364. function getExports(config, unsetOptions) {
  25365. const configExports = config.exports;
  25366. if (configExports == null) {
  25367. unsetOptions.add('exports');
  25368. }
  25369. else if (!['default', 'named', 'none', 'auto'].includes(configExports)) {
  25370. return error(logInvalidExportOptionValue(configExports));
  25371. }
  25372. return configExports || 'auto';
  25373. }
  25374. const getGeneratedCode = (config, preferConst) => {
  25375. const configWithPreset = getOptionWithPreset(config.generatedCode, generatedCodePresets, 'output.generatedCode', URL_OUTPUT_GENERATEDCODE, '');
  25376. return {
  25377. arrowFunctions: configWithPreset.arrowFunctions === true,
  25378. constBindings: configWithPreset.constBindings === true || preferConst,
  25379. objectShorthand: configWithPreset.objectShorthand === true,
  25380. reservedNamesAsProps: configWithPreset.reservedNamesAsProps !== false,
  25381. symbols: configWithPreset.symbols === true
  25382. };
  25383. };
  25384. const getIndent = (config, compact) => {
  25385. if (compact) {
  25386. return '';
  25387. }
  25388. const configIndent = config.indent;
  25389. return configIndent === false ? '' : configIndent ?? true;
  25390. };
  25391. const ALLOWED_INTEROP_TYPES = new Set([
  25392. 'compat',
  25393. 'auto',
  25394. 'esModule',
  25395. 'default',
  25396. 'defaultOnly'
  25397. ]);
  25398. const getInterop = (config) => {
  25399. const configInterop = config.interop;
  25400. if (typeof configInterop === 'function') {
  25401. const interopPerId = Object.create(null);
  25402. let defaultInterop = null;
  25403. return id => id === null
  25404. ? defaultInterop || validateInterop((defaultInterop = configInterop(id)))
  25405. : id in interopPerId
  25406. ? interopPerId[id]
  25407. : validateInterop((interopPerId[id] = configInterop(id)));
  25408. }
  25409. return configInterop === undefined ? () => 'default' : () => validateInterop(configInterop);
  25410. };
  25411. const validateInterop = (interop) => {
  25412. if (!ALLOWED_INTEROP_TYPES.has(interop)) {
  25413. return error(logInvalidOption('output.interop', URL_OUTPUT_INTEROP,
  25414. // eslint-disable-next-line unicorn/prefer-spread
  25415. `use one of ${Array.from(ALLOWED_INTEROP_TYPES, value => JSON.stringify(value)).join(', ')}`, interop));
  25416. }
  25417. return interop;
  25418. };
  25419. const getManualChunks = (config, inlineDynamicImports, preserveModules, inputOptions) => {
  25420. const configManualChunks = config.manualChunks || inputOptions.manualChunks;
  25421. if (configManualChunks) {
  25422. if (inlineDynamicImports) {
  25423. return error(logInvalidOption('output.manualChunks', URL_OUTPUT_MANUALCHUNKS, 'this option is not supported for "output.inlineDynamicImports"'));
  25424. }
  25425. if (preserveModules) {
  25426. return error(logInvalidOption('output.manualChunks', URL_OUTPUT_MANUALCHUNKS, 'this option is not supported for "output.preserveModules"'));
  25427. }
  25428. }
  25429. return configManualChunks || {};
  25430. };
  25431. const getMinifyInternalExports = (config, format, compact) => config.minifyInternalExports ?? (compact || format === 'es' || format === 'system');
  25432. const getNamespaceToStringTag = (config, generatedCode, inputOptions) => {
  25433. const configNamespaceToStringTag = config.namespaceToStringTag;
  25434. if (configNamespaceToStringTag != null) {
  25435. warnDeprecation(`The "output.namespaceToStringTag" option is deprecated. Use the "output.generatedCode.symbols" option instead.`, URL_OUTPUT_GENERATEDCODE_SYMBOLS, true, inputOptions);
  25436. return configNamespaceToStringTag;
  25437. }
  25438. return generatedCode.symbols || false;
  25439. };
  25440. const getSourcemapFileNames = (config, unsetOptions) => {
  25441. const configSourcemapFileNames = config.sourcemapFileNames;
  25442. if (configSourcemapFileNames == null) {
  25443. unsetOptions.add('sourcemapFileNames');
  25444. }
  25445. return configSourcemapFileNames;
  25446. };
  25447. const getSourcemapBaseUrl = (config) => {
  25448. const { sourcemapBaseUrl } = config;
  25449. if (sourcemapBaseUrl) {
  25450. if (isValidUrl(sourcemapBaseUrl)) {
  25451. return addTrailingSlashIfMissed(sourcemapBaseUrl);
  25452. }
  25453. return error(logInvalidOption('output.sourcemapBaseUrl', URL_OUTPUT_SOURCEMAPBASEURL, `must be a valid URL, received ${JSON.stringify(sourcemapBaseUrl)}`));
  25454. }
  25455. };
  25456. function rollup(rawInputOptions) {
  25457. return rollupInternal(rawInputOptions, null);
  25458. }
  25459. async function rollupInternal(rawInputOptions, watcher) {
  25460. const { options: inputOptions, unsetOptions: unsetInputOptions } = await getInputOptions(rawInputOptions, watcher !== null);
  25461. initialiseTimers(inputOptions);
  25462. const graph = new Graph(inputOptions, watcher);
  25463. // remove the cache object from the memory after graph creation (cache is not used anymore)
  25464. const useCache = rawInputOptions.cache !== false;
  25465. if (rawInputOptions.cache) {
  25466. inputOptions.cache = undefined;
  25467. rawInputOptions.cache = undefined;
  25468. }
  25469. timeStart('BUILD', 1);
  25470. await catchUnfinishedHookActions(graph.pluginDriver, async () => {
  25471. try {
  25472. timeStart('initialize', 2);
  25473. await graph.pluginDriver.hookParallel('buildStart', [inputOptions]);
  25474. timeEnd('initialize', 2);
  25475. await graph.build();
  25476. }
  25477. catch (error_) {
  25478. const watchFiles = Object.keys(graph.watchFiles);
  25479. if (watchFiles.length > 0) {
  25480. error_.watchFiles = watchFiles;
  25481. }
  25482. await graph.pluginDriver.hookParallel('buildEnd', [error_]);
  25483. await graph.pluginDriver.hookParallel('closeBundle', []);
  25484. throw error_;
  25485. }
  25486. await graph.pluginDriver.hookParallel('buildEnd', []);
  25487. });
  25488. timeEnd('BUILD', 1);
  25489. const result = {
  25490. cache: useCache ? graph.getCache() : undefined,
  25491. async close() {
  25492. if (result.closed)
  25493. return;
  25494. result.closed = true;
  25495. await graph.pluginDriver.hookParallel('closeBundle', []);
  25496. },
  25497. closed: false,
  25498. async generate(rawOutputOptions) {
  25499. if (result.closed)
  25500. return error(logAlreadyClosed());
  25501. return handleGenerateWrite(false, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  25502. },
  25503. watchFiles: Object.keys(graph.watchFiles),
  25504. async write(rawOutputOptions) {
  25505. if (result.closed)
  25506. return error(logAlreadyClosed());
  25507. return handleGenerateWrite(true, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  25508. }
  25509. };
  25510. if (inputOptions.perf)
  25511. result.getTimings = getTimings;
  25512. return result;
  25513. }
  25514. async function getInputOptions(initialInputOptions, watchMode) {
  25515. if (!initialInputOptions) {
  25516. throw new Error('You must supply an options object to rollup');
  25517. }
  25518. const processedInputOptions = await getProcessedInputOptions(initialInputOptions, watchMode);
  25519. const { options, unsetOptions } = await normalizeInputOptions(processedInputOptions, watchMode);
  25520. normalizePlugins(options.plugins, ANONYMOUS_PLUGIN_PREFIX);
  25521. return { options, unsetOptions };
  25522. }
  25523. async function getProcessedInputOptions(inputOptions, watchMode) {
  25524. const plugins = getSortedValidatedPlugins('options', await normalizePluginOption(inputOptions.plugins));
  25525. const logLevel = inputOptions.logLevel || LOGLEVEL_INFO;
  25526. const logger = getLogger(plugins, getOnLog(inputOptions, logLevel), watchMode, logLevel);
  25527. for (const plugin of plugins) {
  25528. const { name, options } = plugin;
  25529. const handler = 'handler' in options ? options.handler : options;
  25530. const processedOptions = await handler.call({
  25531. debug: getLogHandler(LOGLEVEL_DEBUG, 'PLUGIN_LOG', logger, name, logLevel),
  25532. error: (error_) => error(logPluginError(normalizeLog(error_), name, { hook: 'onLog' })),
  25533. info: getLogHandler(LOGLEVEL_INFO, 'PLUGIN_LOG', logger, name, logLevel),
  25534. meta: { rollupVersion: version$1, watchMode },
  25535. warn: getLogHandler(LOGLEVEL_WARN, 'PLUGIN_WARNING', logger, name, logLevel)
  25536. }, inputOptions);
  25537. if (processedOptions) {
  25538. inputOptions = processedOptions;
  25539. }
  25540. }
  25541. return inputOptions;
  25542. }
  25543. function normalizePlugins(plugins, anonymousPrefix) {
  25544. for (const [index, plugin] of plugins.entries()) {
  25545. if (!plugin.name) {
  25546. plugin.name = `${anonymousPrefix}${index + 1}`;
  25547. }
  25548. }
  25549. }
  25550. async function handleGenerateWrite(isWrite, inputOptions, unsetInputOptions, rawOutputOptions, graph) {
  25551. const { options: outputOptions, outputPluginDriver, unsetOptions } = await getOutputOptionsAndPluginDriver(rawOutputOptions, graph.pluginDriver, inputOptions, unsetInputOptions);
  25552. return catchUnfinishedHookActions(outputPluginDriver, async () => {
  25553. const bundle = new Bundle(outputOptions, unsetOptions, inputOptions, outputPluginDriver, graph);
  25554. const generated = await bundle.generate(isWrite);
  25555. if (isWrite) {
  25556. timeStart('WRITE', 1);
  25557. if (!outputOptions.dir && !outputOptions.file) {
  25558. return error(logMissingFileOrDirOption());
  25559. }
  25560. await Promise.all(Object.values(generated).map(chunk => graph.fileOperationQueue.run(() => writeOutputFile(chunk, outputOptions))));
  25561. await outputPluginDriver.hookParallel('writeBundle', [outputOptions, generated]);
  25562. timeEnd('WRITE', 1);
  25563. }
  25564. return createOutput(generated);
  25565. });
  25566. }
  25567. async function getOutputOptionsAndPluginDriver(rawOutputOptions, inputPluginDriver, inputOptions, unsetInputOptions) {
  25568. if (!rawOutputOptions) {
  25569. throw new Error('You must supply an options object');
  25570. }
  25571. const rawPlugins = await normalizePluginOption(rawOutputOptions.plugins);
  25572. normalizePlugins(rawPlugins, ANONYMOUS_OUTPUT_PLUGIN_PREFIX);
  25573. const outputPluginDriver = inputPluginDriver.createOutputPluginDriver(rawPlugins);
  25574. return {
  25575. ...(await getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver)),
  25576. outputPluginDriver
  25577. };
  25578. }
  25579. function getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver) {
  25580. return normalizeOutputOptions(outputPluginDriver.hookReduceArg0Sync('outputOptions', [rawOutputOptions], (outputOptions, result) => result || outputOptions, pluginContext => {
  25581. const emitError = () => pluginContext.error(logCannotEmitFromOptionsHook());
  25582. return {
  25583. ...pluginContext,
  25584. emitFile: emitError,
  25585. setAssetSource: emitError
  25586. };
  25587. }), inputOptions, unsetInputOptions);
  25588. }
  25589. function createOutput(outputBundle) {
  25590. return {
  25591. output: Object.values(outputBundle).filter(outputFile => Object.keys(outputFile).length > 0).sort((outputFileA, outputFileB) => getSortingFileType(outputFileA) - getSortingFileType(outputFileB))
  25592. };
  25593. }
  25594. var SortingFileType;
  25595. (function (SortingFileType) {
  25596. SortingFileType[SortingFileType["ENTRY_CHUNK"] = 0] = "ENTRY_CHUNK";
  25597. SortingFileType[SortingFileType["SECONDARY_CHUNK"] = 1] = "SECONDARY_CHUNK";
  25598. SortingFileType[SortingFileType["ASSET"] = 2] = "ASSET";
  25599. })(SortingFileType || (SortingFileType = {}));
  25600. function getSortingFileType(file) {
  25601. if (file.type === 'asset') {
  25602. return SortingFileType.ASSET;
  25603. }
  25604. if (file.isEntry) {
  25605. return SortingFileType.ENTRY_CHUNK;
  25606. }
  25607. return SortingFileType.SECONDARY_CHUNK;
  25608. }
  25609. async function writeOutputFile(outputFile, outputOptions) {
  25610. const fileName = node_path.resolve(outputOptions.dir || node_path.dirname(outputOptions.file), outputFile.fileName);
  25611. // 'recursive: true' does not throw if the folder structure, or parts of it, already exist
  25612. await promises.mkdir(node_path.dirname(fileName), { recursive: true });
  25613. return promises.writeFile(fileName, outputFile.type === 'asset' ? outputFile.source : outputFile.code);
  25614. }
  25615. /**
  25616. * Auxiliary function for defining rollup configuration
  25617. * Mainly to facilitate IDE code prompts, after all, export default does not
  25618. * prompt, even if you add @type annotations, it is not accurate
  25619. * @param options
  25620. */
  25621. function defineConfig(options) {
  25622. return options;
  25623. }
  25624. exports.LOGLEVEL_DEBUG = LOGLEVEL_DEBUG;
  25625. exports.LOGLEVEL_WARN = LOGLEVEL_WARN;
  25626. exports.URL_AVOIDING_EVAL = URL_AVOIDING_EVAL;
  25627. exports.URL_NAME_IS_NOT_EXPORTED = URL_NAME_IS_NOT_EXPORTED;
  25628. exports.URL_OUTPUT_EXPORTS = URL_OUTPUT_EXPORTS;
  25629. exports.URL_OUTPUT_GLOBALS = URL_OUTPUT_GLOBALS;
  25630. exports.URL_SOURCEMAP_IS_LIKELY_TO_BE_INCORRECT = URL_SOURCEMAP_IS_LIKELY_TO_BE_INCORRECT;
  25631. exports.URL_THIS_IS_UNDEFINED = URL_THIS_IS_UNDEFINED;
  25632. exports.URL_TREATING_MODULE_AS_EXTERNAL_DEPENDENCY = URL_TREATING_MODULE_AS_EXTERNAL_DEPENDENCY;
  25633. exports.URL_WATCH = URL_WATCH;
  25634. exports.blue = blue;
  25635. exports.bold = bold;
  25636. exports.commandAliases = commandAliases;
  25637. exports.createFilter = createFilter;
  25638. exports.cyan = cyan$1;
  25639. exports.cyan$1 = cyan;
  25640. exports.defineConfig = defineConfig;
  25641. exports.ensureArray = ensureArray$1;
  25642. exports.error = error;
  25643. exports.getAliasName = getAliasName;
  25644. exports.getAugmentedNamespace = getAugmentedNamespace;
  25645. exports.getNewArray = getNewArray;
  25646. exports.getOrCreate = getOrCreate;
  25647. exports.getRollupUrl = getRollupUrl;
  25648. exports.gray = gray;
  25649. exports.green = green;
  25650. exports.handleError = handleError;
  25651. exports.isWatchEnabled = isWatchEnabled;
  25652. exports.logCannotBundleConfigAsEsm = logCannotBundleConfigAsEsm;
  25653. exports.logCannotLoadConfigAsCjs = logCannotLoadConfigAsCjs;
  25654. exports.logCannotLoadConfigAsEsm = logCannotLoadConfigAsEsm;
  25655. exports.logDuplicateImportOptions = logDuplicateImportOptions;
  25656. exports.logFailAfterWarnings = logFailAfterWarnings;
  25657. exports.logInvalidOption = logInvalidOption;
  25658. exports.logMissingConfig = logMissingConfig;
  25659. exports.logMissingExternalConfig = logMissingExternalConfig;
  25660. exports.logOnlyInlineSourcemapsForStdout = logOnlyInlineSourcemapsForStdout;
  25661. exports.mergeOptions = mergeOptions;
  25662. exports.normalizePluginOption = normalizePluginOption;
  25663. exports.picomatch = picomatch;
  25664. exports.printQuotedStringList = printQuotedStringList;
  25665. exports.relativeId = relativeId;
  25666. exports.rollup = rollup;
  25667. exports.rollupInternal = rollupInternal;
  25668. exports.stderr = stderr;
  25669. exports.underline = underline;
  25670. exports.version = version$1;
  25671. exports.yellow = yellow;
  25672. //# sourceMappingURL=rollup.js.map