node-entry.js 922 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463
  1. /*
  2. @license
  3. Rollup.js v4.60.1
  4. Mon, 30 Mar 2026 04:32:12 GMT - commit ae871d762f6bbeb4320d28fe179211168f27a434
  5. https://github.com/rollup/rollup
  6. Released under the MIT License.
  7. */
  8. import { EMPTY_OBJECT, ExportDefaultDeclaration as ExportDefaultDeclaration$1, CallExpression as CallExpression$1, EMPTY_ARRAY, LOGLEVEL_WARN, logUnusedExternalImports, ANNOTATION_KEY, INVALID_ANNOTATION_KEY, ExpressionStatement as ExpressionStatement$1, AwaitExpression as AwaitExpression$1, MemberExpression as MemberExpression$1, Identifier as Identifier$1, FunctionExpression as FunctionExpression$1, ArrowFunctionExpression as ArrowFunctionExpression$1, ObjectExpression as ObjectExpression$1, Property as Property$1, Program as Program$1, logIllegalImportReassignment, BLANK, logRedeclarationError, StaticBlock as StaticBlock$1, CatchClause as CatchClause$1, logDuplicateArgumentNameError, logModuleLevelDirective, ReturnStatement as ReturnStatement$1, VariableDeclarator as VariableDeclarator$1, logMissingExport, normalize, getImportPath, error, logSourcePhaseFormatUnsupported, logMissingNodeBuiltins, logReservedNamespace, logIllegalIdentifierAsName, logMissingNameOptionForIifeExport, logMissingNameOptionForUmdExport, RestElement as RestElement$1, logConstVariableReassignError, EMPTY_SET, logCannotCallNamespace, logEval, BlockStatement as BlockStatement$1, getRollupError, logModuleParseError, logParseError, LOGLEVEL_INFO, logFirstSideEffect, locate, logInvalidAnnotation, logThisIsUndefined, getAstBuffer, convertAnnotations, FIXED_STRINGS, convertNode as convertNode$1, logImportAttributeIsInvalid, logImportOptionsAreInvalid, logMissingEntryExport, logSyntheticNamedExportsNeedNamespaceExport, logDuplicateExportError, logInvalidSourcemapForError, augmentCodeLocation, logInconsistentImportAttributes, logMissingJsxExport, logNamespaceConflict, logAmbiguousExternalNamespaces, logShimmedExport, parseAst, TemplateLiteral as TemplateLiteral$1, Literal as Literal$1, logCircularReexport, logInvalidFormatForTopLevelAwait, logAddonNotGenerated, logIncompatibleExportOptionValue, logMixedExport, logFailedValidation, isPathFragment, logCyclicCrossChunkReexport, getAliasName, logUnexpectedNamedImport, isAbsolute as isAbsolute$1, relative as relative$1, logUnexpectedNamespaceReexport, logEmptyChunk, logMissingGlobalName, logOptimizeChunkStatus, logSourcemapBroken, logConflictingSourcemapSources, logChunkInvalid, logInvalidOption, URL_OUTPUT_FORMAT, URL_OUTPUT_DIR, URL_OUTPUT_SOURCEMAPFILE, URL_OUTPUT_AMD_ID, logFileNameOutsideOutputDirectory, logCannotAssignModuleToChunk, logCircularChunk, logUnknownOption, printQuotedStringList, LOGLEVEL_ERROR, logLevelPriority, LOGLEVEL_DEBUG, logAnonymousPluginCache, logDuplicatePluginName, logInvalidSetAssetSourceCall, logPluginError, logNoTransformMapOrAstWithoutCode, warnDeprecation, URL_TRANSFORM, relativeId, logBadLoader, logNonExternalSourcePhaseImport, logInternalIdCannotBeExternal, isRelative, logUnresolvedImport, logUnresolvedImportTreatedAsExternal, logExternalSyntheticExports, logUnresolvedEntry, logUnresolvedImplicitDependant, logExternalModulesCannotBeIncludedInManualChunks, logEntryCannotBeExternal, logImplicitDependantCannotBeExternal, logExternalModulesCannotBeTransformedToModules, URL_LOAD, logNoAssetSourceSet, logFileReferenceIdNotFoundForFilename, logAssetReferenceIdNotFoundForSetSource, logAssetSourceAlreadySet, logInvalidRollupPhaseForChunkEmission, logChunkNotGeneratedForFileName, logAssetNotFinalisedForFileName, logFileNameConflict, URL_GENERATEBUNDLE, logInvalidLogPosition, logInputHookInOutputPlugin, logInvalidAddonPluginHook, logInvalidFunctionPluginHook, logImplicitDependantIsNotIncluded, logCircularDependency, augmentLogMessage, URL_JSX, URL_TREESHAKE, URL_TREESHAKE_MODULESIDEEFFECTS, URL_OUTPUT_INLINEDYNAMICIMPORTS, URL_PRESERVEENTRYSIGNATURES, URL_OUTPUT_GENERATEDCODE, isValidUrl, addTrailingSlashIfMissed, URL_OUTPUT_SOURCEMAPBASEURL, URL_OUTPUT_MANUALCHUNKS, logInvalidExportOptionValue, URL_OUTPUT_AMD_BASEPATH, URL_OUTPUT_INTEROP, URL_OUTPUT_EXTERNALIMPORTATTRIBUTES, logAlreadyClosed, logMissingFileOrDirOption, logCannotEmitFromOptionsHook, URL_WATCH } from './parseAst.js';
  9. import { relative, dirname, basename, extname, resolve as resolve$1, join } from 'node:path';
  10. import { posix, isAbsolute, resolve, win32 } from 'path';
  11. import { parseAsync, xxhashBase16, xxhashBase64Url, xxhashBase36 } from '../../native.js';
  12. import process$1, { env } from 'node:process';
  13. import { performance } from 'node:perf_hooks';
  14. import * as promises from 'node:fs/promises';
  15. function _mergeNamespaces(n, m) {
  16. for (var i = 0; i < m.length; i++) {
  17. const e = m[i];
  18. if (typeof e !== 'string' && !Array.isArray(e)) { for (const k in e) {
  19. if (k !== 'default' && !(k in n)) {
  20. n[k] = e[k];
  21. }
  22. } }
  23. }
  24. return Object.defineProperty(n, Symbol.toStringTag, { value: 'Module' });
  25. }
  26. var version = "4.60.1";
  27. // src/vlq.ts
  28. var comma = ",".charCodeAt(0);
  29. var semicolon = ";".charCodeAt(0);
  30. var chars$1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  31. var intToChar = new Uint8Array(64);
  32. var charToInt = new Uint8Array(128);
  33. for (let i = 0; i < chars$1.length; i++) {
  34. const c = chars$1.charCodeAt(i);
  35. intToChar[i] = c;
  36. charToInt[c] = i;
  37. }
  38. function decodeInteger(reader, relative) {
  39. let value = 0;
  40. let shift = 0;
  41. let integer = 0;
  42. do {
  43. const c = reader.next();
  44. integer = charToInt[c];
  45. value |= (integer & 31) << shift;
  46. shift += 5;
  47. } while (integer & 32);
  48. const shouldNegate = value & 1;
  49. value >>>= 1;
  50. if (shouldNegate) {
  51. value = -2147483648 | -value;
  52. }
  53. return relative + value;
  54. }
  55. function encodeInteger(builder, num, relative) {
  56. let delta = num - relative;
  57. delta = delta < 0 ? -delta << 1 | 1 : delta << 1;
  58. do {
  59. let clamped = delta & 31;
  60. delta >>>= 5;
  61. if (delta > 0) clamped |= 32;
  62. builder.write(intToChar[clamped]);
  63. } while (delta > 0);
  64. return num;
  65. }
  66. function hasMoreVlq(reader, max) {
  67. if (reader.pos >= max) return false;
  68. return reader.peek() !== comma;
  69. }
  70. // src/strings.ts
  71. var bufLength = 1024 * 16;
  72. var td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? {
  73. decode(buf) {
  74. const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
  75. return out.toString();
  76. }
  77. } : {
  78. decode(buf) {
  79. let out = "";
  80. for (let i = 0; i < buf.length; i++) {
  81. out += String.fromCharCode(buf[i]);
  82. }
  83. return out;
  84. }
  85. };
  86. var StringWriter = class {
  87. constructor() {
  88. this.pos = 0;
  89. this.out = "";
  90. this.buffer = new Uint8Array(bufLength);
  91. }
  92. write(v) {
  93. const { buffer } = this;
  94. buffer[this.pos++] = v;
  95. if (this.pos === bufLength) {
  96. this.out += td.decode(buffer);
  97. this.pos = 0;
  98. }
  99. }
  100. flush() {
  101. const { buffer, out, pos } = this;
  102. return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
  103. }
  104. };
  105. var StringReader = class {
  106. constructor(buffer) {
  107. this.pos = 0;
  108. this.buffer = buffer;
  109. }
  110. next() {
  111. return this.buffer.charCodeAt(this.pos++);
  112. }
  113. peek() {
  114. return this.buffer.charCodeAt(this.pos);
  115. }
  116. indexOf(char) {
  117. const { buffer, pos } = this;
  118. const idx = buffer.indexOf(char, pos);
  119. return idx === -1 ? buffer.length : idx;
  120. }
  121. };
  122. // src/sourcemap-codec.ts
  123. function decode(mappings) {
  124. const { length } = mappings;
  125. const reader = new StringReader(mappings);
  126. const decoded = [];
  127. let genColumn = 0;
  128. let sourcesIndex = 0;
  129. let sourceLine = 0;
  130. let sourceColumn = 0;
  131. let namesIndex = 0;
  132. do {
  133. const semi = reader.indexOf(";");
  134. const line = [];
  135. let sorted = true;
  136. let lastCol = 0;
  137. genColumn = 0;
  138. while (reader.pos < semi) {
  139. let seg;
  140. genColumn = decodeInteger(reader, genColumn);
  141. if (genColumn < lastCol) sorted = false;
  142. lastCol = genColumn;
  143. if (hasMoreVlq(reader, semi)) {
  144. sourcesIndex = decodeInteger(reader, sourcesIndex);
  145. sourceLine = decodeInteger(reader, sourceLine);
  146. sourceColumn = decodeInteger(reader, sourceColumn);
  147. if (hasMoreVlq(reader, semi)) {
  148. namesIndex = decodeInteger(reader, namesIndex);
  149. seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex];
  150. } else {
  151. seg = [genColumn, sourcesIndex, sourceLine, sourceColumn];
  152. }
  153. } else {
  154. seg = [genColumn];
  155. }
  156. line.push(seg);
  157. reader.pos++;
  158. }
  159. if (!sorted) sort(line);
  160. decoded.push(line);
  161. reader.pos = semi + 1;
  162. } while (reader.pos <= length);
  163. return decoded;
  164. }
  165. function sort(line) {
  166. line.sort(sortComparator);
  167. }
  168. function sortComparator(a, b) {
  169. return a[0] - b[0];
  170. }
  171. function encode(decoded) {
  172. const writer = new StringWriter();
  173. let sourcesIndex = 0;
  174. let sourceLine = 0;
  175. let sourceColumn = 0;
  176. let namesIndex = 0;
  177. for (let i = 0; i < decoded.length; i++) {
  178. const line = decoded[i];
  179. if (i > 0) writer.write(semicolon);
  180. if (line.length === 0) continue;
  181. let genColumn = 0;
  182. for (let j = 0; j < line.length; j++) {
  183. const segment = line[j];
  184. if (j > 0) writer.write(comma);
  185. genColumn = encodeInteger(writer, segment[0], genColumn);
  186. if (segment.length === 1) continue;
  187. sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
  188. sourceLine = encodeInteger(writer, segment[2], sourceLine);
  189. sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
  190. if (segment.length === 4) continue;
  191. namesIndex = encodeInteger(writer, segment[4], namesIndex);
  192. }
  193. }
  194. return writer.flush();
  195. }
  196. class BitSet {
  197. constructor(arg) {
  198. this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
  199. }
  200. add(n) {
  201. this.bits[n >> 5] |= 1 << (n & 31);
  202. }
  203. has(n) {
  204. return !!(this.bits[n >> 5] & (1 << (n & 31)));
  205. }
  206. }
  207. let Chunk$1 = class Chunk {
  208. constructor(start, end, content) {
  209. this.start = start;
  210. this.end = end;
  211. this.original = content;
  212. this.intro = '';
  213. this.outro = '';
  214. this.content = content;
  215. this.storeName = false;
  216. this.edited = false;
  217. {
  218. this.previous = null;
  219. this.next = null;
  220. }
  221. }
  222. appendLeft(content) {
  223. this.outro += content;
  224. }
  225. appendRight(content) {
  226. this.intro = this.intro + content;
  227. }
  228. clone() {
  229. const chunk = new Chunk(this.start, this.end, this.original);
  230. chunk.intro = this.intro;
  231. chunk.outro = this.outro;
  232. chunk.content = this.content;
  233. chunk.storeName = this.storeName;
  234. chunk.edited = this.edited;
  235. return chunk;
  236. }
  237. contains(index) {
  238. return this.start < index && index < this.end;
  239. }
  240. eachNext(fn) {
  241. let chunk = this;
  242. while (chunk) {
  243. fn(chunk);
  244. chunk = chunk.next;
  245. }
  246. }
  247. eachPrevious(fn) {
  248. let chunk = this;
  249. while (chunk) {
  250. fn(chunk);
  251. chunk = chunk.previous;
  252. }
  253. }
  254. edit(content, storeName, contentOnly) {
  255. this.content = content;
  256. if (!contentOnly) {
  257. this.intro = '';
  258. this.outro = '';
  259. }
  260. this.storeName = storeName;
  261. this.edited = true;
  262. return this;
  263. }
  264. prependLeft(content) {
  265. this.outro = content + this.outro;
  266. }
  267. prependRight(content) {
  268. this.intro = content + this.intro;
  269. }
  270. reset() {
  271. this.intro = '';
  272. this.outro = '';
  273. if (this.edited) {
  274. this.content = this.original;
  275. this.storeName = false;
  276. this.edited = false;
  277. }
  278. }
  279. split(index) {
  280. const sliceIndex = index - this.start;
  281. const originalBefore = this.original.slice(0, sliceIndex);
  282. const originalAfter = this.original.slice(sliceIndex);
  283. this.original = originalBefore;
  284. const newChunk = new Chunk(index, this.end, originalAfter);
  285. newChunk.outro = this.outro;
  286. this.outro = '';
  287. this.end = index;
  288. if (this.edited) {
  289. // after split we should save the edit content record into the correct chunk
  290. // to make sure sourcemap correct
  291. // For example:
  292. // ' test'.trim()
  293. // split -> ' ' + 'test'
  294. // ✔️ edit -> '' + 'test'
  295. // ✖️ edit -> 'test' + ''
  296. // TODO is this block necessary?...
  297. newChunk.edit('', false);
  298. this.content = '';
  299. } else {
  300. this.content = originalBefore;
  301. }
  302. newChunk.next = this.next;
  303. if (newChunk.next) newChunk.next.previous = newChunk;
  304. newChunk.previous = this;
  305. this.next = newChunk;
  306. return newChunk;
  307. }
  308. toString() {
  309. return this.intro + this.content + this.outro;
  310. }
  311. trimEnd(rx) {
  312. this.outro = this.outro.replace(rx, '');
  313. if (this.outro.length) return true;
  314. const trimmed = this.content.replace(rx, '');
  315. if (trimmed.length) {
  316. if (trimmed !== this.content) {
  317. this.split(this.start + trimmed.length).edit('', undefined, true);
  318. if (this.edited) {
  319. // save the change, if it has been edited
  320. this.edit(trimmed, this.storeName, true);
  321. }
  322. }
  323. return true;
  324. } else {
  325. this.edit('', undefined, true);
  326. this.intro = this.intro.replace(rx, '');
  327. if (this.intro.length) return true;
  328. }
  329. }
  330. trimStart(rx) {
  331. this.intro = this.intro.replace(rx, '');
  332. if (this.intro.length) return true;
  333. const trimmed = this.content.replace(rx, '');
  334. if (trimmed.length) {
  335. if (trimmed !== this.content) {
  336. const newChunk = this.split(this.end - trimmed.length);
  337. if (this.edited) {
  338. // save the change, if it has been edited
  339. newChunk.edit(trimmed, this.storeName, true);
  340. }
  341. this.edit('', undefined, true);
  342. }
  343. return true;
  344. } else {
  345. this.edit('', undefined, true);
  346. this.outro = this.outro.replace(rx, '');
  347. if (this.outro.length) return true;
  348. }
  349. }
  350. };
  351. function getBtoa() {
  352. if (typeof globalThis !== 'undefined' && typeof globalThis.btoa === 'function') {
  353. return (str) => globalThis.btoa(unescape(encodeURIComponent(str)));
  354. } else if (typeof Buffer === 'function') {
  355. return (str) => Buffer.from(str, 'utf-8').toString('base64');
  356. } else {
  357. return () => {
  358. throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
  359. };
  360. }
  361. }
  362. const btoa = /*#__PURE__*/ getBtoa();
  363. class SourceMap {
  364. constructor(properties) {
  365. this.version = 3;
  366. this.file = properties.file;
  367. this.sources = properties.sources;
  368. this.sourcesContent = properties.sourcesContent;
  369. this.names = properties.names;
  370. this.mappings = encode(properties.mappings);
  371. if (typeof properties.x_google_ignoreList !== 'undefined') {
  372. this.x_google_ignoreList = properties.x_google_ignoreList;
  373. }
  374. if (typeof properties.debugId !== 'undefined') {
  375. this.debugId = properties.debugId;
  376. }
  377. }
  378. toString() {
  379. return JSON.stringify(this);
  380. }
  381. toUrl() {
  382. return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
  383. }
  384. }
  385. function guessIndent(code) {
  386. const lines = code.split('\n');
  387. const tabbed = lines.filter((line) => /^\t+/.test(line));
  388. const spaced = lines.filter((line) => /^ {2,}/.test(line));
  389. if (tabbed.length === 0 && spaced.length === 0) {
  390. return null;
  391. }
  392. // More lines tabbed than spaced? Assume tabs, and
  393. // default to tabs in the case of a tie (or nothing
  394. // to go on)
  395. if (tabbed.length >= spaced.length) {
  396. return '\t';
  397. }
  398. // Otherwise, we need to guess the multiple
  399. const min = spaced.reduce((previous, current) => {
  400. const numSpaces = /^ +/.exec(current)[0].length;
  401. return Math.min(numSpaces, previous);
  402. }, Infinity);
  403. return new Array(min + 1).join(' ');
  404. }
  405. function getRelativePath(from, to) {
  406. const fromParts = from.split(/[/\\]/);
  407. const toParts = to.split(/[/\\]/);
  408. fromParts.pop(); // get dirname
  409. while (fromParts[0] === toParts[0]) {
  410. fromParts.shift();
  411. toParts.shift();
  412. }
  413. if (fromParts.length) {
  414. let i = fromParts.length;
  415. while (i--) fromParts[i] = '..';
  416. }
  417. return fromParts.concat(toParts).join('/');
  418. }
  419. const toString = Object.prototype.toString;
  420. function isObject(thing) {
  421. return toString.call(thing) === '[object Object]';
  422. }
  423. function getLocator(source) {
  424. const originalLines = source.split('\n');
  425. const lineOffsets = [];
  426. for (let i = 0, pos = 0; i < originalLines.length; i++) {
  427. lineOffsets.push(pos);
  428. pos += originalLines[i].length + 1;
  429. }
  430. return function locate(index) {
  431. let i = 0;
  432. let j = lineOffsets.length;
  433. while (i < j) {
  434. const m = (i + j) >> 1;
  435. if (index < lineOffsets[m]) {
  436. j = m;
  437. } else {
  438. i = m + 1;
  439. }
  440. }
  441. const line = i - 1;
  442. const column = index - lineOffsets[line];
  443. return { line, column };
  444. };
  445. }
  446. const wordRegex = /\w/;
  447. class Mappings {
  448. constructor(hires) {
  449. this.hires = hires;
  450. this.generatedCodeLine = 0;
  451. this.generatedCodeColumn = 0;
  452. this.raw = [];
  453. this.rawSegments = this.raw[this.generatedCodeLine] = [];
  454. this.pending = null;
  455. }
  456. addEdit(sourceIndex, content, loc, nameIndex) {
  457. if (content.length) {
  458. const contentLengthMinusOne = content.length - 1;
  459. let contentLineEnd = content.indexOf('\n', 0);
  460. let previousContentLineEnd = -1;
  461. // Loop through each line in the content and add a segment, but stop if the last line is empty,
  462. // else code afterwards would fill one line too many
  463. while (contentLineEnd >= 0 && contentLengthMinusOne > contentLineEnd) {
  464. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  465. if (nameIndex >= 0) {
  466. segment.push(nameIndex);
  467. }
  468. this.rawSegments.push(segment);
  469. this.generatedCodeLine += 1;
  470. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  471. this.generatedCodeColumn = 0;
  472. previousContentLineEnd = contentLineEnd;
  473. contentLineEnd = content.indexOf('\n', contentLineEnd + 1);
  474. }
  475. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  476. if (nameIndex >= 0) {
  477. segment.push(nameIndex);
  478. }
  479. this.rawSegments.push(segment);
  480. this.advance(content.slice(previousContentLineEnd + 1));
  481. } else if (this.pending) {
  482. this.rawSegments.push(this.pending);
  483. this.advance(content);
  484. }
  485. this.pending = null;
  486. }
  487. addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
  488. let originalCharIndex = chunk.start;
  489. let first = true;
  490. // when iterating each char, check if it's in a word boundary
  491. let charInHiresBoundary = false;
  492. while (originalCharIndex < chunk.end) {
  493. if (original[originalCharIndex] === '\n') {
  494. loc.line += 1;
  495. loc.column = 0;
  496. this.generatedCodeLine += 1;
  497. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  498. this.generatedCodeColumn = 0;
  499. first = true;
  500. charInHiresBoundary = false;
  501. } else {
  502. if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
  503. const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
  504. if (this.hires === 'boundary') {
  505. // in hires "boundary", group segments per word boundary than per char
  506. if (wordRegex.test(original[originalCharIndex])) {
  507. // for first char in the boundary found, start the boundary by pushing a segment
  508. if (!charInHiresBoundary) {
  509. this.rawSegments.push(segment);
  510. charInHiresBoundary = true;
  511. }
  512. } else {
  513. // for non-word char, end the boundary by pushing a segment
  514. this.rawSegments.push(segment);
  515. charInHiresBoundary = false;
  516. }
  517. } else {
  518. this.rawSegments.push(segment);
  519. }
  520. }
  521. loc.column += 1;
  522. this.generatedCodeColumn += 1;
  523. first = false;
  524. }
  525. originalCharIndex += 1;
  526. }
  527. this.pending = null;
  528. }
  529. advance(str) {
  530. if (!str) return;
  531. const lines = str.split('\n');
  532. if (lines.length > 1) {
  533. for (let i = 0; i < lines.length - 1; i++) {
  534. this.generatedCodeLine++;
  535. this.raw[this.generatedCodeLine] = this.rawSegments = [];
  536. }
  537. this.generatedCodeColumn = 0;
  538. }
  539. this.generatedCodeColumn += lines[lines.length - 1].length;
  540. }
  541. }
  542. const n = '\n';
  543. const warned = {
  544. insertLeft: false,
  545. insertRight: false,
  546. storeName: false,
  547. };
  548. class MagicString {
  549. constructor(string, options = {}) {
  550. const chunk = new Chunk$1(0, string.length, string);
  551. Object.defineProperties(this, {
  552. original: { writable: true, value: string },
  553. outro: { writable: true, value: '' },
  554. intro: { writable: true, value: '' },
  555. firstChunk: { writable: true, value: chunk },
  556. lastChunk: { writable: true, value: chunk },
  557. lastSearchedChunk: { writable: true, value: chunk },
  558. byStart: { writable: true, value: {} },
  559. byEnd: { writable: true, value: {} },
  560. filename: { writable: true, value: options.filename },
  561. indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
  562. sourcemapLocations: { writable: true, value: new BitSet() },
  563. storedNames: { writable: true, value: {} },
  564. indentStr: { writable: true, value: undefined },
  565. ignoreList: { writable: true, value: options.ignoreList },
  566. offset: { writable: true, value: options.offset || 0 },
  567. });
  568. this.byStart[0] = chunk;
  569. this.byEnd[string.length] = chunk;
  570. }
  571. addSourcemapLocation(char) {
  572. this.sourcemapLocations.add(char);
  573. }
  574. append(content) {
  575. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  576. this.outro += content;
  577. return this;
  578. }
  579. appendLeft(index, content) {
  580. index = index + this.offset;
  581. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  582. this._split(index);
  583. const chunk = this.byEnd[index];
  584. if (chunk) {
  585. chunk.appendLeft(content);
  586. } else {
  587. this.intro += content;
  588. }
  589. return this;
  590. }
  591. appendRight(index, content) {
  592. index = index + this.offset;
  593. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  594. this._split(index);
  595. const chunk = this.byStart[index];
  596. if (chunk) {
  597. chunk.appendRight(content);
  598. } else {
  599. this.outro += content;
  600. }
  601. return this;
  602. }
  603. clone() {
  604. const cloned = new MagicString(this.original, { filename: this.filename, offset: this.offset });
  605. let originalChunk = this.firstChunk;
  606. let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
  607. while (originalChunk) {
  608. cloned.byStart[clonedChunk.start] = clonedChunk;
  609. cloned.byEnd[clonedChunk.end] = clonedChunk;
  610. const nextOriginalChunk = originalChunk.next;
  611. const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
  612. if (nextClonedChunk) {
  613. clonedChunk.next = nextClonedChunk;
  614. nextClonedChunk.previous = clonedChunk;
  615. clonedChunk = nextClonedChunk;
  616. }
  617. originalChunk = nextOriginalChunk;
  618. }
  619. cloned.lastChunk = clonedChunk;
  620. if (this.indentExclusionRanges) {
  621. cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
  622. }
  623. cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
  624. cloned.intro = this.intro;
  625. cloned.outro = this.outro;
  626. return cloned;
  627. }
  628. generateDecodedMap(options) {
  629. options = options || {};
  630. const sourceIndex = 0;
  631. const names = Object.keys(this.storedNames);
  632. const mappings = new Mappings(options.hires);
  633. const locate = getLocator(this.original);
  634. if (this.intro) {
  635. mappings.advance(this.intro);
  636. }
  637. this.firstChunk.eachNext((chunk) => {
  638. const loc = locate(chunk.start);
  639. if (chunk.intro.length) mappings.advance(chunk.intro);
  640. if (chunk.edited) {
  641. mappings.addEdit(
  642. sourceIndex,
  643. chunk.content,
  644. loc,
  645. chunk.storeName ? names.indexOf(chunk.original) : -1,
  646. );
  647. } else {
  648. mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
  649. }
  650. if (chunk.outro.length) mappings.advance(chunk.outro);
  651. });
  652. if (this.outro) {
  653. mappings.advance(this.outro);
  654. }
  655. return {
  656. file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
  657. sources: [
  658. options.source ? getRelativePath(options.file || '', options.source) : options.file || '',
  659. ],
  660. sourcesContent: options.includeContent ? [this.original] : undefined,
  661. names,
  662. mappings: mappings.raw,
  663. x_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined,
  664. };
  665. }
  666. generateMap(options) {
  667. return new SourceMap(this.generateDecodedMap(options));
  668. }
  669. _ensureindentStr() {
  670. if (this.indentStr === undefined) {
  671. this.indentStr = guessIndent(this.original);
  672. }
  673. }
  674. _getRawIndentString() {
  675. this._ensureindentStr();
  676. return this.indentStr;
  677. }
  678. getIndentString() {
  679. this._ensureindentStr();
  680. return this.indentStr === null ? '\t' : this.indentStr;
  681. }
  682. indent(indentStr, options) {
  683. const pattern = /^[^\r\n]/gm;
  684. if (isObject(indentStr)) {
  685. options = indentStr;
  686. indentStr = undefined;
  687. }
  688. if (indentStr === undefined) {
  689. this._ensureindentStr();
  690. indentStr = this.indentStr || '\t';
  691. }
  692. if (indentStr === '') return this; // noop
  693. options = options || {};
  694. // Process exclusion ranges
  695. const isExcluded = {};
  696. if (options.exclude) {
  697. const exclusions =
  698. typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
  699. exclusions.forEach((exclusion) => {
  700. for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
  701. isExcluded[i] = true;
  702. }
  703. });
  704. }
  705. let shouldIndentNextCharacter = options.indentStart !== false;
  706. const replacer = (match) => {
  707. if (shouldIndentNextCharacter) return `${indentStr}${match}`;
  708. shouldIndentNextCharacter = true;
  709. return match;
  710. };
  711. this.intro = this.intro.replace(pattern, replacer);
  712. let charIndex = 0;
  713. let chunk = this.firstChunk;
  714. while (chunk) {
  715. const end = chunk.end;
  716. if (chunk.edited) {
  717. if (!isExcluded[charIndex]) {
  718. chunk.content = chunk.content.replace(pattern, replacer);
  719. if (chunk.content.length) {
  720. shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
  721. }
  722. }
  723. } else {
  724. charIndex = chunk.start;
  725. while (charIndex < end) {
  726. if (!isExcluded[charIndex]) {
  727. const char = this.original[charIndex];
  728. if (char === '\n') {
  729. shouldIndentNextCharacter = true;
  730. } else if (char !== '\r' && shouldIndentNextCharacter) {
  731. shouldIndentNextCharacter = false;
  732. if (charIndex === chunk.start) {
  733. chunk.prependRight(indentStr);
  734. } else {
  735. this._splitChunk(chunk, charIndex);
  736. chunk = chunk.next;
  737. chunk.prependRight(indentStr);
  738. }
  739. }
  740. }
  741. charIndex += 1;
  742. }
  743. }
  744. charIndex = chunk.end;
  745. chunk = chunk.next;
  746. }
  747. this.outro = this.outro.replace(pattern, replacer);
  748. return this;
  749. }
  750. insert() {
  751. throw new Error(
  752. 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)',
  753. );
  754. }
  755. insertLeft(index, content) {
  756. if (!warned.insertLeft) {
  757. console.warn(
  758. 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead',
  759. );
  760. warned.insertLeft = true;
  761. }
  762. return this.appendLeft(index, content);
  763. }
  764. insertRight(index, content) {
  765. if (!warned.insertRight) {
  766. console.warn(
  767. 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead',
  768. );
  769. warned.insertRight = true;
  770. }
  771. return this.prependRight(index, content);
  772. }
  773. move(start, end, index) {
  774. start = start + this.offset;
  775. end = end + this.offset;
  776. index = index + this.offset;
  777. if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself');
  778. this._split(start);
  779. this._split(end);
  780. this._split(index);
  781. const first = this.byStart[start];
  782. const last = this.byEnd[end];
  783. const oldLeft = first.previous;
  784. const oldRight = last.next;
  785. const newRight = this.byStart[index];
  786. if (!newRight && last === this.lastChunk) return this;
  787. const newLeft = newRight ? newRight.previous : this.lastChunk;
  788. if (oldLeft) oldLeft.next = oldRight;
  789. if (oldRight) oldRight.previous = oldLeft;
  790. if (newLeft) newLeft.next = first;
  791. if (newRight) newRight.previous = last;
  792. if (!first.previous) this.firstChunk = last.next;
  793. if (!last.next) {
  794. this.lastChunk = first.previous;
  795. this.lastChunk.next = null;
  796. }
  797. first.previous = newLeft;
  798. last.next = newRight || null;
  799. if (!newLeft) this.firstChunk = first;
  800. if (!newRight) this.lastChunk = last;
  801. return this;
  802. }
  803. overwrite(start, end, content, options) {
  804. options = options || {};
  805. return this.update(start, end, content, { ...options, overwrite: !options.contentOnly });
  806. }
  807. update(start, end, content, options) {
  808. start = start + this.offset;
  809. end = end + this.offset;
  810. if (typeof content !== 'string') throw new TypeError('replacement content must be a string');
  811. if (this.original.length !== 0) {
  812. while (start < 0) start += this.original.length;
  813. while (end < 0) end += this.original.length;
  814. }
  815. if (end > this.original.length) throw new Error('end is out of bounds');
  816. if (start === end)
  817. throw new Error(
  818. 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead',
  819. );
  820. this._split(start);
  821. this._split(end);
  822. if (options === true) {
  823. if (!warned.storeName) {
  824. console.warn(
  825. 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string',
  826. );
  827. warned.storeName = true;
  828. }
  829. options = { storeName: true };
  830. }
  831. const storeName = options !== undefined ? options.storeName : false;
  832. const overwrite = options !== undefined ? options.overwrite : false;
  833. if (storeName) {
  834. const original = this.original.slice(start, end);
  835. Object.defineProperty(this.storedNames, original, {
  836. writable: true,
  837. value: true,
  838. enumerable: true,
  839. });
  840. }
  841. const first = this.byStart[start];
  842. const last = this.byEnd[end];
  843. if (first) {
  844. let chunk = first;
  845. while (chunk !== last) {
  846. if (chunk.next !== this.byStart[chunk.end]) {
  847. throw new Error('Cannot overwrite across a split point');
  848. }
  849. chunk = chunk.next;
  850. chunk.edit('', false);
  851. }
  852. first.edit(content, storeName, !overwrite);
  853. } else {
  854. // must be inserting at the end
  855. const newChunk = new Chunk$1(start, end, '').edit(content, storeName);
  856. // TODO last chunk in the array may not be the last chunk, if it's moved...
  857. last.next = newChunk;
  858. newChunk.previous = last;
  859. }
  860. return this;
  861. }
  862. prepend(content) {
  863. if (typeof content !== 'string') throw new TypeError('outro content must be a string');
  864. this.intro = content + this.intro;
  865. return this;
  866. }
  867. prependLeft(index, content) {
  868. index = index + this.offset;
  869. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  870. this._split(index);
  871. const chunk = this.byEnd[index];
  872. if (chunk) {
  873. chunk.prependLeft(content);
  874. } else {
  875. this.intro = content + this.intro;
  876. }
  877. return this;
  878. }
  879. prependRight(index, content) {
  880. index = index + this.offset;
  881. if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
  882. this._split(index);
  883. const chunk = this.byStart[index];
  884. if (chunk) {
  885. chunk.prependRight(content);
  886. } else {
  887. this.outro = content + this.outro;
  888. }
  889. return this;
  890. }
  891. remove(start, end) {
  892. start = start + this.offset;
  893. end = end + this.offset;
  894. if (this.original.length !== 0) {
  895. while (start < 0) start += this.original.length;
  896. while (end < 0) end += this.original.length;
  897. }
  898. if (start === end) return this;
  899. if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
  900. if (start > end) throw new Error('end must be greater than start');
  901. this._split(start);
  902. this._split(end);
  903. let chunk = this.byStart[start];
  904. while (chunk) {
  905. chunk.intro = '';
  906. chunk.outro = '';
  907. chunk.edit('');
  908. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  909. }
  910. return this;
  911. }
  912. reset(start, end) {
  913. start = start + this.offset;
  914. end = end + this.offset;
  915. if (this.original.length !== 0) {
  916. while (start < 0) start += this.original.length;
  917. while (end < 0) end += this.original.length;
  918. }
  919. if (start === end) return this;
  920. if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
  921. if (start > end) throw new Error('end must be greater than start');
  922. this._split(start);
  923. this._split(end);
  924. let chunk = this.byStart[start];
  925. while (chunk) {
  926. chunk.reset();
  927. chunk = end > chunk.end ? this.byStart[chunk.end] : null;
  928. }
  929. return this;
  930. }
  931. lastChar() {
  932. if (this.outro.length) return this.outro[this.outro.length - 1];
  933. let chunk = this.lastChunk;
  934. do {
  935. if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
  936. if (chunk.content.length) return chunk.content[chunk.content.length - 1];
  937. if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
  938. } while ((chunk = chunk.previous));
  939. if (this.intro.length) return this.intro[this.intro.length - 1];
  940. return '';
  941. }
  942. lastLine() {
  943. let lineIndex = this.outro.lastIndexOf(n);
  944. if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
  945. let lineStr = this.outro;
  946. let chunk = this.lastChunk;
  947. do {
  948. if (chunk.outro.length > 0) {
  949. lineIndex = chunk.outro.lastIndexOf(n);
  950. if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
  951. lineStr = chunk.outro + lineStr;
  952. }
  953. if (chunk.content.length > 0) {
  954. lineIndex = chunk.content.lastIndexOf(n);
  955. if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
  956. lineStr = chunk.content + lineStr;
  957. }
  958. if (chunk.intro.length > 0) {
  959. lineIndex = chunk.intro.lastIndexOf(n);
  960. if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
  961. lineStr = chunk.intro + lineStr;
  962. }
  963. } while ((chunk = chunk.previous));
  964. lineIndex = this.intro.lastIndexOf(n);
  965. if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
  966. return this.intro + lineStr;
  967. }
  968. slice(start = 0, end = this.original.length - this.offset) {
  969. start = start + this.offset;
  970. end = end + this.offset;
  971. if (this.original.length !== 0) {
  972. while (start < 0) start += this.original.length;
  973. while (end < 0) end += this.original.length;
  974. }
  975. let result = '';
  976. // find start chunk
  977. let chunk = this.firstChunk;
  978. while (chunk && (chunk.start > start || chunk.end <= start)) {
  979. // found end chunk before start
  980. if (chunk.start < end && chunk.end >= end) {
  981. return result;
  982. }
  983. chunk = chunk.next;
  984. }
  985. if (chunk && chunk.edited && chunk.start !== start)
  986. throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
  987. const startChunk = chunk;
  988. while (chunk) {
  989. if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
  990. result += chunk.intro;
  991. }
  992. const containsEnd = chunk.start < end && chunk.end >= end;
  993. if (containsEnd && chunk.edited && chunk.end !== end)
  994. throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
  995. const sliceStart = startChunk === chunk ? start - chunk.start : 0;
  996. const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
  997. result += chunk.content.slice(sliceStart, sliceEnd);
  998. if (chunk.outro && (!containsEnd || chunk.end === end)) {
  999. result += chunk.outro;
  1000. }
  1001. if (containsEnd) {
  1002. break;
  1003. }
  1004. chunk = chunk.next;
  1005. }
  1006. return result;
  1007. }
  1008. // TODO deprecate this? not really very useful
  1009. snip(start, end) {
  1010. const clone = this.clone();
  1011. clone.remove(0, start);
  1012. clone.remove(end, clone.original.length);
  1013. return clone;
  1014. }
  1015. _split(index) {
  1016. if (this.byStart[index] || this.byEnd[index]) return;
  1017. let chunk = this.lastSearchedChunk;
  1018. let previousChunk = chunk;
  1019. const searchForward = index > chunk.end;
  1020. while (chunk) {
  1021. if (chunk.contains(index)) return this._splitChunk(chunk, index);
  1022. chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
  1023. // Prevent infinite loop (e.g. via empty chunks, where start === end)
  1024. if (chunk === previousChunk) return;
  1025. previousChunk = chunk;
  1026. }
  1027. }
  1028. _splitChunk(chunk, index) {
  1029. if (chunk.edited && chunk.content.length) {
  1030. // zero-length edited chunks are a special case (overlapping replacements)
  1031. const loc = getLocator(this.original)(index);
  1032. throw new Error(
  1033. `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`,
  1034. );
  1035. }
  1036. const newChunk = chunk.split(index);
  1037. this.byEnd[index] = chunk;
  1038. this.byStart[index] = newChunk;
  1039. this.byEnd[newChunk.end] = newChunk;
  1040. if (chunk === this.lastChunk) this.lastChunk = newChunk;
  1041. this.lastSearchedChunk = chunk;
  1042. return true;
  1043. }
  1044. toString() {
  1045. let str = this.intro;
  1046. let chunk = this.firstChunk;
  1047. while (chunk) {
  1048. str += chunk.toString();
  1049. chunk = chunk.next;
  1050. }
  1051. return str + this.outro;
  1052. }
  1053. isEmpty() {
  1054. let chunk = this.firstChunk;
  1055. do {
  1056. if (
  1057. (chunk.intro.length && chunk.intro.trim()) ||
  1058. (chunk.content.length && chunk.content.trim()) ||
  1059. (chunk.outro.length && chunk.outro.trim())
  1060. )
  1061. return false;
  1062. } while ((chunk = chunk.next));
  1063. return true;
  1064. }
  1065. length() {
  1066. let chunk = this.firstChunk;
  1067. let length = 0;
  1068. do {
  1069. length += chunk.intro.length + chunk.content.length + chunk.outro.length;
  1070. } while ((chunk = chunk.next));
  1071. return length;
  1072. }
  1073. trimLines() {
  1074. return this.trim('[\\r\\n]');
  1075. }
  1076. trim(charType) {
  1077. return this.trimStart(charType).trimEnd(charType);
  1078. }
  1079. trimEndAborted(charType) {
  1080. const rx = new RegExp((charType || '\\s') + '+$');
  1081. this.outro = this.outro.replace(rx, '');
  1082. if (this.outro.length) return true;
  1083. let chunk = this.lastChunk;
  1084. do {
  1085. const end = chunk.end;
  1086. const aborted = chunk.trimEnd(rx);
  1087. // if chunk was trimmed, we have a new lastChunk
  1088. if (chunk.end !== end) {
  1089. if (this.lastChunk === chunk) {
  1090. this.lastChunk = chunk.next;
  1091. }
  1092. this.byEnd[chunk.end] = chunk;
  1093. this.byStart[chunk.next.start] = chunk.next;
  1094. this.byEnd[chunk.next.end] = chunk.next;
  1095. }
  1096. if (aborted) return true;
  1097. chunk = chunk.previous;
  1098. } while (chunk);
  1099. return false;
  1100. }
  1101. trimEnd(charType) {
  1102. this.trimEndAborted(charType);
  1103. return this;
  1104. }
  1105. trimStartAborted(charType) {
  1106. const rx = new RegExp('^' + (charType || '\\s') + '+');
  1107. this.intro = this.intro.replace(rx, '');
  1108. if (this.intro.length) return true;
  1109. let chunk = this.firstChunk;
  1110. do {
  1111. const end = chunk.end;
  1112. const aborted = chunk.trimStart(rx);
  1113. if (chunk.end !== end) {
  1114. // special case...
  1115. if (chunk === this.lastChunk) this.lastChunk = chunk.next;
  1116. this.byEnd[chunk.end] = chunk;
  1117. this.byStart[chunk.next.start] = chunk.next;
  1118. this.byEnd[chunk.next.end] = chunk.next;
  1119. }
  1120. if (aborted) return true;
  1121. chunk = chunk.next;
  1122. } while (chunk);
  1123. return false;
  1124. }
  1125. trimStart(charType) {
  1126. this.trimStartAborted(charType);
  1127. return this;
  1128. }
  1129. hasChanged() {
  1130. return this.original !== this.toString();
  1131. }
  1132. _replaceRegexp(searchValue, replacement) {
  1133. function getReplacement(match, str) {
  1134. if (typeof replacement === 'string') {
  1135. return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
  1136. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
  1137. if (i === '$') return '$';
  1138. if (i === '&') return match[0];
  1139. const num = +i;
  1140. if (num < match.length) return match[+i];
  1141. return `$${i}`;
  1142. });
  1143. } else {
  1144. return replacement(...match, match.index, str, match.groups);
  1145. }
  1146. }
  1147. function matchAll(re, str) {
  1148. let match;
  1149. const matches = [];
  1150. while ((match = re.exec(str))) {
  1151. matches.push(match);
  1152. }
  1153. return matches;
  1154. }
  1155. if (searchValue.global) {
  1156. const matches = matchAll(searchValue, this.original);
  1157. matches.forEach((match) => {
  1158. if (match.index != null) {
  1159. const replacement = getReplacement(match, this.original);
  1160. if (replacement !== match[0]) {
  1161. this.overwrite(match.index, match.index + match[0].length, replacement);
  1162. }
  1163. }
  1164. });
  1165. } else {
  1166. const match = this.original.match(searchValue);
  1167. if (match && match.index != null) {
  1168. const replacement = getReplacement(match, this.original);
  1169. if (replacement !== match[0]) {
  1170. this.overwrite(match.index, match.index + match[0].length, replacement);
  1171. }
  1172. }
  1173. }
  1174. return this;
  1175. }
  1176. _replaceString(string, replacement) {
  1177. const { original } = this;
  1178. const index = original.indexOf(string);
  1179. if (index !== -1) {
  1180. if (typeof replacement === 'function') {
  1181. replacement = replacement(string, index, original);
  1182. }
  1183. if (string !== replacement) {
  1184. this.overwrite(index, index + string.length, replacement);
  1185. }
  1186. }
  1187. return this;
  1188. }
  1189. replace(searchValue, replacement) {
  1190. if (typeof searchValue === 'string') {
  1191. return this._replaceString(searchValue, replacement);
  1192. }
  1193. return this._replaceRegexp(searchValue, replacement);
  1194. }
  1195. _replaceAllString(string, replacement) {
  1196. const { original } = this;
  1197. const stringLength = string.length;
  1198. for (
  1199. let index = original.indexOf(string);
  1200. index !== -1;
  1201. index = original.indexOf(string, index + stringLength)
  1202. ) {
  1203. const previous = original.slice(index, index + stringLength);
  1204. let _replacement = replacement;
  1205. if (typeof replacement === 'function') {
  1206. _replacement = replacement(previous, index, original);
  1207. }
  1208. if (previous !== _replacement) this.overwrite(index, index + stringLength, _replacement);
  1209. }
  1210. return this;
  1211. }
  1212. replaceAll(searchValue, replacement) {
  1213. if (typeof searchValue === 'string') {
  1214. return this._replaceAllString(searchValue, replacement);
  1215. }
  1216. if (!searchValue.global) {
  1217. throw new TypeError(
  1218. 'MagicString.prototype.replaceAll called with a non-global RegExp argument',
  1219. );
  1220. }
  1221. return this._replaceRegexp(searchValue, replacement);
  1222. }
  1223. }
  1224. const hasOwnProp = Object.prototype.hasOwnProperty;
  1225. let Bundle$1 = class Bundle {
  1226. constructor(options = {}) {
  1227. this.intro = options.intro || '';
  1228. this.separator = options.separator !== undefined ? options.separator : '\n';
  1229. this.sources = [];
  1230. this.uniqueSources = [];
  1231. this.uniqueSourceIndexByFilename = {};
  1232. }
  1233. addSource(source) {
  1234. if (source instanceof MagicString) {
  1235. return this.addSource({
  1236. content: source,
  1237. filename: source.filename,
  1238. separator: this.separator,
  1239. });
  1240. }
  1241. if (!isObject(source) || !source.content) {
  1242. throw new Error(
  1243. 'bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`',
  1244. );
  1245. }
  1246. ['filename', 'ignoreList', 'indentExclusionRanges', 'separator'].forEach((option) => {
  1247. if (!hasOwnProp.call(source, option)) source[option] = source.content[option];
  1248. });
  1249. if (source.separator === undefined) {
  1250. // TODO there's a bunch of this sort of thing, needs cleaning up
  1251. source.separator = this.separator;
  1252. }
  1253. if (source.filename) {
  1254. if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {
  1255. this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;
  1256. this.uniqueSources.push({ filename: source.filename, content: source.content.original });
  1257. } else {
  1258. const uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];
  1259. if (source.content.original !== uniqueSource.content) {
  1260. throw new Error(`Illegal source: same filename (${source.filename}), different contents`);
  1261. }
  1262. }
  1263. }
  1264. this.sources.push(source);
  1265. return this;
  1266. }
  1267. append(str, options) {
  1268. this.addSource({
  1269. content: new MagicString(str),
  1270. separator: (options && options.separator) || '',
  1271. });
  1272. return this;
  1273. }
  1274. clone() {
  1275. const bundle = new Bundle({
  1276. intro: this.intro,
  1277. separator: this.separator,
  1278. });
  1279. this.sources.forEach((source) => {
  1280. bundle.addSource({
  1281. filename: source.filename,
  1282. content: source.content.clone(),
  1283. separator: source.separator,
  1284. });
  1285. });
  1286. return bundle;
  1287. }
  1288. generateDecodedMap(options = {}) {
  1289. const names = [];
  1290. let x_google_ignoreList = undefined;
  1291. this.sources.forEach((source) => {
  1292. Object.keys(source.content.storedNames).forEach((name) => {
  1293. if (!~names.indexOf(name)) names.push(name);
  1294. });
  1295. });
  1296. const mappings = new Mappings(options.hires);
  1297. if (this.intro) {
  1298. mappings.advance(this.intro);
  1299. }
  1300. this.sources.forEach((source, i) => {
  1301. if (i > 0) {
  1302. mappings.advance(this.separator);
  1303. }
  1304. const sourceIndex = source.filename ? this.uniqueSourceIndexByFilename[source.filename] : -1;
  1305. const magicString = source.content;
  1306. const locate = getLocator(magicString.original);
  1307. if (magicString.intro) {
  1308. mappings.advance(magicString.intro);
  1309. }
  1310. magicString.firstChunk.eachNext((chunk) => {
  1311. const loc = locate(chunk.start);
  1312. if (chunk.intro.length) mappings.advance(chunk.intro);
  1313. if (source.filename) {
  1314. if (chunk.edited) {
  1315. mappings.addEdit(
  1316. sourceIndex,
  1317. chunk.content,
  1318. loc,
  1319. chunk.storeName ? names.indexOf(chunk.original) : -1,
  1320. );
  1321. } else {
  1322. mappings.addUneditedChunk(
  1323. sourceIndex,
  1324. chunk,
  1325. magicString.original,
  1326. loc,
  1327. magicString.sourcemapLocations,
  1328. );
  1329. }
  1330. } else {
  1331. mappings.advance(chunk.content);
  1332. }
  1333. if (chunk.outro.length) mappings.advance(chunk.outro);
  1334. });
  1335. if (magicString.outro) {
  1336. mappings.advance(magicString.outro);
  1337. }
  1338. if (source.ignoreList && sourceIndex !== -1) {
  1339. if (x_google_ignoreList === undefined) {
  1340. x_google_ignoreList = [];
  1341. }
  1342. x_google_ignoreList.push(sourceIndex);
  1343. }
  1344. });
  1345. return {
  1346. file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
  1347. sources: this.uniqueSources.map((source) => {
  1348. return options.file ? getRelativePath(options.file, source.filename) : source.filename;
  1349. }),
  1350. sourcesContent: this.uniqueSources.map((source) => {
  1351. return options.includeContent ? source.content : null;
  1352. }),
  1353. names,
  1354. mappings: mappings.raw,
  1355. x_google_ignoreList,
  1356. };
  1357. }
  1358. generateMap(options) {
  1359. return new SourceMap(this.generateDecodedMap(options));
  1360. }
  1361. getIndentString() {
  1362. const indentStringCounts = {};
  1363. this.sources.forEach((source) => {
  1364. const indentStr = source.content._getRawIndentString();
  1365. if (indentStr === null) return;
  1366. if (!indentStringCounts[indentStr]) indentStringCounts[indentStr] = 0;
  1367. indentStringCounts[indentStr] += 1;
  1368. });
  1369. return (
  1370. Object.keys(indentStringCounts).sort((a, b) => {
  1371. return indentStringCounts[a] - indentStringCounts[b];
  1372. })[0] || '\t'
  1373. );
  1374. }
  1375. indent(indentStr) {
  1376. if (!arguments.length) {
  1377. indentStr = this.getIndentString();
  1378. }
  1379. if (indentStr === '') return this; // noop
  1380. let trailingNewline = !this.intro || this.intro.slice(-1) === '\n';
  1381. this.sources.forEach((source, i) => {
  1382. const separator = source.separator !== undefined ? source.separator : this.separator;
  1383. const indentStart = trailingNewline || (i > 0 && /\r?\n$/.test(separator));
  1384. source.content.indent(indentStr, {
  1385. exclude: source.indentExclusionRanges,
  1386. indentStart, //: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator )
  1387. });
  1388. trailingNewline = source.content.lastChar() === '\n';
  1389. });
  1390. if (this.intro) {
  1391. this.intro =
  1392. indentStr +
  1393. this.intro.replace(/^[^\n]/gm, (match, index) => {
  1394. return index > 0 ? indentStr + match : match;
  1395. });
  1396. }
  1397. return this;
  1398. }
  1399. prepend(str) {
  1400. this.intro = str + this.intro;
  1401. return this;
  1402. }
  1403. toString() {
  1404. const body = this.sources
  1405. .map((source, i) => {
  1406. const separator = source.separator !== undefined ? source.separator : this.separator;
  1407. const str = (i > 0 ? separator : '') + source.content.toString();
  1408. return str;
  1409. })
  1410. .join('');
  1411. return this.intro + body;
  1412. }
  1413. isEmpty() {
  1414. if (this.intro.length && this.intro.trim()) return false;
  1415. if (this.sources.some((source) => !source.content.isEmpty())) return false;
  1416. return true;
  1417. }
  1418. length() {
  1419. return this.sources.reduce(
  1420. (length, source) => length + source.content.length(),
  1421. this.intro.length,
  1422. );
  1423. }
  1424. trimLines() {
  1425. return this.trim('[\\r\\n]');
  1426. }
  1427. trim(charType) {
  1428. return this.trimStart(charType).trimEnd(charType);
  1429. }
  1430. trimStart(charType) {
  1431. const rx = new RegExp('^' + (charType || '\\s') + '+');
  1432. this.intro = this.intro.replace(rx, '');
  1433. if (!this.intro) {
  1434. let source;
  1435. let i = 0;
  1436. do {
  1437. source = this.sources[i++];
  1438. if (!source) {
  1439. break;
  1440. }
  1441. } while (!source.content.trimStartAborted(charType));
  1442. }
  1443. return this;
  1444. }
  1445. trimEnd(charType) {
  1446. const rx = new RegExp((charType || '\\s') + '+$');
  1447. let source;
  1448. let i = this.sources.length - 1;
  1449. do {
  1450. source = this.sources[i--];
  1451. if (!source) {
  1452. this.intro = this.intro.replace(rx, '');
  1453. break;
  1454. }
  1455. } while (!source.content.trimEndAborted(charType));
  1456. return this;
  1457. }
  1458. };
  1459. function treeshakeNode(node, code, start, end) {
  1460. code.remove(start, end);
  1461. node.removeAnnotations(code);
  1462. }
  1463. const NO_SEMICOLON = { isNoStatement: true };
  1464. // This assumes there are only white-space and comments between start and the string we are looking for
  1465. function findFirstOccurrenceOutsideComment(code, searchString, start = 0) {
  1466. let searchPos, charCodeAfterSlash;
  1467. searchPos = code.indexOf(searchString, start);
  1468. while (true) {
  1469. start = code.indexOf('/', start);
  1470. if (start === -1 || start >= searchPos)
  1471. return searchPos;
  1472. charCodeAfterSlash = code.charCodeAt(++start);
  1473. ++start;
  1474. // With our assumption, '/' always starts a comment. Determine comment type:
  1475. start =
  1476. charCodeAfterSlash === 47 /*"/"*/
  1477. ? code.indexOf('\n', start) + 1
  1478. : code.indexOf('*/', start) + 2;
  1479. if (start > searchPos) {
  1480. searchPos = code.indexOf(searchString, start);
  1481. }
  1482. }
  1483. }
  1484. const NON_WHITESPACE = /\S/g;
  1485. function findNonWhiteSpace(code, index) {
  1486. NON_WHITESPACE.lastIndex = index;
  1487. const result = NON_WHITESPACE.exec(code);
  1488. return result.index;
  1489. }
  1490. const WHITESPACE = /\s/;
  1491. function findLastWhiteSpaceReverse(code, start, end) {
  1492. while (true) {
  1493. if (start >= end) {
  1494. return end;
  1495. }
  1496. if (WHITESPACE.test(code[end - 1])) {
  1497. end--;
  1498. }
  1499. else {
  1500. return end;
  1501. }
  1502. }
  1503. }
  1504. // This assumes "code" only contains white-space and comments
  1505. // Returns position of line-comment if applicable
  1506. function findFirstLineBreakOutsideComment(code) {
  1507. let lineBreakPos, charCodeAfterSlash, start = 0;
  1508. lineBreakPos = code.indexOf('\n', start);
  1509. while (true) {
  1510. start = code.indexOf('/', start);
  1511. if (start === -1 || start > lineBreakPos)
  1512. return [lineBreakPos, lineBreakPos + 1];
  1513. // With our assumption, '/' always starts a comment. Determine comment type:
  1514. charCodeAfterSlash = code.charCodeAt(start + 1);
  1515. if (charCodeAfterSlash === 47 /*"/"*/)
  1516. return [start, lineBreakPos + 1];
  1517. start = code.indexOf('*/', start + 2) + 2;
  1518. if (start > lineBreakPos) {
  1519. lineBreakPos = code.indexOf('\n', start);
  1520. }
  1521. }
  1522. }
  1523. function renderStatementList(statements, code, start, end, options) {
  1524. let currentNode, currentNodeStart, currentNodeNeedsBoundaries, nextNodeStart;
  1525. let nextNode = statements[0];
  1526. let nextNodeNeedsBoundaries = !nextNode.included || nextNode.needsBoundaries;
  1527. if (nextNodeNeedsBoundaries) {
  1528. nextNodeStart =
  1529. start + findFirstLineBreakOutsideComment(code.original.slice(start, nextNode.start))[1];
  1530. }
  1531. for (let nextIndex = 1; nextIndex <= statements.length; nextIndex++) {
  1532. currentNode = nextNode;
  1533. currentNodeStart = nextNodeStart;
  1534. currentNodeNeedsBoundaries = nextNodeNeedsBoundaries;
  1535. nextNode = statements[nextIndex];
  1536. nextNodeNeedsBoundaries =
  1537. nextNode === undefined ? false : !nextNode.included || nextNode.needsBoundaries;
  1538. if (currentNodeNeedsBoundaries || nextNodeNeedsBoundaries) {
  1539. nextNodeStart =
  1540. currentNode.end +
  1541. findFirstLineBreakOutsideComment(code.original.slice(currentNode.end, nextNode === undefined ? end : nextNode.start))[1];
  1542. if (currentNode.included) {
  1543. if (currentNodeNeedsBoundaries) {
  1544. currentNode.render(code, options, {
  1545. end: nextNodeStart,
  1546. start: currentNodeStart
  1547. });
  1548. }
  1549. else {
  1550. currentNode.render(code, options);
  1551. }
  1552. }
  1553. else {
  1554. treeshakeNode(currentNode, code, currentNodeStart, nextNodeStart);
  1555. }
  1556. }
  1557. else {
  1558. currentNode.render(code, options);
  1559. }
  1560. }
  1561. }
  1562. // This assumes that the first character is not part of the first node
  1563. function getCommaSeparatedNodesWithBoundaries(nodes, code, start, end) {
  1564. const splitUpNodes = [];
  1565. let node, nextNodeStart, contentEnd, char;
  1566. let separator = start - 1;
  1567. for (const nextNode of nodes) {
  1568. if (node !== undefined) {
  1569. separator =
  1570. node.end +
  1571. findFirstOccurrenceOutsideComment(code.original.slice(node.end, nextNode.start), ',');
  1572. }
  1573. nextNodeStart = contentEnd =
  1574. separator +
  1575. 1 +
  1576. findFirstLineBreakOutsideComment(code.original.slice(separator + 1, nextNode.start))[1];
  1577. while (((char = code.original.charCodeAt(nextNodeStart)),
  1578. char === 32 /*" "*/ || char === 9 /*"\t"*/ || char === 10 /*"\n"*/ || char === 13) /*"\r"*/)
  1579. nextNodeStart++;
  1580. if (node !== undefined) {
  1581. splitUpNodes.push({
  1582. contentEnd,
  1583. end: nextNodeStart,
  1584. node,
  1585. separator,
  1586. start
  1587. });
  1588. }
  1589. node = nextNode;
  1590. start = nextNodeStart;
  1591. }
  1592. splitUpNodes.push({
  1593. contentEnd: end,
  1594. end,
  1595. node: node,
  1596. separator: null,
  1597. start
  1598. });
  1599. return splitUpNodes;
  1600. }
  1601. // This assumes there are only white-space and comments between start and end
  1602. function removeLineBreaks(code, start, end) {
  1603. while (true) {
  1604. const [removeStart, removeEnd] = findFirstLineBreakOutsideComment(code.original.slice(start, end));
  1605. if (removeStart === -1) {
  1606. break;
  1607. }
  1608. code.remove(start + removeStart, (start += removeEnd));
  1609. }
  1610. }
  1611. function getSystemExportStatement(exportedVariables, { exportNamesByVariable, snippets: { _, getObject, getPropertyAccess } }, modifier = '') {
  1612. if (exportedVariables.length === 1 &&
  1613. exportNamesByVariable.get(exportedVariables[0]).length === 1) {
  1614. const variable = exportedVariables[0];
  1615. return `exports(${JSON.stringify(exportNamesByVariable.get(variable)[0])},${_}${variable.getName(getPropertyAccess)}${modifier})`;
  1616. }
  1617. else {
  1618. const fields = [];
  1619. for (const variable of exportedVariables) {
  1620. for (const exportName of exportNamesByVariable.get(variable)) {
  1621. fields.push([exportName, variable.getName(getPropertyAccess) + modifier]);
  1622. }
  1623. }
  1624. return `exports(${getObject(fields, { lineBreakIndent: null })})`;
  1625. }
  1626. }
  1627. // This is only invoked if there is exactly one export name
  1628. function renderSystemExportExpression(exportedVariable, expressionStart, expressionEnd, code, { exportNamesByVariable, snippets: { _ } }) {
  1629. code.prependRight(expressionStart, `exports(${JSON.stringify(exportNamesByVariable.get(exportedVariable)[0])},${_}`);
  1630. code.appendLeft(expressionEnd, ')');
  1631. }
  1632. function renderSystemExportFunction(exportedVariables, expressionStart, expressionEnd, needsParens, code, options) {
  1633. const { _, getDirectReturnIifeLeft } = options.snippets;
  1634. code.prependRight(expressionStart, getDirectReturnIifeLeft(['v'], `${getSystemExportStatement(exportedVariables, options)},${_}v`, { needsArrowReturnParens: true, needsWrappedFunction: needsParens }));
  1635. code.appendLeft(expressionEnd, ')');
  1636. }
  1637. function renderSystemExportSequenceAfterExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options) {
  1638. const { _, getPropertyAccess } = options.snippets;
  1639. code.appendLeft(expressionEnd, `,${_}${getSystemExportStatement([exportedVariable], options)},${_}${exportedVariable.getName(getPropertyAccess)}`);
  1640. if (needsParens) {
  1641. code.prependRight(expressionStart, '(');
  1642. code.appendLeft(expressionEnd, ')');
  1643. }
  1644. }
  1645. function renderSystemExportSequenceBeforeExpression(exportedVariable, expressionStart, expressionEnd, needsParens, code, options, modifier) {
  1646. const { _ } = options.snippets;
  1647. code.prependRight(expressionStart, `${getSystemExportStatement([exportedVariable], options, modifier)},${_}`);
  1648. if (needsParens) {
  1649. code.prependRight(expressionStart, '(');
  1650. code.appendLeft(expressionEnd, ')');
  1651. }
  1652. }
  1653. function getOrCreate(map, key, init) {
  1654. const existing = map.get(key);
  1655. if (existing !== undefined) {
  1656. return existing;
  1657. }
  1658. const value = init();
  1659. map.set(key, value);
  1660. return value;
  1661. }
  1662. function getNewSet() {
  1663. return new Set();
  1664. }
  1665. function getNewArray() {
  1666. return [];
  1667. }
  1668. const UnknownKey = Symbol('Unknown Key');
  1669. const UnknownNonAccessorKey = Symbol('Unknown Non-Accessor Key');
  1670. const UnknownInteger = Symbol('Unknown Integer');
  1671. const UnknownWellKnown = Symbol('Unknown Well-Known');
  1672. const SymbolToStringTag = Symbol('Symbol.toStringTag');
  1673. const SymbolDispose = Symbol('Symbol.asyncDispose');
  1674. const SymbolAsyncDispose = Symbol('Symbol.dispose');
  1675. const SymbolHasInstance = Symbol('Symbol.hasInstance');
  1676. const WELL_KNOWN_SYMBOLS_LIST = [
  1677. SymbolToStringTag,
  1678. SymbolDispose,
  1679. SymbolAsyncDispose,
  1680. SymbolHasInstance
  1681. ];
  1682. const WELL_KNOWN_SYMBOLS = new Set(WELL_KNOWN_SYMBOLS_LIST);
  1683. const isAnyWellKnown = (v) => WELL_KNOWN_SYMBOLS.has(v) || v === UnknownWellKnown;
  1684. const TREE_SHAKEABLE_SYMBOLS_LIST = [SymbolHasInstance, SymbolDispose, SymbolAsyncDispose];
  1685. const TREE_SHAKEABLE_SYMBOLS = new Set(TREE_SHAKEABLE_SYMBOLS_LIST);
  1686. const isConcreteKey = (v) => typeof v === 'string' || WELL_KNOWN_SYMBOLS.has(v);
  1687. const EMPTY_PATH = [];
  1688. const UNKNOWN_PATH = [UnknownKey];
  1689. // For deoptimizations, this means we are modifying an unknown property but did
  1690. // not lose track of the object or are creating a setter/getter;
  1691. // For assignment effects it means we do not check for setter/getter effects
  1692. // but only if something is mutated that is included, which is relevant for
  1693. // Object.defineProperty
  1694. const UNKNOWN_NON_ACCESSOR_PATH = [UnknownNonAccessorKey];
  1695. const UNKNOWN_INTEGER_PATH = [UnknownInteger];
  1696. const INSTANCEOF_PATH = [SymbolHasInstance];
  1697. const EntitiesKey = Symbol('Entities');
  1698. class EntityPathTracker {
  1699. constructor() {
  1700. this.entityPaths = Object.create(null, {
  1701. [EntitiesKey]: { value: new Set() }
  1702. });
  1703. }
  1704. trackEntityAtPathAndGetIfTracked(path, entity) {
  1705. const trackedEntities = this.getEntities(path);
  1706. if (trackedEntities.has(entity))
  1707. return true;
  1708. trackedEntities.add(entity);
  1709. return false;
  1710. }
  1711. withTrackedEntityAtPath(path, entity, onUntracked, returnIfTracked) {
  1712. const trackedEntities = this.getEntities(path);
  1713. if (trackedEntities.has(entity))
  1714. return returnIfTracked;
  1715. trackedEntities.add(entity);
  1716. const result = onUntracked();
  1717. trackedEntities.delete(entity);
  1718. return result;
  1719. }
  1720. getEntities(path) {
  1721. let currentPaths = this.entityPaths;
  1722. for (const pathSegment of path) {
  1723. currentPaths = currentPaths[pathSegment] ||= Object.create(null, {
  1724. [EntitiesKey]: { value: new Set() }
  1725. });
  1726. }
  1727. return currentPaths[EntitiesKey];
  1728. }
  1729. }
  1730. const SHARED_RECURSION_TRACKER = new EntityPathTracker();
  1731. class DiscriminatedPathTracker {
  1732. constructor() {
  1733. this.entityPaths = Object.create(null, {
  1734. [EntitiesKey]: { value: new Map() }
  1735. });
  1736. }
  1737. trackEntityAtPathAndGetIfTracked(path, discriminator, entity) {
  1738. let currentPaths = this.entityPaths;
  1739. for (const pathSegment of path) {
  1740. currentPaths = currentPaths[pathSegment] ||= Object.create(null, {
  1741. [EntitiesKey]: { value: new Map() }
  1742. });
  1743. }
  1744. const trackedEntities = getOrCreate(currentPaths[EntitiesKey], discriminator, (getNewSet));
  1745. if (trackedEntities.has(entity))
  1746. return true;
  1747. trackedEntities.add(entity);
  1748. return false;
  1749. }
  1750. }
  1751. const UNKNOWN_INCLUDED_PATH = Object.freeze({ [UnknownKey]: EMPTY_OBJECT });
  1752. class IncludedFullPathTracker {
  1753. constructor() {
  1754. this.includedPaths = null;
  1755. }
  1756. includePathAndGetIfIncluded(path) {
  1757. let included = true;
  1758. let parent = this;
  1759. let parentSegment = 'includedPaths';
  1760. let currentPaths = (this.includedPaths ||=
  1761. ((included = false), Object.create(null)));
  1762. for (const pathSegment of path) {
  1763. // This means from here, all paths are included
  1764. if (currentPaths[UnknownKey]) {
  1765. return true;
  1766. }
  1767. // Including UnknownKey automatically includes all nested paths.
  1768. // From above, we know that UnknownKey is not included yet.
  1769. if (!isConcreteKey(pathSegment)) {
  1770. // Hopefully, this saves some memory over just setting
  1771. // currentPaths[UnknownKey] = EMPTY_OBJECT
  1772. parent[parentSegment] = UNKNOWN_INCLUDED_PATH;
  1773. return false;
  1774. }
  1775. parent = currentPaths;
  1776. parentSegment = pathSegment;
  1777. currentPaths = currentPaths[pathSegment] ||= ((included = false), Object.create(null));
  1778. }
  1779. return included;
  1780. }
  1781. }
  1782. const UNKNOWN_INCLUDED_TOP_LEVEL_PATH = Object.freeze({
  1783. [UnknownKey]: true
  1784. });
  1785. class IncludedTopLevelPathTracker {
  1786. constructor() {
  1787. this.includedPaths = null;
  1788. }
  1789. includePathAndGetIfIncluded(path) {
  1790. let included = true;
  1791. const includedPaths = (this.includedPaths ||=
  1792. ((included = false), Object.create(null)));
  1793. if (includedPaths[UnknownKey]) {
  1794. return true;
  1795. }
  1796. const [firstPathSegment, secondPathSegment] = path;
  1797. if (!firstPathSegment) {
  1798. return included;
  1799. }
  1800. if (!isConcreteKey(firstPathSegment)) {
  1801. this.includedPaths = UNKNOWN_INCLUDED_TOP_LEVEL_PATH;
  1802. return false;
  1803. }
  1804. if (secondPathSegment) {
  1805. if (includedPaths[firstPathSegment] === UnknownKey) {
  1806. return true;
  1807. }
  1808. includedPaths[firstPathSegment] = UnknownKey;
  1809. return false;
  1810. }
  1811. if (includedPaths[firstPathSegment]) {
  1812. return true;
  1813. }
  1814. includedPaths[firstPathSegment] = true;
  1815. return false;
  1816. }
  1817. includeAllPaths(entity, context, basePath) {
  1818. const { includedPaths } = this;
  1819. if (includedPaths) {
  1820. if (includedPaths[UnknownKey]) {
  1821. entity.includePath([...basePath, UnknownKey], context);
  1822. }
  1823. else {
  1824. const inclusionEntries = Object.entries(includedPaths);
  1825. if (inclusionEntries.length === 0) {
  1826. entity.includePath(basePath, context);
  1827. }
  1828. else {
  1829. for (const [key, value] of inclusionEntries) {
  1830. entity.includePath(value === UnknownKey ? [...basePath, key, UnknownKey] : [...basePath, key], context);
  1831. }
  1832. }
  1833. }
  1834. }
  1835. }
  1836. }
  1837. /** @import { Node } from 'estree' */
  1838. /**
  1839. * @param {Node} node
  1840. * @param {Node} parent
  1841. * @returns {boolean}
  1842. */
  1843. function is_reference(node, parent) {
  1844. if (node.type === 'MemberExpression') {
  1845. return !node.computed && is_reference(node.object, node);
  1846. }
  1847. if (node.type !== 'Identifier') return false;
  1848. switch (parent?.type) {
  1849. // disregard `bar` in `foo.bar`
  1850. case 'MemberExpression':
  1851. return parent.computed || node === parent.object;
  1852. // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}`
  1853. case 'MethodDefinition':
  1854. return parent.computed;
  1855. // disregard the `meta` in `import.meta`
  1856. case 'MetaProperty':
  1857. return parent.meta === node;
  1858. // disregard the `foo` in `class {foo=bar}` but keep it in `class {[foo]=bar}` and `class {bar=foo}`
  1859. case 'PropertyDefinition':
  1860. return parent.computed || node === parent.value;
  1861. // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
  1862. case 'Property':
  1863. return parent.computed || node === parent.value;
  1864. // disregard the `bar` in `export { foo as bar }` or
  1865. // the foo in `import { foo as bar }`
  1866. case 'ExportSpecifier':
  1867. case 'ImportSpecifier':
  1868. return node === parent.local;
  1869. // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}`
  1870. case 'LabeledStatement':
  1871. case 'BreakStatement':
  1872. case 'ContinueStatement':
  1873. return false;
  1874. default:
  1875. return true;
  1876. }
  1877. }
  1878. function createInclusionContext() {
  1879. return {
  1880. brokenFlow: false,
  1881. hasBreak: false,
  1882. hasContinue: false,
  1883. includedCallArguments: new Set(),
  1884. includedLabels: new Set()
  1885. };
  1886. }
  1887. function createHasEffectsContext() {
  1888. return {
  1889. accessed: new EntityPathTracker(),
  1890. assigned: new EntityPathTracker(),
  1891. brokenFlow: false,
  1892. called: new DiscriminatedPathTracker(),
  1893. hasBreak: false,
  1894. hasContinue: false,
  1895. ignore: {
  1896. breaks: false,
  1897. continues: false,
  1898. labels: new Set(),
  1899. returnYield: false,
  1900. this: false
  1901. },
  1902. includedLabels: new Set(),
  1903. instantiated: new DiscriminatedPathTracker(),
  1904. replacedVariableInits: new Map()
  1905. };
  1906. }
  1907. function isFlagSet(flags, flag) {
  1908. return (flags & flag) !== 0;
  1909. }
  1910. function setFlag(flags, flag, value) {
  1911. return (flags & ~flag) | (-value & flag);
  1912. }
  1913. const UnknownValue = Symbol('Unknown Value');
  1914. const UnknownTruthyValue = Symbol('Unknown Truthy Value');
  1915. const UnknownFalsyValue = Symbol('Unknown Falsy Value');
  1916. class ExpressionEntity {
  1917. constructor() {
  1918. this.flags = 0;
  1919. }
  1920. get included() {
  1921. return isFlagSet(this.flags, 1 /* Flag.included */);
  1922. }
  1923. set included(value) {
  1924. this.flags = setFlag(this.flags, 1 /* Flag.included */, value);
  1925. }
  1926. deoptimizeArgumentsOnInteractionAtPath(interaction, _path, _recursionTracker) {
  1927. deoptimizeInteraction(interaction);
  1928. }
  1929. deoptimizePath(_path) { }
  1930. /**
  1931. * If possible it returns a stringifyable literal value for this node that
  1932. * can be used for inlining or comparing values. Otherwise, it should return
  1933. * UnknownValue.
  1934. */
  1935. getLiteralValueAtPath(_path, _recursionTracker, _origin) {
  1936. return UnknownValue;
  1937. }
  1938. getReturnExpressionWhenCalledAtPath(_path, _interaction, _recursionTracker, _origin) {
  1939. return UNKNOWN_RETURN_EXPRESSION;
  1940. }
  1941. hasEffectsOnInteractionAtPath(_path, _interaction, _context) {
  1942. return true;
  1943. }
  1944. include(context, _includeChildrenRecursively, _options) {
  1945. if (!this.included)
  1946. this.includeNode(context);
  1947. }
  1948. includeNode(_context) {
  1949. this.included = true;
  1950. }
  1951. includePath(_path, context) {
  1952. if (!this.included)
  1953. this.includeNode(context);
  1954. }
  1955. /* We are both including and including an unknown path here as the former
  1956. * ensures that nested nodes are included while the latter ensures that all
  1957. * paths of the expression are included.
  1958. * */
  1959. includeCallArguments(interaction, context) {
  1960. includeInteraction(interaction, context);
  1961. }
  1962. shouldBeIncluded(_context) {
  1963. return true;
  1964. }
  1965. }
  1966. const UNKNOWN_EXPRESSION = new (class UnknownExpression extends ExpressionEntity {
  1967. })();
  1968. const UNKNOWN_RETURN_EXPRESSION = [
  1969. UNKNOWN_EXPRESSION,
  1970. false
  1971. ];
  1972. const deoptimizeInteraction = (interaction) => {
  1973. for (const argument of interaction.args) {
  1974. argument?.deoptimizePath(UNKNOWN_PATH);
  1975. }
  1976. };
  1977. const includeInteraction = (interaction, context) => {
  1978. // We do not re-include the "this" argument as we expect this is already
  1979. // re-included at the call site
  1980. interaction.args[0]?.includePath(UNKNOWN_PATH, context);
  1981. includeInteractionWithoutThis(interaction, context);
  1982. };
  1983. const includeInteractionWithoutThis = ({ args }, context) => {
  1984. for (let argumentIndex = 1; argumentIndex < args.length; argumentIndex++) {
  1985. const argument = args[argumentIndex];
  1986. if (argument) {
  1987. argument.includePath(UNKNOWN_PATH, context);
  1988. argument.include(context, false);
  1989. }
  1990. }
  1991. };
  1992. const INTERACTION_ACCESSED = 0;
  1993. const INTERACTION_ASSIGNED = 1;
  1994. const INTERACTION_CALLED = 2;
  1995. const NODE_INTERACTION_UNKNOWN_ACCESS = {
  1996. args: [null],
  1997. type: INTERACTION_ACCESSED
  1998. };
  1999. const NODE_INTERACTION_UNKNOWN_ASSIGNMENT = {
  2000. args: [null, UNKNOWN_EXPRESSION],
  2001. type: INTERACTION_ASSIGNED
  2002. };
  2003. // While this is technically a call without arguments, we can compare against
  2004. // this reference in places where precise values or this argument would make a
  2005. // difference
  2006. const NODE_INTERACTION_UNKNOWN_CALL = {
  2007. args: [null],
  2008. type: INTERACTION_CALLED,
  2009. withNew: false
  2010. };
  2011. const PureFunctionKey = Symbol('PureFunction');
  2012. const getPureFunctions = ({ treeshake }) => {
  2013. const pureFunctions = Object.create(null);
  2014. for (const functionName of treeshake ? treeshake.manualPureFunctions : []) {
  2015. let currentFunctions = pureFunctions;
  2016. for (const pathSegment of functionName.split('.')) {
  2017. currentFunctions = currentFunctions[pathSegment] ||= Object.create(null);
  2018. }
  2019. currentFunctions[PureFunctionKey] = true;
  2020. }
  2021. return pureFunctions;
  2022. };
  2023. class Variable extends ExpressionEntity {
  2024. markReassigned() {
  2025. this.isReassigned = true;
  2026. }
  2027. constructor(name) {
  2028. super();
  2029. this.name = name;
  2030. this.alwaysRendered = false;
  2031. this.forbiddenNames = null;
  2032. this.globalName = null;
  2033. this.initReached = false;
  2034. this.isId = false;
  2035. this.kind = null;
  2036. this.renderBaseName = null;
  2037. this.renderName = null;
  2038. this.isReassigned = false;
  2039. this.onlyFunctionCallUsed = true;
  2040. }
  2041. /**
  2042. * Binds identifiers that reference this variable to this variable.
  2043. * Necessary to be able to change variable names.
  2044. */
  2045. addReference(_identifier) { }
  2046. /**
  2047. * Check if the identifier variable is only used as function call
  2048. * @returns true if the variable is only used as function call
  2049. */
  2050. getOnlyFunctionCallUsed() {
  2051. return this.onlyFunctionCallUsed;
  2052. }
  2053. /**
  2054. * Collect the places where the identifier variable is used
  2055. * @param usedPlace Where the variable is used
  2056. */
  2057. addUsedPlace(usedPlace) {
  2058. const isFunctionCall = usedPlace.parent.type === CallExpression$1 &&
  2059. usedPlace.parent.callee === usedPlace;
  2060. if (!isFunctionCall && usedPlace.parent.type !== ExportDefaultDeclaration$1) {
  2061. this.onlyFunctionCallUsed = false;
  2062. }
  2063. }
  2064. /**
  2065. * Prevent this variable from being renamed to this name to avoid name
  2066. * collisions
  2067. */
  2068. forbidName(name) {
  2069. (this.forbiddenNames ||= new Set()).add(name);
  2070. }
  2071. getBaseVariableName() {
  2072. return (this.renderedLikeHoisted?.getBaseVariableName() ||
  2073. this.renderBaseName ||
  2074. this.renderName ||
  2075. this.name);
  2076. }
  2077. getName(getPropertyAccess, useOriginalName) {
  2078. if (this.globalName) {
  2079. return this.globalName;
  2080. }
  2081. if (useOriginalName?.(this)) {
  2082. return this.name;
  2083. }
  2084. if (this.renderedLikeHoisted) {
  2085. return this.renderedLikeHoisted.getName(getPropertyAccess, useOriginalName);
  2086. }
  2087. const name = this.renderName || this.name;
  2088. return this.renderBaseName ? `${this.renderBaseName}${getPropertyAccess(name)}` : name;
  2089. }
  2090. hasEffectsOnInteractionAtPath(path, { type }, _context) {
  2091. return type !== INTERACTION_ACCESSED || path.length > 0;
  2092. }
  2093. /**
  2094. * Marks this variable as being part of the bundle, which is usually the case
  2095. * when one of its identifiers becomes part of the bundle. Returns true if it
  2096. * has not been included previously. Once a variable is included, it should
  2097. * take care all its declarations are included.
  2098. */
  2099. includePath(path, context) {
  2100. this.included = true;
  2101. this.renderedLikeHoisted?.includePath(path, context);
  2102. }
  2103. /**
  2104. * Links the rendered name of this variable to another variable and includes
  2105. * this variable if the other variable is included.
  2106. */
  2107. renderLikeHoisted(variable) {
  2108. this.renderedLikeHoisted = variable;
  2109. }
  2110. markCalledFromTryStatement() { }
  2111. setRenderNames(baseName, name) {
  2112. this.renderBaseName = baseName;
  2113. this.renderName = name;
  2114. }
  2115. }
  2116. /** Synthetic import name for source phase imports, similar to '*' for namespaces */
  2117. const SOURCE_PHASE_IMPORT = '*source';
  2118. class ExternalVariable extends Variable {
  2119. constructor(module, name) {
  2120. super(name);
  2121. this.referenced = false;
  2122. this.module = module;
  2123. this.isNamespace = name === '*';
  2124. this.isSourcePhase = name === SOURCE_PHASE_IMPORT;
  2125. }
  2126. addReference(identifier) {
  2127. this.referenced = true;
  2128. if (this.name === 'default' || this.name === '*') {
  2129. this.module.suggestName(identifier.name);
  2130. }
  2131. }
  2132. hasEffectsOnInteractionAtPath(path, { type }) {
  2133. return type !== INTERACTION_ACCESSED || path.length > (this.isNamespace ? 1 : 0);
  2134. }
  2135. includePath(path, context) {
  2136. super.includePath(path, context);
  2137. this.module.used = true;
  2138. }
  2139. }
  2140. function cacheObjectGetters(object, getterProperties) {
  2141. for (const property of getterProperties) {
  2142. const propertyGetter = Object.getOwnPropertyDescriptor(object, property).get;
  2143. Object.defineProperty(object, property, {
  2144. get() {
  2145. const value = propertyGetter.call(object);
  2146. // This replaces the getter with a fixed value for subsequent calls
  2147. Object.defineProperty(object, property, { value });
  2148. return value;
  2149. }
  2150. });
  2151. }
  2152. }
  2153. const RESERVED_NAMES = new Set([
  2154. 'await',
  2155. 'break',
  2156. 'case',
  2157. 'catch',
  2158. 'class',
  2159. 'const',
  2160. 'continue',
  2161. 'debugger',
  2162. 'default',
  2163. 'delete',
  2164. 'do',
  2165. 'else',
  2166. 'enum',
  2167. 'eval',
  2168. 'export',
  2169. 'exports',
  2170. 'extends',
  2171. 'false',
  2172. 'finally',
  2173. 'for',
  2174. 'function',
  2175. 'if',
  2176. 'implements',
  2177. 'import',
  2178. 'in',
  2179. 'instanceof',
  2180. 'interface',
  2181. 'let',
  2182. 'NaN',
  2183. 'new',
  2184. 'null',
  2185. 'package',
  2186. 'private',
  2187. 'protected',
  2188. 'public',
  2189. 'return',
  2190. 'static',
  2191. 'super',
  2192. 'switch',
  2193. 'this',
  2194. 'throw',
  2195. 'true',
  2196. 'try',
  2197. 'typeof',
  2198. 'undefined',
  2199. 'var',
  2200. 'void',
  2201. 'while',
  2202. 'with',
  2203. 'yield'
  2204. ]);
  2205. const illegalCharacters = /[^\w$]/g;
  2206. const startsWithDigit = (value) => /\d/.test(value[0]);
  2207. const needsEscape = (value) => startsWithDigit(value) || RESERVED_NAMES.has(value) || value === 'arguments';
  2208. function isLegal(value) {
  2209. if (needsEscape(value)) {
  2210. return false;
  2211. }
  2212. return !illegalCharacters.test(value);
  2213. }
  2214. function makeLegal(value) {
  2215. value = value
  2216. .replace(/-(\w)/g, (_, letter) => letter.toUpperCase())
  2217. .replace(illegalCharacters, '_');
  2218. if (needsEscape(value))
  2219. value = `_${value}`;
  2220. return value || '_';
  2221. }
  2222. const VALID_IDENTIFIER_REGEXP = /^[$_\p{ID_Start}][$\u200C\u200D\p{ID_Continue}]*$/u;
  2223. const NUMBER_REGEXP = /^(?:0|[1-9]\d*)$/;
  2224. function stringifyObjectKeyIfNeeded(key) {
  2225. if (VALID_IDENTIFIER_REGEXP.test(key)) {
  2226. return key === '__proto__' ? '["__proto__"]' : key;
  2227. }
  2228. if (NUMBER_REGEXP.test(key) && +key <= Number.MAX_SAFE_INTEGER) {
  2229. return key;
  2230. }
  2231. return JSON.stringify(key);
  2232. }
  2233. function stringifyIdentifierIfNeeded(key) {
  2234. if (VALID_IDENTIFIER_REGEXP.test(key)) {
  2235. return key;
  2236. }
  2237. return JSON.stringify(key);
  2238. }
  2239. class ExternalModule {
  2240. constructor(options, id, moduleSideEffects, meta, renormalizeRenderPath, attributes) {
  2241. this.options = options;
  2242. this.id = id;
  2243. this.renormalizeRenderPath = renormalizeRenderPath;
  2244. this.dynamicImporters = [];
  2245. this.execIndex = Infinity;
  2246. this.exportedVariables = new Map();
  2247. this.importers = [];
  2248. this.reexported = false;
  2249. this.used = false;
  2250. this.declarations = new Map();
  2251. this.importersByExportedName = new Map();
  2252. this.mostCommonSuggestion = 0;
  2253. this.nameSuggestions = new Map();
  2254. this.suggestedVariableName = makeLegal(id.split(/[/\\]/).pop());
  2255. const { importers, dynamicImporters } = this;
  2256. this.info = {
  2257. ast: null,
  2258. attributes,
  2259. code: null,
  2260. dynamicallyImportedIdResolutions: EMPTY_ARRAY,
  2261. dynamicallyImportedIds: EMPTY_ARRAY,
  2262. get dynamicImporters() {
  2263. return dynamicImporters.sort();
  2264. },
  2265. exportedBindings: null,
  2266. exports: null,
  2267. hasDefaultExport: null,
  2268. id,
  2269. implicitlyLoadedAfterOneOf: EMPTY_ARRAY,
  2270. implicitlyLoadedBefore: EMPTY_ARRAY,
  2271. importedIdResolutions: EMPTY_ARRAY,
  2272. importedIds: EMPTY_ARRAY,
  2273. get importers() {
  2274. return importers.sort();
  2275. },
  2276. isEntry: false,
  2277. isExternal: true,
  2278. isIncluded: null,
  2279. meta,
  2280. moduleSideEffects,
  2281. safeVariableNames: null,
  2282. syntheticNamedExports: false
  2283. };
  2284. }
  2285. cacheInfoGetters() {
  2286. cacheObjectGetters(this.info, ['dynamicImporters', 'importers']);
  2287. }
  2288. getVariableForExportName(name, { importChain }) {
  2289. const declaration = this.declarations.get(name);
  2290. for (const module of importChain) {
  2291. getOrCreate(this.importersByExportedName, name, getNewSet).add(module);
  2292. }
  2293. if (declaration)
  2294. return [declaration];
  2295. const externalVariable = new ExternalVariable(this, name);
  2296. this.declarations.set(name, externalVariable);
  2297. this.exportedVariables.set(externalVariable, name);
  2298. return [externalVariable];
  2299. }
  2300. suggestName(name) {
  2301. const value = (this.nameSuggestions.get(name) ?? 0) + 1;
  2302. this.nameSuggestions.set(name, value);
  2303. if (value > this.mostCommonSuggestion) {
  2304. this.mostCommonSuggestion = value;
  2305. this.suggestedVariableName = name;
  2306. }
  2307. }
  2308. warnUnusedImports() {
  2309. const unused = [...this.declarations]
  2310. .filter(([name, declaration]) => name !== '*' && !declaration.included && !this.reexported && !declaration.referenced)
  2311. .map(([name]) => name);
  2312. if (unused.length === 0)
  2313. return;
  2314. const importersSet = new Set();
  2315. for (const name of unused) {
  2316. const importersOfName = this.importersByExportedName.get(name);
  2317. for (const importer of this.importers) {
  2318. if (!importersOfName?.has(importer))
  2319. continue;
  2320. importersSet.add(importer);
  2321. }
  2322. }
  2323. const importersArray = [...importersSet];
  2324. this.options.onLog(LOGLEVEL_WARN, logUnusedExternalImports(this.id, unused, importersArray));
  2325. }
  2326. }
  2327. function markModuleAndImpureDependenciesAsExecuted(baseModule) {
  2328. baseModule.isExecuted = true;
  2329. const modules = [baseModule];
  2330. const visitedModules = new Set();
  2331. for (const module of modules) {
  2332. for (const dependency of [...module.dependencies, ...module.implicitlyLoadedBefore]) {
  2333. if (!(dependency instanceof ExternalModule) &&
  2334. !dependency.isExecuted &&
  2335. (dependency.info.moduleSideEffects || module.implicitlyLoadedBefore.has(dependency)) &&
  2336. !visitedModules.has(dependency.id)) {
  2337. dependency.isExecuted = true;
  2338. visitedModules.add(dependency.id);
  2339. modules.push(dependency);
  2340. }
  2341. }
  2342. }
  2343. }
  2344. const doNothing = () => { };
  2345. // This file is generated by scripts/generate-child-node-keys.js.
  2346. // Do not edit this file directly.
  2347. const childNodeKeys = {
  2348. ArrayExpression: ['elements'],
  2349. ArrayPattern: ['elements'],
  2350. ArrowFunctionExpression: ['params', 'body'],
  2351. AssignmentExpression: ['left', 'right'],
  2352. AssignmentPattern: ['left', 'right'],
  2353. AwaitExpression: ['argument'],
  2354. BinaryExpression: ['left', 'right'],
  2355. BlockStatement: ['body'],
  2356. BreakStatement: ['label'],
  2357. CallExpression: ['callee', 'arguments'],
  2358. CatchClause: ['param', 'body'],
  2359. ChainExpression: ['expression'],
  2360. ClassBody: ['body'],
  2361. ClassDeclaration: ['decorators', 'id', 'superClass', 'body'],
  2362. ClassExpression: ['decorators', 'id', 'superClass', 'body'],
  2363. ConditionalExpression: ['test', 'consequent', 'alternate'],
  2364. ContinueStatement: ['label'],
  2365. DebuggerStatement: [],
  2366. Decorator: ['expression'],
  2367. DoWhileStatement: ['body', 'test'],
  2368. EmptyStatement: [],
  2369. ExportAllDeclaration: ['exported', 'source', 'attributes'],
  2370. ExportDefaultDeclaration: ['declaration'],
  2371. ExportNamedDeclaration: ['specifiers', 'source', 'attributes', 'declaration'],
  2372. ExportSpecifier: ['local', 'exported'],
  2373. ExpressionStatement: ['expression'],
  2374. ForInStatement: ['left', 'right', 'body'],
  2375. ForOfStatement: ['left', 'right', 'body'],
  2376. ForStatement: ['init', 'test', 'update', 'body'],
  2377. FunctionDeclaration: ['id', 'params', 'body'],
  2378. FunctionExpression: ['id', 'params', 'body'],
  2379. Identifier: [],
  2380. IfStatement: ['test', 'consequent', 'alternate'],
  2381. ImportAttribute: ['key', 'value'],
  2382. ImportDeclaration: ['specifiers', 'source', 'attributes'],
  2383. ImportDefaultSpecifier: ['local'],
  2384. ImportExpression: ['source', 'options'],
  2385. ImportNamespaceSpecifier: ['local'],
  2386. ImportSpecifier: ['imported', 'local'],
  2387. JSXAttribute: ['name', 'value'],
  2388. JSXClosingElement: ['name'],
  2389. JSXClosingFragment: [],
  2390. JSXElement: ['openingElement', 'children', 'closingElement'],
  2391. JSXEmptyExpression: [],
  2392. JSXExpressionContainer: ['expression'],
  2393. JSXFragment: ['openingFragment', 'children', 'closingFragment'],
  2394. JSXIdentifier: [],
  2395. JSXMemberExpression: ['object', 'property'],
  2396. JSXNamespacedName: ['namespace', 'name'],
  2397. JSXOpeningElement: ['name', 'attributes'],
  2398. JSXOpeningFragment: [],
  2399. JSXSpreadAttribute: ['argument'],
  2400. JSXSpreadChild: ['expression'],
  2401. JSXText: [],
  2402. LabeledStatement: ['label', 'body'],
  2403. Literal: [],
  2404. LogicalExpression: ['left', 'right'],
  2405. MemberExpression: ['object', 'property'],
  2406. MetaProperty: ['meta', 'property'],
  2407. MethodDefinition: ['decorators', 'key', 'value'],
  2408. NewExpression: ['callee', 'arguments'],
  2409. ObjectExpression: ['properties'],
  2410. ObjectPattern: ['properties'],
  2411. PanicError: [],
  2412. ParseError: [],
  2413. PrivateIdentifier: [],
  2414. Program: ['body'],
  2415. Property: ['key', 'value'],
  2416. PropertyDefinition: ['decorators', 'key', 'value'],
  2417. RestElement: ['argument'],
  2418. ReturnStatement: ['argument'],
  2419. SequenceExpression: ['expressions'],
  2420. SpreadElement: ['argument'],
  2421. StaticBlock: ['body'],
  2422. Super: [],
  2423. SwitchCase: ['test', 'consequent'],
  2424. SwitchStatement: ['discriminant', 'cases'],
  2425. TaggedTemplateExpression: ['tag', 'quasi'],
  2426. TemplateElement: [],
  2427. TemplateLiteral: ['quasis', 'expressions'],
  2428. ThisExpression: [],
  2429. ThrowStatement: ['argument'],
  2430. TryStatement: ['block', 'handler', 'finalizer'],
  2431. UnaryExpression: ['argument'],
  2432. UpdateExpression: ['argument'],
  2433. VariableDeclaration: ['declarations'],
  2434. VariableDeclarator: ['id', 'init'],
  2435. WhileStatement: ['test', 'body'],
  2436. YieldExpression: ['argument']
  2437. };
  2438. const INCLUDE_PARAMETERS = 'variables';
  2439. const IS_SKIPPED_CHAIN = Symbol('IS_SKIPPED_CHAIN');
  2440. class NodeBase extends ExpressionEntity {
  2441. /**
  2442. * Nodes can apply custom deoptimizations once they become part of the
  2443. * executed code. To do this, they must initialize this as false, implement
  2444. * applyDeoptimizations and call this from include and hasEffects if they have
  2445. * custom handlers
  2446. */
  2447. get deoptimized() {
  2448. return isFlagSet(this.flags, 2 /* Flag.deoptimized */);
  2449. }
  2450. set deoptimized(value) {
  2451. this.flags = setFlag(this.flags, 2 /* Flag.deoptimized */, value);
  2452. }
  2453. constructor(parent, parentScope) {
  2454. super();
  2455. this.parent = parent;
  2456. this.scope = parentScope;
  2457. this.createScope(parentScope);
  2458. }
  2459. addExportedVariables(_variables, _exportNamesByVariable) { }
  2460. /**
  2461. * Override this to bind assignments to variables and do any initialisations
  2462. * that require the scopes to be populated with variables.
  2463. */
  2464. bind() {
  2465. for (const key of childNodeKeys[this.type]) {
  2466. const value = this[key];
  2467. if (Array.isArray(value)) {
  2468. for (const child of value) {
  2469. child?.bind();
  2470. }
  2471. }
  2472. else if (value) {
  2473. value.bind();
  2474. }
  2475. }
  2476. }
  2477. /**
  2478. * Override if this node should receive a different scope than the parent
  2479. * scope.
  2480. */
  2481. createScope(parentScope) {
  2482. this.scope = parentScope;
  2483. }
  2484. hasEffects(context) {
  2485. if (!this.deoptimized)
  2486. this.applyDeoptimizations();
  2487. for (const key of childNodeKeys[this.type]) {
  2488. const value = this[key];
  2489. if (value === null)
  2490. continue;
  2491. if (Array.isArray(value)) {
  2492. for (const child of value) {
  2493. if (child?.hasEffects(context))
  2494. return true;
  2495. }
  2496. }
  2497. else if (value.hasEffects(context))
  2498. return true;
  2499. }
  2500. return false;
  2501. }
  2502. hasEffectsAsAssignmentTarget(context, _checkAccess) {
  2503. return (this.hasEffects(context) ||
  2504. this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
  2505. }
  2506. include(context, includeChildrenRecursively, _options) {
  2507. if (!this.included)
  2508. this.includeNode(context);
  2509. for (const key of childNodeKeys[this.type]) {
  2510. const value = this[key];
  2511. if (value === null)
  2512. continue;
  2513. if (Array.isArray(value)) {
  2514. for (const child of value) {
  2515. child?.include(context, includeChildrenRecursively);
  2516. }
  2517. }
  2518. else {
  2519. value.include(context, includeChildrenRecursively);
  2520. }
  2521. }
  2522. }
  2523. includeNode(context) {
  2524. this.included = true;
  2525. if (!this.deoptimized)
  2526. this.applyDeoptimizations();
  2527. for (const key of childNodeKeys[this.type]) {
  2528. const value = this[key];
  2529. if (value === null)
  2530. continue;
  2531. if (Array.isArray(value)) {
  2532. for (const child of value) {
  2533. child?.includePath(UNKNOWN_PATH, context);
  2534. }
  2535. }
  2536. else {
  2537. value.includePath(UNKNOWN_PATH, context);
  2538. }
  2539. }
  2540. }
  2541. includeAsAssignmentTarget(context, includeChildrenRecursively, _deoptimizeAccess) {
  2542. this.include(context, includeChildrenRecursively);
  2543. }
  2544. /**
  2545. * Override to perform special initialisation steps after the scope is
  2546. * initialised
  2547. */
  2548. initialise() {
  2549. this.scope.context.magicString.addSourcemapLocation(this.start);
  2550. this.scope.context.magicString.addSourcemapLocation(this.end);
  2551. }
  2552. parseNode(esTreeNode) {
  2553. for (const [key, value] of Object.entries(esTreeNode)) {
  2554. // Skip properties defined on the class already.
  2555. // This way, we can override this function to add custom initialisation and then call super.parseNode
  2556. // Note: this doesn't skip properties with defined getters/setters which we use to pack wrap booleans
  2557. // in bitfields. Those are still assigned from the value in the esTreeNode.
  2558. if (this.hasOwnProperty(key))
  2559. continue;
  2560. if (key.charCodeAt(0) === 95 /* _ */) {
  2561. if (key === ANNOTATION_KEY) {
  2562. this.annotations = value;
  2563. }
  2564. else if (key === INVALID_ANNOTATION_KEY) {
  2565. this.invalidAnnotations = value;
  2566. }
  2567. }
  2568. else if (typeof value !== 'object' || value === null) {
  2569. this[key] = value;
  2570. }
  2571. else if (Array.isArray(value)) {
  2572. this[key] = new Array(value.length);
  2573. let index = 0;
  2574. for (const child of value) {
  2575. this[key][index++] =
  2576. child === null
  2577. ? null
  2578. : new (this.scope.context.getNodeConstructor(child.type))(this, this.scope).parseNode(child);
  2579. }
  2580. }
  2581. else {
  2582. this[key] = new (this.scope.context.getNodeConstructor(value.type))(this, this.scope).parseNode(value);
  2583. }
  2584. }
  2585. // extend child keys for unknown node types
  2586. childNodeKeys[esTreeNode.type] ||= createChildNodeKeysForNode(esTreeNode);
  2587. this.initialise();
  2588. return this;
  2589. }
  2590. removeAnnotations(code) {
  2591. if (this.annotations) {
  2592. for (const annotation of this.annotations) {
  2593. code.remove(annotation.start, annotation.end);
  2594. }
  2595. }
  2596. }
  2597. render(code, options) {
  2598. for (const key of childNodeKeys[this.type]) {
  2599. const value = this[key];
  2600. if (value === null)
  2601. continue;
  2602. if (Array.isArray(value)) {
  2603. for (const child of value) {
  2604. child?.render(code, options);
  2605. }
  2606. }
  2607. else {
  2608. value.render(code, options);
  2609. }
  2610. }
  2611. }
  2612. setAssignedValue(value) {
  2613. this.assignmentInteraction = { args: [null, value], type: INTERACTION_ASSIGNED };
  2614. }
  2615. shouldBeIncluded(context) {
  2616. return this.included || (!context.brokenFlow && this.hasEffects(createHasEffectsContext()));
  2617. }
  2618. /**
  2619. * Just deoptimize everything by default so that when e.g. we do not track
  2620. * something properly, it is deoptimized.
  2621. * @protected
  2622. */
  2623. applyDeoptimizations() {
  2624. this.deoptimized = true;
  2625. for (const key of childNodeKeys[this.type]) {
  2626. const value = this[key];
  2627. if (value === null)
  2628. continue;
  2629. if (Array.isArray(value)) {
  2630. for (const child of value) {
  2631. child?.deoptimizePath(UNKNOWN_PATH);
  2632. }
  2633. }
  2634. else {
  2635. value.deoptimizePath(UNKNOWN_PATH);
  2636. }
  2637. }
  2638. this.scope.context.requestTreeshakingPass();
  2639. }
  2640. }
  2641. function createChildNodeKeysForNode(esTreeNode) {
  2642. return Object.keys(esTreeNode).filter(key => typeof esTreeNode[key] === 'object' && key.charCodeAt(0) !== 95 /* _ */);
  2643. }
  2644. function onlyIncludeSelf() {
  2645. this.included = true;
  2646. if (!this.deoptimized)
  2647. this.applyDeoptimizations();
  2648. }
  2649. function onlyIncludeSelfNoDeoptimize() {
  2650. this.included = true;
  2651. }
  2652. function doNotDeoptimize() {
  2653. this.deoptimized = true;
  2654. }
  2655. function isObjectExpressionNode(node) {
  2656. return node instanceof NodeBase && node.type === ObjectExpression$1;
  2657. }
  2658. function isPropertyNode(node) {
  2659. return node instanceof NodeBase && node.type === Property$1;
  2660. }
  2661. function isArrowFunctionExpressionNode(node) {
  2662. return node instanceof NodeBase && node.type === ArrowFunctionExpression$1;
  2663. }
  2664. function isFunctionExpressionNode(node) {
  2665. return node instanceof NodeBase && node.type === FunctionExpression$1;
  2666. }
  2667. function isCallExpressionNode(node) {
  2668. return node instanceof NodeBase && node.type === CallExpression$1;
  2669. }
  2670. function isMemberExpressionNode(node) {
  2671. return node instanceof NodeBase && node.type === MemberExpression$1;
  2672. }
  2673. function isAwaitExpressionNode(node) {
  2674. return node instanceof NodeBase && node.type === AwaitExpression$1;
  2675. }
  2676. function isIdentifierNode(node) {
  2677. return node instanceof NodeBase && node.type === Identifier$1;
  2678. }
  2679. function isExpressionStatementNode(node) {
  2680. return node instanceof NodeBase && node.type === ExpressionStatement$1;
  2681. }
  2682. function assembleMemberDescriptions(memberDescriptions, inheritedDescriptions = null) {
  2683. return Object.create(inheritedDescriptions, memberDescriptions);
  2684. }
  2685. const UNDEFINED_EXPRESSION = new (class UndefinedExpression extends ExpressionEntity {
  2686. getLiteralValueAtPath(path) {
  2687. return path.length > 0 ? UnknownValue : undefined;
  2688. }
  2689. })();
  2690. const returnsUnknown = {
  2691. value: {
  2692. hasEffectsWhenCalled: null,
  2693. returns: UNKNOWN_EXPRESSION
  2694. }
  2695. };
  2696. const UNKNOWN_LITERAL_BOOLEAN = new (class UnknownBoolean extends ExpressionEntity {
  2697. getReturnExpressionWhenCalledAtPath(path) {
  2698. if (path.length === 1) {
  2699. return getMemberReturnExpressionWhenCalled(literalBooleanMembers, path[0]);
  2700. }
  2701. return UNKNOWN_RETURN_EXPRESSION;
  2702. }
  2703. hasEffectsOnInteractionAtPath(path, interaction, context) {
  2704. if (interaction.type === INTERACTION_ACCESSED) {
  2705. return path.length > 1;
  2706. }
  2707. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  2708. return hasMemberEffectWhenCalled(literalBooleanMembers, path[0], interaction, context);
  2709. }
  2710. return true;
  2711. }
  2712. })();
  2713. const returnsBoolean = {
  2714. value: {
  2715. hasEffectsWhenCalled: null,
  2716. returns: UNKNOWN_LITERAL_BOOLEAN
  2717. }
  2718. };
  2719. const UNKNOWN_LITERAL_NUMBER = new (class UnknownNumber extends ExpressionEntity {
  2720. getReturnExpressionWhenCalledAtPath(path) {
  2721. if (path.length === 1) {
  2722. return getMemberReturnExpressionWhenCalled(literalNumberMembers, path[0]);
  2723. }
  2724. return UNKNOWN_RETURN_EXPRESSION;
  2725. }
  2726. hasEffectsOnInteractionAtPath(path, interaction, context) {
  2727. if (interaction.type === INTERACTION_ACCESSED) {
  2728. return path.length > 1;
  2729. }
  2730. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  2731. return hasMemberEffectWhenCalled(literalNumberMembers, path[0], interaction, context);
  2732. }
  2733. return true;
  2734. }
  2735. })();
  2736. const returnsNumber = {
  2737. value: {
  2738. hasEffectsWhenCalled: null,
  2739. returns: UNKNOWN_LITERAL_NUMBER
  2740. }
  2741. };
  2742. const UNKNOWN_LITERAL_STRING = new (class UnknownString extends ExpressionEntity {
  2743. getReturnExpressionWhenCalledAtPath(path) {
  2744. if (path.length === 1) {
  2745. return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
  2746. }
  2747. return UNKNOWN_RETURN_EXPRESSION;
  2748. }
  2749. hasEffectsOnInteractionAtPath(path, interaction, context) {
  2750. if (interaction.type === INTERACTION_ACCESSED) {
  2751. return path.length > 1;
  2752. }
  2753. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  2754. return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
  2755. }
  2756. return true;
  2757. }
  2758. })();
  2759. const returnsString = {
  2760. value: {
  2761. hasEffectsWhenCalled: null,
  2762. returns: UNKNOWN_LITERAL_STRING
  2763. }
  2764. };
  2765. const stringReplace = {
  2766. value: {
  2767. hasEffectsWhenCalled({ args }, context) {
  2768. const argument1 = args[2];
  2769. return (args.length < 3 ||
  2770. (typeof argument1.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, {
  2771. deoptimizeCache() { }
  2772. }) === 'symbol' &&
  2773. argument1.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)));
  2774. },
  2775. returns: UNKNOWN_LITERAL_STRING
  2776. }
  2777. };
  2778. const objectMembers = assembleMemberDescriptions({
  2779. hasOwnProperty: returnsBoolean,
  2780. isPrototypeOf: returnsBoolean,
  2781. propertyIsEnumerable: returnsBoolean,
  2782. toLocaleString: returnsString,
  2783. toString: returnsString,
  2784. valueOf: returnsUnknown
  2785. });
  2786. const literalBooleanMembers = assembleMemberDescriptions({
  2787. valueOf: returnsBoolean
  2788. }, objectMembers);
  2789. const literalNumberMembers = assembleMemberDescriptions({
  2790. toExponential: returnsString,
  2791. toFixed: returnsString,
  2792. toLocaleString: returnsString,
  2793. toPrecision: returnsString,
  2794. valueOf: returnsNumber
  2795. }, objectMembers);
  2796. /**
  2797. * RegExp are stateful when they have the global or sticky flags set.
  2798. * But if we actually don't use them, the side effect does not matter.
  2799. * the check logic in `hasEffectsOnInteractionAtPath`.
  2800. */
  2801. const literalRegExpMembers = assembleMemberDescriptions({
  2802. exec: returnsUnknown,
  2803. test: returnsBoolean
  2804. }, objectMembers);
  2805. const literalStringMembers = assembleMemberDescriptions({
  2806. anchor: returnsString,
  2807. at: returnsUnknown,
  2808. big: returnsString,
  2809. blink: returnsString,
  2810. bold: returnsString,
  2811. charAt: returnsString,
  2812. charCodeAt: returnsNumber,
  2813. codePointAt: returnsUnknown,
  2814. concat: returnsString,
  2815. endsWith: returnsBoolean,
  2816. fixed: returnsString,
  2817. fontcolor: returnsString,
  2818. fontsize: returnsString,
  2819. includes: returnsBoolean,
  2820. indexOf: returnsNumber,
  2821. italics: returnsString,
  2822. lastIndexOf: returnsNumber,
  2823. link: returnsString,
  2824. localeCompare: returnsNumber,
  2825. match: returnsUnknown,
  2826. matchAll: returnsUnknown,
  2827. normalize: returnsString,
  2828. padEnd: returnsString,
  2829. padStart: returnsString,
  2830. repeat: returnsString,
  2831. replace: stringReplace,
  2832. replaceAll: stringReplace,
  2833. search: returnsNumber,
  2834. slice: returnsString,
  2835. small: returnsString,
  2836. split: returnsUnknown,
  2837. startsWith: returnsBoolean,
  2838. strike: returnsString,
  2839. sub: returnsString,
  2840. substr: returnsString,
  2841. substring: returnsString,
  2842. sup: returnsString,
  2843. toLocaleLowerCase: returnsString,
  2844. toLocaleUpperCase: returnsString,
  2845. toLowerCase: returnsString,
  2846. toString: returnsString, // overrides the toString() method of the Object object; it does not inherit Object.prototype.toString()
  2847. toUpperCase: returnsString,
  2848. trim: returnsString,
  2849. trimEnd: returnsString,
  2850. trimLeft: returnsString,
  2851. trimRight: returnsString,
  2852. trimStart: returnsString,
  2853. valueOf: returnsString
  2854. }, objectMembers);
  2855. function getLiteralMembersForValue(value) {
  2856. if (value instanceof RegExp) {
  2857. return literalRegExpMembers;
  2858. }
  2859. switch (typeof value) {
  2860. case 'boolean': {
  2861. return literalBooleanMembers;
  2862. }
  2863. case 'number': {
  2864. return literalNumberMembers;
  2865. }
  2866. case 'string': {
  2867. return literalStringMembers;
  2868. }
  2869. }
  2870. return Object.create(null);
  2871. }
  2872. function hasMemberEffectWhenCalled(members, memberName, interaction, context) {
  2873. if (typeof memberName !== 'string' || !members[memberName]) {
  2874. return true;
  2875. }
  2876. return members[memberName].hasEffectsWhenCalled?.(interaction, context) || false;
  2877. }
  2878. function getMemberReturnExpressionWhenCalled(members, memberName) {
  2879. if (typeof memberName !== 'string' || !members[memberName])
  2880. return UNKNOWN_RETURN_EXPRESSION;
  2881. return [members[memberName].returns, false];
  2882. }
  2883. class Method extends ExpressionEntity {
  2884. constructor(description) {
  2885. super();
  2886. this.description = description;
  2887. }
  2888. deoptimizeArgumentsOnInteractionAtPath({ args, type }, path) {
  2889. if (type === INTERACTION_CALLED && path.length === 0) {
  2890. if (this.description.mutatesSelfAsArray) {
  2891. args[0]?.deoptimizePath(UNKNOWN_INTEGER_PATH);
  2892. }
  2893. if (this.description.mutatesArgs) {
  2894. for (let index = 1; index < args.length; index++) {
  2895. args[index].deoptimizePath(UNKNOWN_PATH);
  2896. }
  2897. }
  2898. }
  2899. }
  2900. getReturnExpressionWhenCalledAtPath(path, { args }) {
  2901. if (path.length > 0) {
  2902. return UNKNOWN_RETURN_EXPRESSION;
  2903. }
  2904. return [
  2905. this.description.returnsPrimitive ||
  2906. (this.description.returns === 'self'
  2907. ? args[0] || UNKNOWN_EXPRESSION
  2908. : this.description.returns()),
  2909. false
  2910. ];
  2911. }
  2912. hasEffectsOnInteractionAtPath(path, { args, type }, context) {
  2913. if (path.length > (type === INTERACTION_ACCESSED ? 1 : 0)) {
  2914. return true;
  2915. }
  2916. if (type === INTERACTION_CALLED) {
  2917. if (this.description.mutatesSelfAsArray === true &&
  2918. args[0]?.hasEffectsOnInteractionAtPath(UNKNOWN_INTEGER_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context)) {
  2919. return true;
  2920. }
  2921. if (this.description.callsArgs) {
  2922. for (const argumentIndex of this.description.callsArgs) {
  2923. if (args[argumentIndex + 1]?.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context)) {
  2924. return true;
  2925. }
  2926. }
  2927. }
  2928. }
  2929. return false;
  2930. }
  2931. }
  2932. const METHOD_RETURNS_BOOLEAN = [
  2933. new Method({
  2934. callsArgs: null,
  2935. mutatesArgs: false,
  2936. mutatesSelfAsArray: false,
  2937. returns: null,
  2938. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  2939. })
  2940. ];
  2941. const METHOD_RETURNS_STRING = [
  2942. new Method({
  2943. callsArgs: null,
  2944. mutatesArgs: false,
  2945. mutatesSelfAsArray: false,
  2946. returns: null,
  2947. returnsPrimitive: UNKNOWN_LITERAL_STRING
  2948. })
  2949. ];
  2950. const METHOD_RETURNS_NUMBER = [
  2951. new Method({
  2952. callsArgs: null,
  2953. mutatesArgs: false,
  2954. mutatesSelfAsArray: false,
  2955. returns: null,
  2956. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  2957. })
  2958. ];
  2959. const METHOD_RETURNS_UNKNOWN = [
  2960. new Method({
  2961. callsArgs: null,
  2962. mutatesArgs: false,
  2963. mutatesSelfAsArray: false,
  2964. returns: null,
  2965. returnsPrimitive: UNKNOWN_EXPRESSION
  2966. })
  2967. ];
  2968. const INTEGER_REG_EXP = /^\d+$/;
  2969. class ObjectEntity extends ExpressionEntity {
  2970. get hasLostTrack() {
  2971. return isFlagSet(this.flags, 2048 /* Flag.hasLostTrack */);
  2972. }
  2973. set hasLostTrack(value) {
  2974. this.flags = setFlag(this.flags, 2048 /* Flag.hasLostTrack */, value);
  2975. }
  2976. get hasUnknownDeoptimizedInteger() {
  2977. return isFlagSet(this.flags, 4096 /* Flag.hasUnknownDeoptimizedInteger */);
  2978. }
  2979. set hasUnknownDeoptimizedInteger(value) {
  2980. this.flags = setFlag(this.flags, 4096 /* Flag.hasUnknownDeoptimizedInteger */, value);
  2981. }
  2982. get hasUnknownDeoptimizedProperty() {
  2983. return isFlagSet(this.flags, 8192 /* Flag.hasUnknownDeoptimizedProperty */);
  2984. }
  2985. set hasUnknownDeoptimizedProperty(value) {
  2986. this.flags = setFlag(this.flags, 8192 /* Flag.hasUnknownDeoptimizedProperty */, value);
  2987. }
  2988. // If a PropertyMap is used, this will be taken as propertiesAndGettersByKey
  2989. // and we assume there are no setters or getters
  2990. constructor(properties, prototypeExpression, immutable = false) {
  2991. super();
  2992. this.prototypeExpression = prototypeExpression;
  2993. this.immutable = immutable;
  2994. this.additionalExpressionsToBeDeoptimized = new Set();
  2995. this.allProperties = [];
  2996. this.alwaysIncludedProperties = new Set();
  2997. this.deoptimizedPaths = new Map();
  2998. this.expressionsToBeDeoptimizedByKey = new Map();
  2999. this.gettersByKey = new Map();
  3000. this.propertiesAndGettersByKey = new Map();
  3001. this.propertiesAndSettersByKey = new Map();
  3002. this.settersByKey = new Map();
  3003. this.unknownIntegerProps = [];
  3004. this.unmatchableGetters = [];
  3005. this.unmatchablePropertiesAndGetters = [];
  3006. this.unmatchablePropertiesAndSetters = [];
  3007. this.unmatchableSetters = [];
  3008. if (Array.isArray(properties)) {
  3009. this.buildPropertyMaps(properties);
  3010. }
  3011. else {
  3012. this.propertiesAndGettersByKey = this.propertiesAndSettersByKey = properties;
  3013. for (const propertiesForKey of properties.values()) {
  3014. this.allProperties.push(...propertiesForKey);
  3015. }
  3016. }
  3017. }
  3018. deoptimizeAllProperties(noAccessors) {
  3019. const isDeoptimized = this.hasLostTrack || this.hasUnknownDeoptimizedProperty;
  3020. if (noAccessors) {
  3021. this.hasUnknownDeoptimizedProperty = true;
  3022. }
  3023. else {
  3024. this.hasLostTrack = true;
  3025. }
  3026. if (isDeoptimized) {
  3027. return;
  3028. }
  3029. for (const properties of [
  3030. ...this.propertiesAndGettersByKey.values(),
  3031. ...this.settersByKey.values()
  3032. ]) {
  3033. for (const property of properties) {
  3034. property.deoptimizePath(UNKNOWN_PATH);
  3035. }
  3036. }
  3037. // While the prototype itself cannot be mutated, each property can
  3038. this.prototypeExpression?.deoptimizePath([UnknownKey, UnknownKey]);
  3039. this.deoptimizeCachedEntities();
  3040. }
  3041. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  3042. const [key, ...subPath] = path;
  3043. const { args, type } = interaction;
  3044. if (this.hasLostTrack ||
  3045. // single paths that are deoptimized will not become getters or setters
  3046. ((type === INTERACTION_CALLED || path.length > 1) &&
  3047. (this.hasUnknownDeoptimizedProperty ||
  3048. (isConcreteKey(key) && this.deoptimizedPaths.get(key))))) {
  3049. deoptimizeInteraction(interaction);
  3050. return;
  3051. }
  3052. const [propertiesForExactMatchByKey, relevantPropertiesByKey, relevantUnmatchableProperties] = type === INTERACTION_CALLED || path.length > 1
  3053. ? [
  3054. this.propertiesAndGettersByKey,
  3055. this.propertiesAndGettersByKey,
  3056. this.unmatchablePropertiesAndGetters
  3057. ]
  3058. : type === INTERACTION_ACCESSED
  3059. ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters]
  3060. : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters];
  3061. if (isConcreteKey(key)) {
  3062. if (propertiesForExactMatchByKey.get(key)) {
  3063. const properties = relevantPropertiesByKey.get(key);
  3064. if (properties) {
  3065. for (const property of properties) {
  3066. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  3067. }
  3068. }
  3069. if (!this.immutable) {
  3070. for (const argument of args) {
  3071. if (argument) {
  3072. this.additionalExpressionsToBeDeoptimized.add(argument);
  3073. }
  3074. }
  3075. }
  3076. return;
  3077. }
  3078. for (const property of relevantUnmatchableProperties) {
  3079. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  3080. }
  3081. if (typeof key === 'string' && INTEGER_REG_EXP.test(key)) {
  3082. for (const property of this.unknownIntegerProps) {
  3083. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  3084. }
  3085. }
  3086. }
  3087. else {
  3088. for (const properties of [
  3089. ...relevantPropertiesByKey.values(),
  3090. relevantUnmatchableProperties
  3091. ]) {
  3092. for (const property of properties) {
  3093. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  3094. }
  3095. }
  3096. for (const property of this.unknownIntegerProps) {
  3097. property.deoptimizeArgumentsOnInteractionAtPath(interaction, subPath, recursionTracker);
  3098. }
  3099. }
  3100. if (!this.immutable) {
  3101. for (const argument of args) {
  3102. if (argument) {
  3103. this.additionalExpressionsToBeDeoptimized.add(argument);
  3104. }
  3105. }
  3106. }
  3107. this.prototypeExpression?.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  3108. }
  3109. deoptimizeIntegerProperties() {
  3110. if (this.hasLostTrack ||
  3111. this.hasUnknownDeoptimizedProperty ||
  3112. this.hasUnknownDeoptimizedInteger) {
  3113. return;
  3114. }
  3115. this.hasUnknownDeoptimizedInteger = true;
  3116. // Omits symbol keys but that's unimportant here
  3117. for (const [key, propertiesAndGetters] of this.propertiesAndGettersByKey.entries()) {
  3118. if (typeof key === 'string' && INTEGER_REG_EXP.test(key)) {
  3119. for (const property of propertiesAndGetters) {
  3120. property.deoptimizePath(UNKNOWN_PATH);
  3121. }
  3122. }
  3123. }
  3124. this.deoptimizeCachedIntegerEntities();
  3125. }
  3126. // Assumption: If only a specific path is deoptimized, no accessors are created
  3127. deoptimizePath(path) {
  3128. if (this.hasLostTrack || this.immutable) {
  3129. return;
  3130. }
  3131. const key = path[0];
  3132. if (path.length === 1) {
  3133. if (key === UnknownInteger) {
  3134. return this.deoptimizeIntegerProperties();
  3135. }
  3136. else if (!isConcreteKey(key)) {
  3137. return this.deoptimizeAllProperties(key === UnknownNonAccessorKey);
  3138. }
  3139. if (!this.deoptimizedPaths.get(key)) {
  3140. this.deoptimizedPaths.set(key, true);
  3141. // we only deoptimizeCache exact matches as in all other cases,
  3142. // we do not return a literal value or return expression
  3143. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimizedByKey.get(key);
  3144. if (expressionsToBeDeoptimized) {
  3145. for (const expression of expressionsToBeDeoptimized) {
  3146. expression.deoptimizeCache();
  3147. }
  3148. }
  3149. }
  3150. }
  3151. const subPath = path.length === 1 ? UNKNOWN_PATH : path.slice(1);
  3152. for (const property of isConcreteKey(key)
  3153. ? [
  3154. ...(this.propertiesAndGettersByKey.get(key) || this.unmatchablePropertiesAndGetters),
  3155. ...(this.settersByKey.get(key) || this.unmatchableSetters)
  3156. ]
  3157. : this.allProperties) {
  3158. property.deoptimizePath(subPath);
  3159. }
  3160. this.prototypeExpression?.deoptimizePath(path.length === 1 ? [path[0], UnknownKey] : path);
  3161. }
  3162. getLiteralValueAtPath(path, recursionTracker, origin) {
  3163. if (path.length === 0) {
  3164. // This should actually be "UnknownTruthyValue". However, this currently
  3165. // causes an issue with TypeScript enums in files with moduleSideEffects:
  3166. // false because we cannot properly track whether a "var" has been
  3167. // initialized. This should be reverted once we can properly track this.
  3168. // return UnknownTruthyValue;
  3169. return UnknownValue;
  3170. }
  3171. const key = path[0];
  3172. const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
  3173. if (expressionAtPath) {
  3174. return expressionAtPath.getLiteralValueAtPath(path.slice(1), recursionTracker, origin);
  3175. }
  3176. if (this.prototypeExpression) {
  3177. return this.prototypeExpression.getLiteralValueAtPath(path, recursionTracker, origin);
  3178. }
  3179. if (path.length === 1) {
  3180. return undefined;
  3181. }
  3182. return UnknownValue;
  3183. }
  3184. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  3185. if (path.length === 0) {
  3186. return UNKNOWN_RETURN_EXPRESSION;
  3187. }
  3188. const [key, ...subPath] = path;
  3189. const expressionAtPath = this.getMemberExpressionAndTrackDeopt(key, origin);
  3190. if (expressionAtPath) {
  3191. return expressionAtPath.getReturnExpressionWhenCalledAtPath(subPath, interaction, recursionTracker, origin);
  3192. }
  3193. if (this.prototypeExpression) {
  3194. return this.prototypeExpression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  3195. }
  3196. return UNKNOWN_RETURN_EXPRESSION;
  3197. }
  3198. hasEffectsOnInteractionAtPath(path, interaction, context) {
  3199. const [key, ...subPath] = path;
  3200. if (subPath.length > 0 || interaction.type === INTERACTION_CALLED) {
  3201. const expressionAtPath = this.getMemberExpression(key);
  3202. if (expressionAtPath) {
  3203. return expressionAtPath.hasEffectsOnInteractionAtPath(subPath, interaction, context);
  3204. }
  3205. if (this.prototypeExpression) {
  3206. return this.prototypeExpression.hasEffectsOnInteractionAtPath(path, interaction, context);
  3207. }
  3208. return true;
  3209. }
  3210. if (key === UnknownNonAccessorKey)
  3211. return false;
  3212. if (this.hasLostTrack)
  3213. return true;
  3214. const [propertiesAndAccessorsByKey, accessorsByKey, unmatchableAccessors] = interaction.type === INTERACTION_ACCESSED
  3215. ? [this.propertiesAndGettersByKey, this.gettersByKey, this.unmatchableGetters]
  3216. : [this.propertiesAndSettersByKey, this.settersByKey, this.unmatchableSetters];
  3217. if (isConcreteKey(key)) {
  3218. if (propertiesAndAccessorsByKey.get(key)) {
  3219. const accessors = accessorsByKey.get(key);
  3220. if (accessors) {
  3221. for (const accessor of accessors) {
  3222. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context))
  3223. return true;
  3224. }
  3225. }
  3226. return false;
  3227. }
  3228. for (const accessor of unmatchableAccessors) {
  3229. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context)) {
  3230. return true;
  3231. }
  3232. }
  3233. }
  3234. else {
  3235. for (const accessors of [...accessorsByKey.values(), unmatchableAccessors]) {
  3236. for (const accessor of accessors) {
  3237. if (accessor.hasEffectsOnInteractionAtPath(subPath, interaction, context))
  3238. return true;
  3239. }
  3240. }
  3241. }
  3242. if (this.prototypeExpression) {
  3243. return this.prototypeExpression.hasEffectsOnInteractionAtPath(path, interaction, context);
  3244. }
  3245. return false;
  3246. }
  3247. include(context, includeChildrenRecursively) {
  3248. this.included = true;
  3249. for (const property of this.allProperties) {
  3250. if (includeChildrenRecursively ||
  3251. property.shouldBeIncluded(context) ||
  3252. this.alwaysIncludedProperties.has(property)) {
  3253. property.include(context, includeChildrenRecursively);
  3254. }
  3255. }
  3256. this.prototypeExpression?.include(context, includeChildrenRecursively);
  3257. }
  3258. includePath(path, context) {
  3259. this.included = true;
  3260. for (const property of this.alwaysIncludedProperties) {
  3261. property.includePath(UNKNOWN_PATH, context);
  3262. }
  3263. if (path.length === 0)
  3264. return;
  3265. const [key, ...subPath] = path;
  3266. const [includedMembers, includedPath] = isConcreteKey(key)
  3267. ? [
  3268. new Set([
  3269. ...(this.propertiesAndGettersByKey.get(key) || this.unmatchablePropertiesAndGetters),
  3270. ...(this.propertiesAndSettersByKey.get(key) || this.unmatchablePropertiesAndSetters)
  3271. ]),
  3272. subPath
  3273. ]
  3274. : [this.allProperties, UNKNOWN_PATH];
  3275. for (const property of includedMembers) {
  3276. property.includePath(includedPath, context);
  3277. }
  3278. this.prototypeExpression?.includePath(path, context);
  3279. }
  3280. buildPropertyMaps(properties) {
  3281. const { allProperties, alwaysIncludedProperties, propertiesAndGettersByKey, propertiesAndSettersByKey, settersByKey, gettersByKey, unknownIntegerProps, unmatchablePropertiesAndGetters, unmatchablePropertiesAndSetters, unmatchableGetters, unmatchableSetters } = this;
  3282. for (let index = properties.length - 1; index >= 0; index--) {
  3283. const { key, kind, property } = properties[index];
  3284. allProperties.push(property);
  3285. if (isAnyWellKnown(key) && !TREE_SHAKEABLE_SYMBOLS.has(key)) {
  3286. // Never treeshake well-known symbols (unless Rollup can optimize them)
  3287. // They are most likely called implicitly by language semantics, don't get rid of them
  3288. alwaysIncludedProperties.add(property);
  3289. if (key === UnknownWellKnown)
  3290. continue;
  3291. }
  3292. if (isConcreteKey(key)) {
  3293. if (kind === 'set') {
  3294. if (!propertiesAndSettersByKey.has(key)) {
  3295. propertiesAndSettersByKey.set(key, [property, ...unmatchablePropertiesAndSetters]);
  3296. settersByKey.set(key, [property, ...unmatchableSetters]);
  3297. }
  3298. }
  3299. else if (kind === 'get') {
  3300. if (!propertiesAndGettersByKey.has(key)) {
  3301. propertiesAndGettersByKey.set(key, [property, ...unmatchablePropertiesAndGetters]);
  3302. gettersByKey.set(key, [property, ...unmatchableGetters]);
  3303. }
  3304. }
  3305. else {
  3306. if (!propertiesAndSettersByKey.has(key)) {
  3307. propertiesAndSettersByKey.set(key, [property, ...unmatchablePropertiesAndSetters]);
  3308. }
  3309. if (!propertiesAndGettersByKey.has(key)) {
  3310. propertiesAndGettersByKey.set(key, [property, ...unmatchablePropertiesAndGetters]);
  3311. }
  3312. }
  3313. }
  3314. else {
  3315. if (key === UnknownInteger) {
  3316. unknownIntegerProps.push(property);
  3317. continue;
  3318. }
  3319. if (kind === 'set')
  3320. unmatchableSetters.push(property);
  3321. if (kind === 'get')
  3322. unmatchableGetters.push(property);
  3323. if (kind !== 'get')
  3324. unmatchablePropertiesAndSetters.push(property);
  3325. if (kind !== 'set')
  3326. unmatchablePropertiesAndGetters.push(property);
  3327. }
  3328. }
  3329. }
  3330. deoptimizeCachedEntities() {
  3331. for (const expressionsToBeDeoptimized of this.expressionsToBeDeoptimizedByKey.values()) {
  3332. for (const expression of expressionsToBeDeoptimized) {
  3333. expression.deoptimizeCache();
  3334. }
  3335. }
  3336. for (const expression of this.additionalExpressionsToBeDeoptimized) {
  3337. expression.deoptimizePath(UNKNOWN_PATH);
  3338. }
  3339. }
  3340. deoptimizeCachedIntegerEntities() {
  3341. for (const [key, expressionsToBeDeoptimized] of this.expressionsToBeDeoptimizedByKey.entries()) {
  3342. if (typeof key === 'string' && INTEGER_REG_EXP.test(key)) {
  3343. for (const expression of expressionsToBeDeoptimized) {
  3344. expression.deoptimizeCache();
  3345. }
  3346. }
  3347. }
  3348. for (const expression of this.additionalExpressionsToBeDeoptimized) {
  3349. expression.deoptimizePath(UNKNOWN_INTEGER_PATH);
  3350. }
  3351. }
  3352. getMemberExpression(key) {
  3353. if (this.hasLostTrack ||
  3354. this.hasUnknownDeoptimizedProperty ||
  3355. !isConcreteKey(key) ||
  3356. (this.hasUnknownDeoptimizedInteger && typeof key === 'string' && INTEGER_REG_EXP.test(key)) ||
  3357. this.deoptimizedPaths.get(key)) {
  3358. return UNKNOWN_EXPRESSION;
  3359. }
  3360. const properties = this.propertiesAndGettersByKey.get(key);
  3361. if (properties?.length === 1) {
  3362. return properties[0];
  3363. }
  3364. if (properties ||
  3365. this.unmatchablePropertiesAndGetters.length > 0 ||
  3366. (this.unknownIntegerProps.length > 0 && typeof key === 'string' && INTEGER_REG_EXP.test(key))) {
  3367. return UNKNOWN_EXPRESSION;
  3368. }
  3369. return null;
  3370. }
  3371. getMemberExpressionAndTrackDeopt(key, origin) {
  3372. if (!isConcreteKey(key)) {
  3373. return UNKNOWN_EXPRESSION;
  3374. }
  3375. const expression = this.getMemberExpression(key);
  3376. if (!(expression === UNKNOWN_EXPRESSION || this.immutable)) {
  3377. let expressionsToBeDeoptimized = this.expressionsToBeDeoptimizedByKey.get(key);
  3378. if (!expressionsToBeDeoptimized) {
  3379. this.expressionsToBeDeoptimizedByKey.set(key, (expressionsToBeDeoptimized = []));
  3380. }
  3381. expressionsToBeDeoptimized.push(origin);
  3382. }
  3383. return expression;
  3384. }
  3385. }
  3386. const isInteger = (property) => typeof property === 'string' && /^\d+$/.test(property);
  3387. // This makes sure unknown properties are not handled as "undefined" but as
  3388. // "unknown" but without access side effects. An exception is done for numeric
  3389. // properties as we do not expect new builtin properties to be numbers, this
  3390. // will improve tree-shaking for out-of-bounds array properties
  3391. const OBJECT_PROTOTYPE_FALLBACK = new (class ObjectPrototypeFallbackExpression extends ExpressionEntity {
  3392. deoptimizeArgumentsOnInteractionAtPath(interaction, path) {
  3393. if (interaction.type === INTERACTION_CALLED && path.length === 1 && !isInteger(path[0])) {
  3394. deoptimizeInteraction(interaction);
  3395. }
  3396. }
  3397. getLiteralValueAtPath(path) {
  3398. // We ignore number properties as we do not expect new properties to be
  3399. // numbers and also want to keep handling out-of-bound array elements as
  3400. // "undefined"
  3401. return path.length === 1 && isInteger(path[0]) ? undefined : UnknownValue;
  3402. }
  3403. hasEffectsOnInteractionAtPath(path, { type }) {
  3404. return path.length > 1 || type === INTERACTION_CALLED;
  3405. }
  3406. })();
  3407. const OBJECT_PROTOTYPE = new ObjectEntity(new Map([
  3408. ['hasOwnProperty', METHOD_RETURNS_BOOLEAN],
  3409. ['isPrototypeOf', METHOD_RETURNS_BOOLEAN],
  3410. ['propertyIsEnumerable', METHOD_RETURNS_BOOLEAN],
  3411. ['toLocaleString', METHOD_RETURNS_STRING],
  3412. ['toString', METHOD_RETURNS_STRING],
  3413. ['valueOf', METHOD_RETURNS_UNKNOWN]
  3414. ]), OBJECT_PROTOTYPE_FALLBACK, true);
  3415. const NEW_ARRAY_PROPERTIES = [
  3416. { key: UnknownInteger, kind: 'init', property: UNKNOWN_EXPRESSION },
  3417. { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
  3418. ];
  3419. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN = [
  3420. new Method({
  3421. callsArgs: [0],
  3422. mutatesArgs: false,
  3423. mutatesSelfAsArray: 'deopt-only',
  3424. returns: null,
  3425. returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
  3426. })
  3427. ];
  3428. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER = [
  3429. new Method({
  3430. callsArgs: [0],
  3431. mutatesArgs: false,
  3432. mutatesSelfAsArray: 'deopt-only',
  3433. returns: null,
  3434. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  3435. })
  3436. ];
  3437. const METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY = [
  3438. new Method({
  3439. callsArgs: null,
  3440. mutatesArgs: false,
  3441. mutatesSelfAsArray: true,
  3442. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  3443. returnsPrimitive: null
  3444. })
  3445. ];
  3446. const METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
  3447. new Method({
  3448. callsArgs: null,
  3449. mutatesArgs: false,
  3450. mutatesSelfAsArray: 'deopt-only',
  3451. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  3452. returnsPrimitive: null
  3453. })
  3454. ];
  3455. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY = [
  3456. new Method({
  3457. callsArgs: [0],
  3458. mutatesArgs: false,
  3459. mutatesSelfAsArray: 'deopt-only',
  3460. returns: () => new ObjectEntity(NEW_ARRAY_PROPERTIES, ARRAY_PROTOTYPE),
  3461. returnsPrimitive: null
  3462. })
  3463. ];
  3464. const METHOD_MUTATES_SELF_AND_ARGS_RETURNS_NUMBER = [
  3465. new Method({
  3466. callsArgs: null,
  3467. mutatesArgs: true,
  3468. mutatesSelfAsArray: true,
  3469. returns: null,
  3470. returnsPrimitive: UNKNOWN_LITERAL_NUMBER
  3471. })
  3472. ];
  3473. const METHOD_MUTATES_SELF_RETURNS_UNKNOWN = [
  3474. new Method({
  3475. callsArgs: null,
  3476. mutatesArgs: false,
  3477. mutatesSelfAsArray: true,
  3478. returns: null,
  3479. returnsPrimitive: UNKNOWN_EXPRESSION
  3480. })
  3481. ];
  3482. const METHOD_DEOPTS_SELF_RETURNS_UNKNOWN = [
  3483. new Method({
  3484. callsArgs: null,
  3485. mutatesArgs: false,
  3486. mutatesSelfAsArray: 'deopt-only',
  3487. returns: null,
  3488. returnsPrimitive: UNKNOWN_EXPRESSION
  3489. })
  3490. ];
  3491. const METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN = [
  3492. new Method({
  3493. callsArgs: [0],
  3494. mutatesArgs: false,
  3495. mutatesSelfAsArray: 'deopt-only',
  3496. returns: null,
  3497. returnsPrimitive: UNKNOWN_EXPRESSION
  3498. })
  3499. ];
  3500. const METHOD_MUTATES_SELF_RETURNS_SELF = [
  3501. new Method({
  3502. callsArgs: null,
  3503. mutatesArgs: false,
  3504. mutatesSelfAsArray: true,
  3505. returns: 'self',
  3506. returnsPrimitive: null
  3507. })
  3508. ];
  3509. const METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF = [
  3510. new Method({
  3511. callsArgs: [0],
  3512. mutatesArgs: false,
  3513. mutatesSelfAsArray: true,
  3514. returns: 'self',
  3515. returnsPrimitive: null
  3516. })
  3517. ];
  3518. const ARRAY_PROTOTYPE = new ObjectEntity(new Map([
  3519. // We assume that accessors have effects as we do not track the accessed value afterwards
  3520. ['at', METHOD_DEOPTS_SELF_RETURNS_UNKNOWN],
  3521. ['concat', METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY],
  3522. ['copyWithin', METHOD_MUTATES_SELF_RETURNS_SELF],
  3523. ['entries', METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY],
  3524. ['every', METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN],
  3525. ['fill', METHOD_MUTATES_SELF_RETURNS_SELF],
  3526. ['filter', METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY],
  3527. ['find', METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN],
  3528. ['findIndex', METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER],
  3529. ['findLast', METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN],
  3530. ['findLastIndex', METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NUMBER],
  3531. ['flat', METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY],
  3532. ['flatMap', METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY],
  3533. ['forEach', METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN],
  3534. ['includes', METHOD_RETURNS_BOOLEAN],
  3535. ['indexOf', METHOD_RETURNS_NUMBER],
  3536. ['join', METHOD_RETURNS_STRING],
  3537. ['keys', METHOD_RETURNS_UNKNOWN],
  3538. ['lastIndexOf', METHOD_RETURNS_NUMBER],
  3539. ['map', METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_NEW_ARRAY],
  3540. ['pop', METHOD_MUTATES_SELF_RETURNS_UNKNOWN],
  3541. ['push', METHOD_MUTATES_SELF_AND_ARGS_RETURNS_NUMBER],
  3542. ['reduce', METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN],
  3543. ['reduceRight', METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_UNKNOWN],
  3544. ['reverse', METHOD_MUTATES_SELF_RETURNS_SELF],
  3545. ['shift', METHOD_MUTATES_SELF_RETURNS_UNKNOWN],
  3546. ['slice', METHOD_DEOPTS_SELF_RETURNS_NEW_ARRAY],
  3547. ['some', METHOD_CALLS_ARG_DEOPTS_SELF_RETURNS_BOOLEAN],
  3548. ['sort', METHOD_CALLS_ARG_MUTATES_SELF_RETURNS_SELF],
  3549. ['splice', METHOD_MUTATES_SELF_RETURNS_NEW_ARRAY],
  3550. ['toLocaleString', METHOD_RETURNS_STRING],
  3551. ['toString', METHOD_RETURNS_STRING],
  3552. ['unshift', METHOD_MUTATES_SELF_AND_ARGS_RETURNS_NUMBER],
  3553. ['values', METHOD_DEOPTS_SELF_RETURNS_UNKNOWN]
  3554. ]), OBJECT_PROTOTYPE, true);
  3555. class SpreadElement extends NodeBase {
  3556. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  3557. if (path.length > 0) {
  3558. this.argument.deoptimizeArgumentsOnInteractionAtPath(interaction, UNKNOWN_PATH, recursionTracker);
  3559. }
  3560. }
  3561. hasEffects(context) {
  3562. if (!this.deoptimized)
  3563. this.applyDeoptimizations();
  3564. const { propertyReadSideEffects } = this.scope.context.options
  3565. .treeshake;
  3566. return (this.argument.hasEffects(context) ||
  3567. (propertyReadSideEffects &&
  3568. (propertyReadSideEffects === 'always' ||
  3569. this.argument.hasEffectsOnInteractionAtPath(UNKNOWN_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context))));
  3570. }
  3571. includeNode(context) {
  3572. this.included = true;
  3573. if (!this.deoptimized)
  3574. this.applyDeoptimizations();
  3575. this.argument.includePath(UNKNOWN_PATH, context);
  3576. }
  3577. applyDeoptimizations() {
  3578. this.deoptimized = true;
  3579. // Only properties of properties of the argument could become subject to reassignment
  3580. // This will also reassign the return values of iterators
  3581. this.argument.deoptimizePath([UnknownKey, UnknownKey]);
  3582. this.scope.context.requestTreeshakingPass();
  3583. }
  3584. }
  3585. class ArrayExpression extends NodeBase {
  3586. constructor() {
  3587. super(...arguments);
  3588. this.objectEntity = null;
  3589. }
  3590. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  3591. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  3592. }
  3593. deoptimizePath(path) {
  3594. this.getObjectEntity().deoptimizePath(path);
  3595. }
  3596. getLiteralValueAtPath(path, recursionTracker, origin) {
  3597. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  3598. }
  3599. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  3600. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  3601. }
  3602. hasEffectsOnInteractionAtPath(path, interaction, context) {
  3603. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  3604. }
  3605. includeNode(context) {
  3606. this.included = true;
  3607. if (!this.deoptimized)
  3608. this.applyDeoptimizations();
  3609. for (const element of this.elements) {
  3610. if (element) {
  3611. element?.includePath(UNKNOWN_PATH, context);
  3612. }
  3613. }
  3614. }
  3615. applyDeoptimizations() {
  3616. this.deoptimized = true;
  3617. let hasSpread = false;
  3618. for (let index = 0; index < this.elements.length; index++) {
  3619. const element = this.elements[index];
  3620. if (element && (hasSpread || element instanceof SpreadElement)) {
  3621. hasSpread = true;
  3622. element.deoptimizePath(UNKNOWN_PATH);
  3623. }
  3624. }
  3625. this.scope.context.requestTreeshakingPass();
  3626. }
  3627. getObjectEntity() {
  3628. if (this.objectEntity !== null) {
  3629. return this.objectEntity;
  3630. }
  3631. const properties = [
  3632. { key: 'length', kind: 'init', property: UNKNOWN_LITERAL_NUMBER }
  3633. ];
  3634. let hasSpread = false;
  3635. for (let index = 0; index < this.elements.length; index++) {
  3636. const element = this.elements[index];
  3637. if (hasSpread || element instanceof SpreadElement) {
  3638. if (element) {
  3639. hasSpread = true;
  3640. properties.unshift({ key: UnknownInteger, kind: 'init', property: element });
  3641. }
  3642. }
  3643. else if (element) {
  3644. properties.push({ key: String(index), kind: 'init', property: element });
  3645. }
  3646. else {
  3647. properties.push({ key: String(index), kind: 'init', property: UNDEFINED_EXPRESSION });
  3648. }
  3649. }
  3650. return (this.objectEntity = new ObjectEntity(properties, ARRAY_PROTOTYPE));
  3651. }
  3652. }
  3653. /* eslint sort-keys: "off" */
  3654. const ValueProperties = Symbol('Value Properties');
  3655. const getUnknownValue = () => UnknownValue;
  3656. const returnFalse = () => false;
  3657. const returnTrue = () => true;
  3658. const getWellKnownSymbol = (symbol) => ({
  3659. __proto__: null,
  3660. [ValueProperties]: {
  3661. deoptimizeArgumentsOnCall: doNothing,
  3662. getLiteralValue: () => symbol,
  3663. hasEffectsWhenCalled: returnTrue
  3664. }
  3665. });
  3666. const PURE = {
  3667. deoptimizeArgumentsOnCall: doNothing,
  3668. getLiteralValue: getUnknownValue,
  3669. hasEffectsWhenCalled: returnFalse
  3670. };
  3671. const IMPURE = {
  3672. deoptimizeArgumentsOnCall: doNothing,
  3673. getLiteralValue: getUnknownValue,
  3674. hasEffectsWhenCalled: returnTrue
  3675. };
  3676. const PURE_WITH_ARRAY = {
  3677. deoptimizeArgumentsOnCall: doNothing,
  3678. getLiteralValue: getUnknownValue,
  3679. hasEffectsWhenCalled({ args }) {
  3680. return args.length > 1 && !(args[1] instanceof ArrayExpression);
  3681. }
  3682. };
  3683. const GETTER_ACCESS = {
  3684. deoptimizeArgumentsOnCall: doNothing,
  3685. getLiteralValue: getUnknownValue,
  3686. hasEffectsWhenCalled({ args }, context) {
  3687. const [_thisArgument, firstArgument] = args;
  3688. return (!(firstArgument instanceof ExpressionEntity) ||
  3689. firstArgument.hasEffectsOnInteractionAtPath(UNKNOWN_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context));
  3690. }
  3691. };
  3692. // We use shortened variables to reduce file size here
  3693. /* OBJECT */
  3694. const O = {
  3695. __proto__: null,
  3696. [ValueProperties]: IMPURE
  3697. };
  3698. /* PURE FUNCTION */
  3699. const PF = {
  3700. __proto__: null,
  3701. [ValueProperties]: PURE
  3702. };
  3703. /* PURE FUNCTION IF FIRST ARG DOES NOT CONTAIN A GETTER */
  3704. const PF_NO_GETTER = {
  3705. __proto__: null,
  3706. [ValueProperties]: GETTER_ACCESS
  3707. };
  3708. /* FUNCTION THAT MUTATES FIRST ARG WITHOUT TRIGGERING ACCESSORS */
  3709. const MUTATES_ARG_WITHOUT_ACCESSOR = {
  3710. __proto__: null,
  3711. [ValueProperties]: {
  3712. deoptimizeArgumentsOnCall({ args: [, firstArgument] }) {
  3713. firstArgument?.deoptimizePath(UNKNOWN_PATH);
  3714. },
  3715. getLiteralValue: getUnknownValue,
  3716. hasEffectsWhenCalled({ args }, context) {
  3717. return (args.length <= 1 ||
  3718. args[1].hasEffectsOnInteractionAtPath(UNKNOWN_NON_ACCESSOR_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context));
  3719. }
  3720. }
  3721. };
  3722. /* CONSTRUCTOR */
  3723. const C = {
  3724. __proto__: null,
  3725. [ValueProperties]: IMPURE,
  3726. prototype: O
  3727. };
  3728. /* PURE CONSTRUCTOR */
  3729. const PC = {
  3730. __proto__: null,
  3731. [ValueProperties]: PURE,
  3732. prototype: O
  3733. };
  3734. const PC_WITH_ARRAY = {
  3735. __proto__: null,
  3736. [ValueProperties]: PURE_WITH_ARRAY,
  3737. prototype: O
  3738. };
  3739. const ARRAY_TYPE = {
  3740. __proto__: null,
  3741. [ValueProperties]: PURE,
  3742. from: O,
  3743. of: PF,
  3744. prototype: O
  3745. };
  3746. const INTL_MEMBER = {
  3747. __proto__: null,
  3748. [ValueProperties]: PURE,
  3749. supportedLocalesOf: PC
  3750. };
  3751. const UNKNOWN_WELL_KNOWN = {
  3752. deoptimizeArgumentsOnCall: doNothing,
  3753. getLiteralValue: () => UnknownWellKnown,
  3754. hasEffectsWhenCalled: returnTrue
  3755. };
  3756. const knownGlobals = {
  3757. // Placeholders for global objects to avoid shape mutations
  3758. global: O,
  3759. globalThis: O,
  3760. self: O,
  3761. window: O,
  3762. // Common globals
  3763. __proto__: null,
  3764. [ValueProperties]: IMPURE,
  3765. Array: {
  3766. __proto__: null,
  3767. [ValueProperties]: IMPURE,
  3768. from: O,
  3769. isArray: PF,
  3770. of: PF,
  3771. prototype: O
  3772. },
  3773. ArrayBuffer: {
  3774. __proto__: null,
  3775. [ValueProperties]: PURE,
  3776. isView: PF,
  3777. prototype: O
  3778. },
  3779. AggregateError: PC_WITH_ARRAY,
  3780. Atomics: O,
  3781. BigInt: C,
  3782. BigInt64Array: C,
  3783. BigUint64Array: C,
  3784. Boolean: PC,
  3785. constructor: C,
  3786. DataView: PC,
  3787. Date: {
  3788. __proto__: null,
  3789. [ValueProperties]: PURE,
  3790. now: PF,
  3791. parse: PF,
  3792. prototype: O,
  3793. UTC: PF
  3794. },
  3795. decodeURI: PF,
  3796. decodeURIComponent: PF,
  3797. encodeURI: PF,
  3798. encodeURIComponent: PF,
  3799. Error: PC,
  3800. escape: PF,
  3801. eval: O,
  3802. EvalError: PC,
  3803. FinalizationRegistry: C,
  3804. Float32Array: ARRAY_TYPE,
  3805. Float64Array: ARRAY_TYPE,
  3806. Function: C,
  3807. hasOwnProperty: O,
  3808. Infinity: O,
  3809. Int16Array: ARRAY_TYPE,
  3810. Int32Array: ARRAY_TYPE,
  3811. Int8Array: ARRAY_TYPE,
  3812. isFinite: PF,
  3813. isNaN: PF,
  3814. isPrototypeOf: O,
  3815. JSON: O,
  3816. Map: PC_WITH_ARRAY,
  3817. Math: {
  3818. __proto__: null,
  3819. [ValueProperties]: IMPURE,
  3820. abs: PF,
  3821. acos: PF,
  3822. acosh: PF,
  3823. asin: PF,
  3824. asinh: PF,
  3825. atan: PF,
  3826. atan2: PF,
  3827. atanh: PF,
  3828. cbrt: PF,
  3829. ceil: PF,
  3830. clz32: PF,
  3831. cos: PF,
  3832. cosh: PF,
  3833. exp: PF,
  3834. expm1: PF,
  3835. floor: PF,
  3836. fround: PF,
  3837. hypot: PF,
  3838. imul: PF,
  3839. log: PF,
  3840. log10: PF,
  3841. log1p: PF,
  3842. log2: PF,
  3843. max: PF,
  3844. min: PF,
  3845. pow: PF,
  3846. random: PF,
  3847. round: PF,
  3848. sign: PF,
  3849. sin: PF,
  3850. sinh: PF,
  3851. sqrt: PF,
  3852. tan: PF,
  3853. tanh: PF,
  3854. trunc: PF
  3855. },
  3856. NaN: O,
  3857. Number: {
  3858. __proto__: null,
  3859. [ValueProperties]: PURE,
  3860. isFinite: PF,
  3861. isInteger: PF,
  3862. isNaN: PF,
  3863. isSafeInteger: PF,
  3864. parseFloat: PF,
  3865. parseInt: PF,
  3866. prototype: O
  3867. },
  3868. Object: {
  3869. __proto__: null,
  3870. [ValueProperties]: PURE,
  3871. create: PF,
  3872. // Technically those can throw in certain situations, but we ignore this as
  3873. // code that relies on this will hopefully wrap this in a try-catch, which
  3874. // deoptimizes everything anyway
  3875. defineProperty: MUTATES_ARG_WITHOUT_ACCESSOR,
  3876. defineProperties: MUTATES_ARG_WITHOUT_ACCESSOR,
  3877. freeze: MUTATES_ARG_WITHOUT_ACCESSOR,
  3878. getOwnPropertyDescriptor: PF,
  3879. getOwnPropertyDescriptors: PF,
  3880. getOwnPropertyNames: PF,
  3881. getOwnPropertySymbols: PF,
  3882. getPrototypeOf: PF,
  3883. hasOwn: PF,
  3884. is: PF,
  3885. isExtensible: PF,
  3886. isFrozen: PF,
  3887. isSealed: PF,
  3888. keys: PF,
  3889. fromEntries: O,
  3890. entries: PF_NO_GETTER,
  3891. values: PF_NO_GETTER,
  3892. prototype: O
  3893. },
  3894. parseFloat: PF,
  3895. parseInt: PF,
  3896. Promise: {
  3897. __proto__: null,
  3898. [ValueProperties]: IMPURE,
  3899. all: O,
  3900. allSettled: O,
  3901. any: O,
  3902. prototype: O,
  3903. race: O,
  3904. reject: O,
  3905. resolve: O
  3906. },
  3907. propertyIsEnumerable: O,
  3908. Proxy: {
  3909. __proto__: null,
  3910. [ValueProperties]: {
  3911. deoptimizeArgumentsOnCall: ({ args: [, target, parameter] }) => {
  3912. if (isObjectExpressionNode(parameter)) {
  3913. const hasSpreadElement = parameter.properties.some(property => !isPropertyNode(property));
  3914. if (!hasSpreadElement) {
  3915. for (const property of parameter.properties) {
  3916. property.deoptimizeArgumentsOnInteractionAtPath({
  3917. args: [null, target],
  3918. type: INTERACTION_CALLED,
  3919. withNew: false
  3920. }, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  3921. }
  3922. return;
  3923. }
  3924. }
  3925. target.deoptimizePath(UNKNOWN_PATH);
  3926. },
  3927. getLiteralValue: getUnknownValue,
  3928. hasEffectsWhenCalled: returnTrue
  3929. }
  3930. },
  3931. RangeError: PC,
  3932. ReferenceError: PC,
  3933. Reflect: O,
  3934. RegExp: PC,
  3935. Set: PC_WITH_ARRAY,
  3936. SharedArrayBuffer: C,
  3937. String: {
  3938. __proto__: null,
  3939. [ValueProperties]: PURE,
  3940. fromCharCode: PF,
  3941. fromCodePoint: PF,
  3942. prototype: O,
  3943. raw: PF
  3944. },
  3945. Symbol: {
  3946. __proto__: null,
  3947. [ValueProperties]: PURE,
  3948. for: PF,
  3949. keyFor: PF,
  3950. prototype: O,
  3951. asyncDispose: getWellKnownSymbol(SymbolAsyncDispose),
  3952. dispose: getWellKnownSymbol(SymbolDispose),
  3953. hasInstance: getWellKnownSymbol(SymbolHasInstance),
  3954. toStringTag: getWellKnownSymbol(SymbolToStringTag)
  3955. },
  3956. SyntaxError: PC,
  3957. toLocaleString: O,
  3958. toString: O,
  3959. TypeError: PC,
  3960. Uint16Array: ARRAY_TYPE,
  3961. Uint32Array: ARRAY_TYPE,
  3962. Uint8Array: ARRAY_TYPE,
  3963. Uint8ClampedArray: ARRAY_TYPE,
  3964. // Technically, this is a global, but it needs special handling
  3965. // undefined: ?,
  3966. unescape: PF,
  3967. URIError: PC,
  3968. valueOf: O,
  3969. WeakMap: PC_WITH_ARRAY,
  3970. WeakRef: C,
  3971. WeakSet: PC_WITH_ARRAY,
  3972. // Additional globals shared by Node and Browser that are not strictly part of the language
  3973. clearInterval: C,
  3974. clearTimeout: C,
  3975. console: {
  3976. __proto__: null,
  3977. [ValueProperties]: IMPURE,
  3978. assert: C,
  3979. clear: C,
  3980. count: C,
  3981. countReset: C,
  3982. debug: C,
  3983. dir: C,
  3984. dirxml: C,
  3985. error: C,
  3986. exception: C,
  3987. group: C,
  3988. groupCollapsed: C,
  3989. groupEnd: C,
  3990. info: C,
  3991. log: C,
  3992. table: C,
  3993. time: C,
  3994. timeEnd: C,
  3995. timeLog: C,
  3996. trace: C,
  3997. warn: C
  3998. },
  3999. Intl: {
  4000. __proto__: null,
  4001. [ValueProperties]: IMPURE,
  4002. Collator: INTL_MEMBER,
  4003. DateTimeFormat: INTL_MEMBER,
  4004. DisplayNames: INTL_MEMBER,
  4005. ListFormat: INTL_MEMBER,
  4006. Locale: INTL_MEMBER,
  4007. NumberFormat: INTL_MEMBER,
  4008. PluralRules: INTL_MEMBER,
  4009. RelativeTimeFormat: INTL_MEMBER,
  4010. Segmenter: INTL_MEMBER
  4011. },
  4012. setInterval: C,
  4013. setTimeout: C,
  4014. TextDecoder: C,
  4015. TextEncoder: C,
  4016. URL: {
  4017. __proto__: null,
  4018. [ValueProperties]: IMPURE,
  4019. prototype: O,
  4020. canParse: PF
  4021. },
  4022. URLSearchParams: C,
  4023. // Browser specific globals
  4024. AbortController: C,
  4025. AbortSignal: C,
  4026. addEventListener: O,
  4027. alert: O,
  4028. AnalyserNode: C,
  4029. Animation: C,
  4030. AnimationEvent: C,
  4031. applicationCache: O,
  4032. ApplicationCache: C,
  4033. ApplicationCacheErrorEvent: C,
  4034. atob: O,
  4035. Attr: C,
  4036. Audio: C,
  4037. AudioBuffer: C,
  4038. AudioBufferSourceNode: C,
  4039. AudioContext: C,
  4040. AudioDestinationNode: C,
  4041. AudioListener: C,
  4042. AudioNode: C,
  4043. AudioParam: C,
  4044. AudioProcessingEvent: C,
  4045. AudioScheduledSourceNode: C,
  4046. AudioWorkletNode: C,
  4047. BarProp: C,
  4048. BaseAudioContext: C,
  4049. BatteryManager: C,
  4050. BeforeUnloadEvent: C,
  4051. BiquadFilterNode: C,
  4052. Blob: C,
  4053. BlobEvent: C,
  4054. blur: O,
  4055. BroadcastChannel: C,
  4056. btoa: O,
  4057. ByteLengthQueuingStrategy: C,
  4058. Cache: C,
  4059. caches: O,
  4060. CacheStorage: C,
  4061. cancelAnimationFrame: O,
  4062. cancelIdleCallback: O,
  4063. CanvasCaptureMediaStreamTrack: C,
  4064. CanvasGradient: C,
  4065. CanvasPattern: C,
  4066. CanvasRenderingContext2D: C,
  4067. ChannelMergerNode: C,
  4068. ChannelSplitterNode: C,
  4069. CharacterData: C,
  4070. clientInformation: O,
  4071. ClipboardEvent: C,
  4072. close: O,
  4073. closed: O,
  4074. CloseEvent: C,
  4075. Comment: C,
  4076. CompositionEvent: C,
  4077. confirm: O,
  4078. ConstantSourceNode: C,
  4079. ConvolverNode: C,
  4080. CountQueuingStrategy: C,
  4081. createImageBitmap: O,
  4082. Credential: C,
  4083. CredentialsContainer: C,
  4084. crypto: O,
  4085. Crypto: C,
  4086. CryptoKey: C,
  4087. CSS: C,
  4088. CSSConditionRule: C,
  4089. CSSFontFaceRule: C,
  4090. CSSGroupingRule: C,
  4091. CSSImportRule: C,
  4092. CSSKeyframeRule: C,
  4093. CSSKeyframesRule: C,
  4094. CSSMediaRule: C,
  4095. CSSNamespaceRule: C,
  4096. CSSPageRule: C,
  4097. CSSRule: C,
  4098. CSSRuleList: C,
  4099. CSSStyleDeclaration: C,
  4100. CSSStyleRule: C,
  4101. CSSStyleSheet: C,
  4102. CSSSupportsRule: C,
  4103. CustomElementRegistry: C,
  4104. customElements: O,
  4105. CustomEvent: {
  4106. __proto__: null,
  4107. [ValueProperties]: {
  4108. deoptimizeArgumentsOnCall({ args }) {
  4109. args[2]?.deoptimizePath(['detail']);
  4110. },
  4111. getLiteralValue: getUnknownValue,
  4112. hasEffectsWhenCalled: returnFalse
  4113. },
  4114. prototype: O
  4115. },
  4116. DataTransfer: C,
  4117. DataTransferItem: C,
  4118. DataTransferItemList: C,
  4119. defaultstatus: O,
  4120. defaultStatus: O,
  4121. DelayNode: C,
  4122. DeviceMotionEvent: C,
  4123. DeviceOrientationEvent: C,
  4124. devicePixelRatio: O,
  4125. dispatchEvent: O,
  4126. document: O,
  4127. Document: C,
  4128. DocumentFragment: C,
  4129. DocumentType: C,
  4130. DOMError: C,
  4131. DOMException: C,
  4132. DOMImplementation: C,
  4133. DOMMatrix: C,
  4134. DOMMatrixReadOnly: C,
  4135. DOMParser: C,
  4136. DOMPoint: C,
  4137. DOMPointReadOnly: C,
  4138. DOMQuad: C,
  4139. DOMRect: C,
  4140. DOMRectReadOnly: C,
  4141. DOMStringList: C,
  4142. DOMStringMap: C,
  4143. DOMTokenList: C,
  4144. DragEvent: C,
  4145. DynamicsCompressorNode: C,
  4146. Element: C,
  4147. ErrorEvent: C,
  4148. Event: C,
  4149. EventSource: C,
  4150. EventTarget: C,
  4151. external: O,
  4152. fetch: O,
  4153. File: C,
  4154. FileList: C,
  4155. FileReader: C,
  4156. find: O,
  4157. focus: O,
  4158. FocusEvent: C,
  4159. FontFace: C,
  4160. FontFaceSetLoadEvent: C,
  4161. FormData: C,
  4162. frames: O,
  4163. GainNode: C,
  4164. Gamepad: C,
  4165. GamepadButton: C,
  4166. GamepadEvent: C,
  4167. getComputedStyle: O,
  4168. getSelection: O,
  4169. HashChangeEvent: C,
  4170. Headers: C,
  4171. history: O,
  4172. History: C,
  4173. HTMLAllCollection: C,
  4174. HTMLAnchorElement: C,
  4175. HTMLAreaElement: C,
  4176. HTMLAudioElement: C,
  4177. HTMLBaseElement: C,
  4178. HTMLBodyElement: C,
  4179. HTMLBRElement: C,
  4180. HTMLButtonElement: C,
  4181. HTMLCanvasElement: C,
  4182. HTMLCollection: C,
  4183. HTMLContentElement: C,
  4184. HTMLDataElement: C,
  4185. HTMLDataListElement: C,
  4186. HTMLDetailsElement: C,
  4187. HTMLDialogElement: C,
  4188. HTMLDirectoryElement: C,
  4189. HTMLDivElement: C,
  4190. HTMLDListElement: C,
  4191. HTMLDocument: C,
  4192. HTMLElement: C,
  4193. HTMLEmbedElement: C,
  4194. HTMLFieldSetElement: C,
  4195. HTMLFontElement: C,
  4196. HTMLFormControlsCollection: C,
  4197. HTMLFormElement: C,
  4198. HTMLFrameElement: C,
  4199. HTMLFrameSetElement: C,
  4200. HTMLHeadElement: C,
  4201. HTMLHeadingElement: C,
  4202. HTMLHRElement: C,
  4203. HTMLHtmlElement: C,
  4204. HTMLIFrameElement: C,
  4205. HTMLImageElement: C,
  4206. HTMLInputElement: C,
  4207. HTMLLabelElement: C,
  4208. HTMLLegendElement: C,
  4209. HTMLLIElement: C,
  4210. HTMLLinkElement: C,
  4211. HTMLMapElement: C,
  4212. HTMLMarqueeElement: C,
  4213. HTMLMediaElement: C,
  4214. HTMLMenuElement: C,
  4215. HTMLMetaElement: C,
  4216. HTMLMeterElement: C,
  4217. HTMLModElement: C,
  4218. HTMLObjectElement: C,
  4219. HTMLOListElement: C,
  4220. HTMLOptGroupElement: C,
  4221. HTMLOptionElement: C,
  4222. HTMLOptionsCollection: C,
  4223. HTMLOutputElement: C,
  4224. HTMLParagraphElement: C,
  4225. HTMLParamElement: C,
  4226. HTMLPictureElement: C,
  4227. HTMLPreElement: C,
  4228. HTMLProgressElement: C,
  4229. HTMLQuoteElement: C,
  4230. HTMLScriptElement: C,
  4231. HTMLSelectElement: C,
  4232. HTMLShadowElement: C,
  4233. HTMLSlotElement: C,
  4234. HTMLSourceElement: C,
  4235. HTMLSpanElement: C,
  4236. HTMLStyleElement: C,
  4237. HTMLTableCaptionElement: C,
  4238. HTMLTableCellElement: C,
  4239. HTMLTableColElement: C,
  4240. HTMLTableElement: C,
  4241. HTMLTableRowElement: C,
  4242. HTMLTableSectionElement: C,
  4243. HTMLTemplateElement: C,
  4244. HTMLTextAreaElement: C,
  4245. HTMLTimeElement: C,
  4246. HTMLTitleElement: C,
  4247. HTMLTrackElement: C,
  4248. HTMLUListElement: C,
  4249. HTMLUnknownElement: C,
  4250. HTMLVideoElement: C,
  4251. IDBCursor: C,
  4252. IDBCursorWithValue: C,
  4253. IDBDatabase: C,
  4254. IDBFactory: C,
  4255. IDBIndex: C,
  4256. IDBKeyRange: C,
  4257. IDBObjectStore: C,
  4258. IDBOpenDBRequest: C,
  4259. IDBRequest: C,
  4260. IDBTransaction: C,
  4261. IDBVersionChangeEvent: C,
  4262. IdleDeadline: C,
  4263. IIRFilterNode: C,
  4264. Image: C,
  4265. ImageBitmap: C,
  4266. ImageBitmapRenderingContext: C,
  4267. ImageCapture: C,
  4268. ImageData: C,
  4269. indexedDB: O,
  4270. innerHeight: O,
  4271. innerWidth: O,
  4272. InputEvent: C,
  4273. IntersectionObserver: C,
  4274. IntersectionObserverEntry: C,
  4275. isSecureContext: O,
  4276. KeyboardEvent: C,
  4277. KeyframeEffect: C,
  4278. length: O,
  4279. localStorage: O,
  4280. location: O,
  4281. Location: C,
  4282. locationbar: O,
  4283. matchMedia: O,
  4284. MediaDeviceInfo: C,
  4285. MediaDevices: C,
  4286. MediaElementAudioSourceNode: C,
  4287. MediaEncryptedEvent: C,
  4288. MediaError: C,
  4289. MediaKeyMessageEvent: C,
  4290. MediaKeySession: C,
  4291. MediaKeyStatusMap: C,
  4292. MediaKeySystemAccess: C,
  4293. MediaList: C,
  4294. MediaQueryList: C,
  4295. MediaQueryListEvent: C,
  4296. MediaRecorder: C,
  4297. MediaSettingsRange: C,
  4298. MediaSource: C,
  4299. MediaStream: C,
  4300. MediaStreamAudioDestinationNode: C,
  4301. MediaStreamAudioSourceNode: C,
  4302. MediaStreamEvent: C,
  4303. MediaStreamTrack: C,
  4304. MediaStreamTrackEvent: C,
  4305. menubar: O,
  4306. MessageChannel: C,
  4307. MessageEvent: C,
  4308. MessagePort: C,
  4309. MIDIAccess: C,
  4310. MIDIConnectionEvent: C,
  4311. MIDIInput: C,
  4312. MIDIInputMap: C,
  4313. MIDIMessageEvent: C,
  4314. MIDIOutput: C,
  4315. MIDIOutputMap: C,
  4316. MIDIPort: C,
  4317. MimeType: C,
  4318. MimeTypeArray: C,
  4319. MouseEvent: C,
  4320. moveBy: O,
  4321. moveTo: O,
  4322. MutationEvent: C,
  4323. MutationObserver: C,
  4324. MutationRecord: C,
  4325. name: O,
  4326. NamedNodeMap: C,
  4327. NavigationPreloadManager: C,
  4328. navigator: O,
  4329. Navigator: C,
  4330. NetworkInformation: C,
  4331. Node: C,
  4332. NodeFilter: O,
  4333. NodeIterator: C,
  4334. NodeList: C,
  4335. Notification: C,
  4336. OfflineAudioCompletionEvent: C,
  4337. OfflineAudioContext: C,
  4338. offscreenBuffering: O,
  4339. OffscreenCanvas: C,
  4340. open: O,
  4341. openDatabase: O,
  4342. Option: C,
  4343. origin: O,
  4344. OscillatorNode: C,
  4345. outerHeight: O,
  4346. outerWidth: O,
  4347. PageTransitionEvent: C,
  4348. pageXOffset: O,
  4349. pageYOffset: O,
  4350. PannerNode: C,
  4351. parent: O,
  4352. Path2D: C,
  4353. PaymentAddress: C,
  4354. PaymentRequest: C,
  4355. PaymentRequestUpdateEvent: C,
  4356. PaymentResponse: C,
  4357. performance: O,
  4358. Performance: C,
  4359. PerformanceEntry: C,
  4360. PerformanceLongTaskTiming: C,
  4361. PerformanceMark: C,
  4362. PerformanceMeasure: C,
  4363. PerformanceNavigation: C,
  4364. PerformanceNavigationTiming: C,
  4365. PerformanceObserver: C,
  4366. PerformanceObserverEntryList: C,
  4367. PerformancePaintTiming: C,
  4368. PerformanceResourceTiming: C,
  4369. PerformanceTiming: C,
  4370. PeriodicWave: C,
  4371. Permissions: C,
  4372. PermissionStatus: C,
  4373. personalbar: O,
  4374. PhotoCapabilities: C,
  4375. Plugin: C,
  4376. PluginArray: C,
  4377. PointerEvent: C,
  4378. PopStateEvent: C,
  4379. postMessage: O,
  4380. Presentation: C,
  4381. PresentationAvailability: C,
  4382. PresentationConnection: C,
  4383. PresentationConnectionAvailableEvent: C,
  4384. PresentationConnectionCloseEvent: C,
  4385. PresentationConnectionList: C,
  4386. PresentationReceiver: C,
  4387. PresentationRequest: C,
  4388. print: O,
  4389. ProcessingInstruction: C,
  4390. ProgressEvent: C,
  4391. PromiseRejectionEvent: C,
  4392. prompt: O,
  4393. PushManager: C,
  4394. PushSubscription: C,
  4395. PushSubscriptionOptions: C,
  4396. queueMicrotask: O,
  4397. RadioNodeList: C,
  4398. Range: C,
  4399. ReadableStream: C,
  4400. RemotePlayback: C,
  4401. removeEventListener: O,
  4402. Request: C,
  4403. requestAnimationFrame: O,
  4404. requestIdleCallback: O,
  4405. resizeBy: O,
  4406. ResizeObserver: C,
  4407. ResizeObserverEntry: C,
  4408. resizeTo: O,
  4409. Response: C,
  4410. RTCCertificate: C,
  4411. RTCDataChannel: C,
  4412. RTCDataChannelEvent: C,
  4413. RTCDtlsTransport: C,
  4414. RTCIceCandidate: C,
  4415. RTCIceTransport: C,
  4416. RTCPeerConnection: C,
  4417. RTCPeerConnectionIceEvent: C,
  4418. RTCRtpReceiver: C,
  4419. RTCRtpSender: C,
  4420. RTCSctpTransport: C,
  4421. RTCSessionDescription: C,
  4422. RTCStatsReport: C,
  4423. RTCTrackEvent: C,
  4424. screen: O,
  4425. Screen: C,
  4426. screenLeft: O,
  4427. ScreenOrientation: C,
  4428. screenTop: O,
  4429. screenX: O,
  4430. screenY: O,
  4431. ScriptProcessorNode: C,
  4432. scroll: O,
  4433. scrollbars: O,
  4434. scrollBy: O,
  4435. scrollTo: O,
  4436. scrollX: O,
  4437. scrollY: O,
  4438. SecurityPolicyViolationEvent: C,
  4439. Selection: C,
  4440. ServiceWorker: C,
  4441. ServiceWorkerContainer: C,
  4442. ServiceWorkerRegistration: C,
  4443. sessionStorage: O,
  4444. ShadowRoot: C,
  4445. SharedWorker: C,
  4446. SourceBuffer: C,
  4447. SourceBufferList: C,
  4448. speechSynthesis: O,
  4449. SpeechSynthesisEvent: C,
  4450. SpeechSynthesisUtterance: C,
  4451. StaticRange: C,
  4452. status: O,
  4453. statusbar: O,
  4454. StereoPannerNode: C,
  4455. stop: O,
  4456. Storage: C,
  4457. StorageEvent: C,
  4458. StorageManager: C,
  4459. styleMedia: O,
  4460. StyleSheet: C,
  4461. StyleSheetList: C,
  4462. SubtleCrypto: C,
  4463. SVGAElement: C,
  4464. SVGAngle: C,
  4465. SVGAnimatedAngle: C,
  4466. SVGAnimatedBoolean: C,
  4467. SVGAnimatedEnumeration: C,
  4468. SVGAnimatedInteger: C,
  4469. SVGAnimatedLength: C,
  4470. SVGAnimatedLengthList: C,
  4471. SVGAnimatedNumber: C,
  4472. SVGAnimatedNumberList: C,
  4473. SVGAnimatedPreserveAspectRatio: C,
  4474. SVGAnimatedRect: C,
  4475. SVGAnimatedString: C,
  4476. SVGAnimatedTransformList: C,
  4477. SVGAnimateElement: C,
  4478. SVGAnimateMotionElement: C,
  4479. SVGAnimateTransformElement: C,
  4480. SVGAnimationElement: C,
  4481. SVGCircleElement: C,
  4482. SVGClipPathElement: C,
  4483. SVGComponentTransferFunctionElement: C,
  4484. SVGDefsElement: C,
  4485. SVGDescElement: C,
  4486. SVGDiscardElement: C,
  4487. SVGElement: C,
  4488. SVGEllipseElement: C,
  4489. SVGFEBlendElement: C,
  4490. SVGFEColorMatrixElement: C,
  4491. SVGFEComponentTransferElement: C,
  4492. SVGFECompositeElement: C,
  4493. SVGFEConvolveMatrixElement: C,
  4494. SVGFEDiffuseLightingElement: C,
  4495. SVGFEDisplacementMapElement: C,
  4496. SVGFEDistantLightElement: C,
  4497. SVGFEDropShadowElement: C,
  4498. SVGFEFloodElement: C,
  4499. SVGFEFuncAElement: C,
  4500. SVGFEFuncBElement: C,
  4501. SVGFEFuncGElement: C,
  4502. SVGFEFuncRElement: C,
  4503. SVGFEGaussianBlurElement: C,
  4504. SVGFEImageElement: C,
  4505. SVGFEMergeElement: C,
  4506. SVGFEMergeNodeElement: C,
  4507. SVGFEMorphologyElement: C,
  4508. SVGFEOffsetElement: C,
  4509. SVGFEPointLightElement: C,
  4510. SVGFESpecularLightingElement: C,
  4511. SVGFESpotLightElement: C,
  4512. SVGFETileElement: C,
  4513. SVGFETurbulenceElement: C,
  4514. SVGFilterElement: C,
  4515. SVGForeignObjectElement: C,
  4516. SVGGElement: C,
  4517. SVGGeometryElement: C,
  4518. SVGGradientElement: C,
  4519. SVGGraphicsElement: C,
  4520. SVGImageElement: C,
  4521. SVGLength: C,
  4522. SVGLengthList: C,
  4523. SVGLinearGradientElement: C,
  4524. SVGLineElement: C,
  4525. SVGMarkerElement: C,
  4526. SVGMaskElement: C,
  4527. SVGMatrix: C,
  4528. SVGMetadataElement: C,
  4529. SVGMPathElement: C,
  4530. SVGNumber: C,
  4531. SVGNumberList: C,
  4532. SVGPathElement: C,
  4533. SVGPatternElement: C,
  4534. SVGPoint: C,
  4535. SVGPointList: C,
  4536. SVGPolygonElement: C,
  4537. SVGPolylineElement: C,
  4538. SVGPreserveAspectRatio: C,
  4539. SVGRadialGradientElement: C,
  4540. SVGRect: C,
  4541. SVGRectElement: C,
  4542. SVGScriptElement: C,
  4543. SVGSetElement: C,
  4544. SVGStopElement: C,
  4545. SVGStringList: C,
  4546. SVGStyleElement: C,
  4547. SVGSVGElement: C,
  4548. SVGSwitchElement: C,
  4549. SVGSymbolElement: C,
  4550. SVGTextContentElement: C,
  4551. SVGTextElement: C,
  4552. SVGTextPathElement: C,
  4553. SVGTextPositioningElement: C,
  4554. SVGTitleElement: C,
  4555. SVGTransform: C,
  4556. SVGTransformList: C,
  4557. SVGTSpanElement: C,
  4558. SVGUnitTypes: C,
  4559. SVGUseElement: C,
  4560. SVGViewElement: C,
  4561. TaskAttributionTiming: C,
  4562. Text: C,
  4563. TextEvent: C,
  4564. TextMetrics: C,
  4565. TextTrack: C,
  4566. TextTrackCue: C,
  4567. TextTrackCueList: C,
  4568. TextTrackList: C,
  4569. TimeRanges: C,
  4570. toolbar: O,
  4571. top: O,
  4572. Touch: C,
  4573. TouchEvent: C,
  4574. TouchList: C,
  4575. TrackEvent: C,
  4576. TransitionEvent: C,
  4577. TreeWalker: C,
  4578. UIEvent: C,
  4579. ValidityState: C,
  4580. visualViewport: O,
  4581. VisualViewport: C,
  4582. VTTCue: C,
  4583. WaveShaperNode: C,
  4584. WebAssembly: O,
  4585. WebGL2RenderingContext: C,
  4586. WebGLActiveInfo: C,
  4587. WebGLBuffer: C,
  4588. WebGLContextEvent: C,
  4589. WebGLFramebuffer: C,
  4590. WebGLProgram: C,
  4591. WebGLQuery: C,
  4592. WebGLRenderbuffer: C,
  4593. WebGLRenderingContext: C,
  4594. WebGLSampler: C,
  4595. WebGLShader: C,
  4596. WebGLShaderPrecisionFormat: C,
  4597. WebGLSync: C,
  4598. WebGLTexture: C,
  4599. WebGLTransformFeedback: C,
  4600. WebGLUniformLocation: C,
  4601. WebGLVertexArrayObject: C,
  4602. WebSocket: C,
  4603. WheelEvent: C,
  4604. Window: C,
  4605. Worker: C,
  4606. WritableStream: C,
  4607. XMLDocument: C,
  4608. XMLHttpRequest: C,
  4609. XMLHttpRequestEventTarget: C,
  4610. XMLHttpRequestUpload: C,
  4611. XMLSerializer: C,
  4612. XPathEvaluator: C,
  4613. XPathExpression: C,
  4614. XPathResult: C,
  4615. XSLTProcessor: C
  4616. };
  4617. for (const global of ['window', 'global', 'self', 'globalThis']) {
  4618. knownGlobals[global] = knownGlobals;
  4619. }
  4620. function getGlobalAtPath(path) {
  4621. let currentGlobal = knownGlobals;
  4622. for (const pathSegment of path) {
  4623. if (typeof pathSegment !== 'string') {
  4624. return null;
  4625. }
  4626. currentGlobal = currentGlobal[pathSegment];
  4627. if (!currentGlobal) {
  4628. // Well-known symbols very often have a complex meaning and are invoked implicitly by the language.
  4629. // Resolve them to a special value so they can be distinguished and excluded from treeshaking.
  4630. return path[0] === 'Symbol' && path.length === 2 ? UNKNOWN_WELL_KNOWN : null;
  4631. }
  4632. }
  4633. return currentGlobal[ValueProperties];
  4634. }
  4635. class GlobalVariable extends Variable {
  4636. constructor(name) {
  4637. super(name);
  4638. // Ensure we use live-bindings for globals as we do not know if they have
  4639. // been reassigned
  4640. this.markReassigned();
  4641. }
  4642. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  4643. switch (interaction.type) {
  4644. // While there is no point in testing these cases as at the moment, they
  4645. // are also covered via other means, we keep them for completeness
  4646. case INTERACTION_ACCESSED:
  4647. case INTERACTION_ASSIGNED: {
  4648. if (!getGlobalAtPath([this.name, ...path].slice(0, -1))) {
  4649. super.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  4650. }
  4651. return;
  4652. }
  4653. case INTERACTION_CALLED: {
  4654. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  4655. if (globalAtPath) {
  4656. globalAtPath.deoptimizeArgumentsOnCall(interaction);
  4657. }
  4658. else {
  4659. super.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  4660. }
  4661. return;
  4662. }
  4663. }
  4664. }
  4665. getLiteralValueAtPath(path, _recursionTracker, _origin) {
  4666. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  4667. return globalAtPath ? globalAtPath.getLiteralValue() : UnknownValue;
  4668. }
  4669. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4670. switch (interaction.type) {
  4671. case INTERACTION_ACCESSED: {
  4672. if (path.length === 0) {
  4673. // Technically, "undefined" is a global variable of sorts
  4674. return this.name !== 'undefined' && !getGlobalAtPath([this.name]);
  4675. }
  4676. return !getGlobalAtPath([this.name, ...path].slice(0, -1));
  4677. }
  4678. case INTERACTION_ASSIGNED: {
  4679. return true;
  4680. }
  4681. case INTERACTION_CALLED: {
  4682. const globalAtPath = getGlobalAtPath([this.name, ...path]);
  4683. return !globalAtPath || globalAtPath.hasEffectsWhenCalled(interaction, context);
  4684. }
  4685. }
  4686. }
  4687. }
  4688. // To avoid infinite recursions
  4689. const MAX_PATH_DEPTH = 6;
  4690. // If a path is longer than MAX_PATH_DEPTH, it is truncated so that it is at
  4691. // most MAX_PATH_DEPTH long. The last element is always UnknownKey
  4692. const limitConcatenatedPathDepth = (path1, path2) => {
  4693. const { length: length1 } = path1;
  4694. const { length: length2 } = path2;
  4695. return length1 === 0
  4696. ? path2
  4697. : length2 === 0
  4698. ? path1
  4699. : length1 + length2 > MAX_PATH_DEPTH
  4700. ? [...path1, ...path2.slice(0, MAX_PATH_DEPTH - 1 - path1.length), 'UnknownKey']
  4701. : [...path1, ...path2];
  4702. };
  4703. class LocalVariable extends Variable {
  4704. constructor(name, declarator, init,
  4705. /** if this is non-empty, the actual init is this path of this.init */
  4706. initPath, context, kind) {
  4707. super(name);
  4708. this.init = init;
  4709. this.initPath = initPath;
  4710. this.kind = kind;
  4711. this.calledFromTryStatement = false;
  4712. this.additionalInitializers = null;
  4713. this.includedPathTracker = new IncludedFullPathTracker();
  4714. this.expressionsToBeDeoptimized = [];
  4715. this.declarations = declarator ? [declarator] : [];
  4716. this.deoptimizationTracker = context.deoptimizationTracker;
  4717. this.module = context.module;
  4718. }
  4719. addDeclaration(identifier, init) {
  4720. this.declarations.push(identifier);
  4721. this.markInitializersForDeoptimization().push(init);
  4722. }
  4723. consolidateInitializers() {
  4724. if (this.additionalInitializers) {
  4725. for (const initializer of this.additionalInitializers) {
  4726. initializer.deoptimizePath(UNKNOWN_PATH);
  4727. }
  4728. }
  4729. }
  4730. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  4731. if (this.isReassigned || path.length + this.initPath.length > MAX_PATH_DEPTH) {
  4732. deoptimizeInteraction(interaction);
  4733. return;
  4734. }
  4735. recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  4736. this.init.deoptimizeArgumentsOnInteractionAtPath(interaction, [...this.initPath, ...path], recursionTracker);
  4737. }, undefined);
  4738. }
  4739. deoptimizePath(path) {
  4740. if (this.isReassigned ||
  4741. this.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  4742. return;
  4743. }
  4744. if (path.length === 0) {
  4745. this.markReassigned();
  4746. const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
  4747. this.expressionsToBeDeoptimized = EMPTY_ARRAY;
  4748. for (const expression of expressionsToBeDeoptimized) {
  4749. expression.deoptimizeCache();
  4750. }
  4751. this.init.deoptimizePath([...this.initPath, UnknownKey]);
  4752. }
  4753. else {
  4754. this.init.deoptimizePath(limitConcatenatedPathDepth(this.initPath, path));
  4755. }
  4756. }
  4757. getLiteralValueAtPath(path, recursionTracker, origin) {
  4758. if (this.isReassigned || path.length + this.initPath.length > MAX_PATH_DEPTH) {
  4759. return UnknownValue;
  4760. }
  4761. return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  4762. this.expressionsToBeDeoptimized.push(origin);
  4763. return this.init.getLiteralValueAtPath([...this.initPath, ...path], recursionTracker, origin);
  4764. }, UnknownValue);
  4765. }
  4766. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  4767. if (this.isReassigned || path.length + this.initPath.length > MAX_PATH_DEPTH) {
  4768. return UNKNOWN_RETURN_EXPRESSION;
  4769. }
  4770. return recursionTracker.withTrackedEntityAtPath(path, this.init, () => {
  4771. this.expressionsToBeDeoptimized.push(origin);
  4772. return this.init.getReturnExpressionWhenCalledAtPath([...this.initPath, ...path], interaction, recursionTracker, origin);
  4773. }, UNKNOWN_RETURN_EXPRESSION);
  4774. }
  4775. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4776. if (path.length + this.initPath.length > MAX_PATH_DEPTH) {
  4777. return true;
  4778. }
  4779. switch (interaction.type) {
  4780. case INTERACTION_ACCESSED: {
  4781. if (this.isReassigned)
  4782. return true;
  4783. return (!context.accessed.trackEntityAtPathAndGetIfTracked(path, this) &&
  4784. this.init.hasEffectsOnInteractionAtPath([...this.initPath, ...path], interaction, context));
  4785. }
  4786. case INTERACTION_ASSIGNED: {
  4787. if (this.included)
  4788. return true;
  4789. if (path.length === 0)
  4790. return false;
  4791. // if (this.isReassigned || this.init.included) return true;
  4792. if (this.isReassigned)
  4793. return true;
  4794. return (!context.assigned.trackEntityAtPathAndGetIfTracked(path, this) &&
  4795. this.init.hasEffectsOnInteractionAtPath([...this.initPath, ...path], interaction, context));
  4796. }
  4797. case INTERACTION_CALLED: {
  4798. if (this.isReassigned)
  4799. return true;
  4800. return (!(interaction.withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, interaction.args, this) &&
  4801. this.init.hasEffectsOnInteractionAtPath([...this.initPath, ...path], interaction, context));
  4802. }
  4803. }
  4804. }
  4805. includePath(path, context) {
  4806. if (!this.includedPathTracker.includePathAndGetIfIncluded(path)) {
  4807. this.module.scope.context.requestTreeshakingPass();
  4808. if (!this.included) {
  4809. // This will reduce the number of tree-shaking passes by eagerly
  4810. // including inits. By pushing this here instead of directly including
  4811. // we avoid deep call stacks.
  4812. this.module.scope.context.newlyIncludedVariableInits.add(this.init);
  4813. }
  4814. super.includePath(path, context);
  4815. for (const declaration of this.declarations) {
  4816. // If node is a default export, it can save a tree-shaking run to include the full declaration now
  4817. if (!declaration.included)
  4818. declaration.include(context, false);
  4819. let node = declaration.parent;
  4820. while (!node.included) {
  4821. // We do not want to properly include parents in case they are part of a dead branch
  4822. // in which case .include() might pull in more dead code
  4823. node.includeNode(context);
  4824. if (node.type === Program$1)
  4825. break;
  4826. node = node.parent;
  4827. }
  4828. }
  4829. // We need to make sure we include the correct path of the init
  4830. if (path.length > 0) {
  4831. this.init.includePath(limitConcatenatedPathDepth(this.initPath, path), context);
  4832. this.additionalInitializers?.forEach(initializer => initializer.includePath(UNKNOWN_PATH, context));
  4833. }
  4834. }
  4835. }
  4836. includeCallArguments(interaction, context) {
  4837. if (this.isReassigned ||
  4838. context.includedCallArguments.has(this.init) ||
  4839. // This can be removed again once we can include arguments when called at
  4840. // a specific path
  4841. this.initPath.length > 0) {
  4842. includeInteraction(interaction, context);
  4843. }
  4844. else {
  4845. context.includedCallArguments.add(this.init);
  4846. this.init.includeCallArguments(interaction, context);
  4847. context.includedCallArguments.delete(this.init);
  4848. }
  4849. }
  4850. markCalledFromTryStatement() {
  4851. this.calledFromTryStatement = true;
  4852. }
  4853. markInitializersForDeoptimization() {
  4854. if (this.additionalInitializers === null) {
  4855. this.additionalInitializers = [this.init];
  4856. this.init = UNKNOWN_EXPRESSION;
  4857. this.markReassigned();
  4858. }
  4859. return this.additionalInitializers;
  4860. }
  4861. }
  4862. const tdzVariableKinds = new Set(['class', 'const', 'let', 'var', 'using', 'await using']);
  4863. class IdentifierBase extends NodeBase {
  4864. constructor() {
  4865. super(...arguments);
  4866. this.variable = null;
  4867. this.isVariableReference = false;
  4868. }
  4869. get isTDZAccess() {
  4870. if (!isFlagSet(this.flags, 4 /* Flag.tdzAccessDefined */)) {
  4871. return null;
  4872. }
  4873. return isFlagSet(this.flags, 8 /* Flag.tdzAccess */);
  4874. }
  4875. set isTDZAccess(value) {
  4876. this.flags = setFlag(this.flags, 4 /* Flag.tdzAccessDefined */, true);
  4877. this.flags = setFlag(this.flags, 8 /* Flag.tdzAccess */, value);
  4878. }
  4879. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  4880. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  4881. }
  4882. deoptimizePath(path) {
  4883. if (path.length === 0 && !this.scope.contains(this.name)) {
  4884. this.disallowImportReassignment();
  4885. }
  4886. // We keep conditional chaining because an unknown Node could have an
  4887. // Identifier as property that might be deoptimized by default
  4888. this.variable?.deoptimizePath(path);
  4889. }
  4890. getLiteralValueAtPath(path, recursionTracker, origin) {
  4891. return this.getVariableRespectingTDZ().getLiteralValueAtPath(path, recursionTracker, origin);
  4892. }
  4893. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  4894. const [expression, isPure] = this.getVariableRespectingTDZ().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  4895. return [expression, isPure || this.isPureFunction(path)];
  4896. }
  4897. hasEffects(context) {
  4898. if (!this.deoptimized)
  4899. this.applyDeoptimizations();
  4900. if (this.isPossibleTDZ() && this.variable.kind !== 'var') {
  4901. return true;
  4902. }
  4903. return (this.scope.context.options.treeshake
  4904. .unknownGlobalSideEffects &&
  4905. this.variable instanceof GlobalVariable &&
  4906. !this.isPureFunction(EMPTY_PATH) &&
  4907. this.variable.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_ACCESS, context));
  4908. }
  4909. hasEffectsOnInteractionAtPath(path, interaction, context) {
  4910. switch (interaction.type) {
  4911. case INTERACTION_ACCESSED: {
  4912. return (this.variable !== null &&
  4913. !this.isPureFunction(path) &&
  4914. this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context));
  4915. }
  4916. case INTERACTION_ASSIGNED: {
  4917. return (path.length > 0 ? this.getVariableRespectingTDZ() : this.variable).hasEffectsOnInteractionAtPath(path, interaction, context);
  4918. }
  4919. case INTERACTION_CALLED: {
  4920. return (!this.isPureFunction(path) &&
  4921. this.getVariableRespectingTDZ().hasEffectsOnInteractionAtPath(path, interaction, context));
  4922. }
  4923. }
  4924. }
  4925. include(context, includeChildrenRecursively) {
  4926. if (!this.included)
  4927. this.includeNode(context);
  4928. if (includeChildrenRecursively) {
  4929. this.variable?.includePath(UNKNOWN_PATH, context);
  4930. }
  4931. }
  4932. includeNode(context) {
  4933. this.included = true;
  4934. if (!this.deoptimized)
  4935. this.applyDeoptimizations();
  4936. if (this.variable !== null) {
  4937. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  4938. }
  4939. }
  4940. includePath(path, context) {
  4941. if (!this.included) {
  4942. this.included = true;
  4943. if (!this.deoptimized)
  4944. this.applyDeoptimizations();
  4945. if (this.variable !== null) {
  4946. this.scope.context.includeVariableInModule(this.variable, path, context);
  4947. }
  4948. }
  4949. else if (path.length > 0) {
  4950. this.variable?.includePath(path, context);
  4951. }
  4952. }
  4953. includeCallArguments(interaction, context) {
  4954. this.variable.includeCallArguments(interaction, context);
  4955. }
  4956. isPossibleTDZ() {
  4957. // return cached value to avoid issues with the next tree-shaking pass
  4958. const cachedTdzAccess = this.isTDZAccess;
  4959. if (cachedTdzAccess !== null)
  4960. return cachedTdzAccess;
  4961. if (!(this.variable instanceof LocalVariable &&
  4962. this.variable.kind &&
  4963. tdzVariableKinds.has(this.variable.kind) &&
  4964. // We ignore modules that did not receive a treeshaking pass yet as that
  4965. // causes many false positives due to circular dependencies or disabled
  4966. // moduleSideEffects.
  4967. this.variable.module.hasTreeShakingPassStarted)) {
  4968. return (this.isTDZAccess = false);
  4969. }
  4970. let decl_id;
  4971. if (this.variable.declarations &&
  4972. this.variable.declarations.length === 1 &&
  4973. (decl_id = this.variable.declarations[0]) &&
  4974. this.start < decl_id.start &&
  4975. closestParentFunctionOrProgram(this) === closestParentFunctionOrProgram(decl_id)) {
  4976. // a variable accessed before its declaration
  4977. // in the same function or at top level of module
  4978. return (this.isTDZAccess = true);
  4979. }
  4980. if (!this.variable.initReached) {
  4981. // Either a const/let TDZ violation or
  4982. // var use before declaration was encountered.
  4983. return (this.isTDZAccess = true);
  4984. }
  4985. return (this.isTDZAccess = false);
  4986. }
  4987. applyDeoptimizations() {
  4988. this.deoptimized = true;
  4989. if (this.variable instanceof LocalVariable) {
  4990. // When accessing a variable from a module without side effects, this
  4991. // means we use an export of that module and therefore need to potentially
  4992. // include it in the bundle.
  4993. if (!this.variable.module.isExecuted) {
  4994. markModuleAndImpureDependenciesAsExecuted(this.variable.module);
  4995. }
  4996. this.variable.consolidateInitializers();
  4997. this.scope.context.requestTreeshakingPass();
  4998. }
  4999. if (this.isVariableReference) {
  5000. this.variable.addUsedPlace(this);
  5001. this.scope.context.requestTreeshakingPass();
  5002. }
  5003. }
  5004. disallowImportReassignment() {
  5005. return this.scope.context.error(logIllegalImportReassignment(this.name, this.scope.context.module.id), this.start);
  5006. }
  5007. getVariableRespectingTDZ() {
  5008. if (this.isPossibleTDZ()) {
  5009. return UNKNOWN_EXPRESSION;
  5010. }
  5011. return this.variable;
  5012. }
  5013. isPureFunction(path) {
  5014. let currentPureFunction = this.scope.context.manualPureFunctions[this.name];
  5015. for (const segment of path) {
  5016. if (currentPureFunction) {
  5017. if (currentPureFunction[PureFunctionKey]) {
  5018. return true;
  5019. }
  5020. currentPureFunction = currentPureFunction[segment];
  5021. }
  5022. else {
  5023. return false;
  5024. }
  5025. }
  5026. return currentPureFunction?.[PureFunctionKey];
  5027. }
  5028. }
  5029. function closestParentFunctionOrProgram(node) {
  5030. while (node && !/^Program|Function/.test(node.type)) {
  5031. node = node.parent;
  5032. }
  5033. // one of: ArrowFunctionExpression, FunctionDeclaration, FunctionExpression or Program
  5034. return node;
  5035. }
  5036. class ObjectMember extends ExpressionEntity {
  5037. constructor(object, path) {
  5038. super();
  5039. this.object = object;
  5040. this.path = path;
  5041. }
  5042. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  5043. this.object.deoptimizeArgumentsOnInteractionAtPath(interaction, [...this.path, ...path], recursionTracker);
  5044. }
  5045. deoptimizePath(path) {
  5046. this.object.deoptimizePath([...this.path, ...path]);
  5047. }
  5048. getLiteralValueAtPath(path, recursionTracker, origin) {
  5049. return this.object.getLiteralValueAtPath([...this.path, ...path], recursionTracker, origin);
  5050. }
  5051. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  5052. return this.object.getReturnExpressionWhenCalledAtPath([...this.path, ...path], interaction, recursionTracker, origin);
  5053. }
  5054. hasEffectsOnInteractionAtPath(path, interaction, context) {
  5055. return this.object.hasEffectsOnInteractionAtPath([...this.path, ...path], interaction, context);
  5056. }
  5057. }
  5058. class Identifier extends IdentifierBase {
  5059. constructor() {
  5060. super(...arguments);
  5061. this.variable = null;
  5062. }
  5063. get isDestructuringDeoptimized() {
  5064. return isFlagSet(this.flags, 16777216 /* Flag.destructuringDeoptimized */);
  5065. }
  5066. set isDestructuringDeoptimized(value) {
  5067. this.flags = setFlag(this.flags, 16777216 /* Flag.destructuringDeoptimized */, value);
  5068. }
  5069. addExportedVariables(variables, exportNamesByVariable) {
  5070. if (exportNamesByVariable.has(this.variable)) {
  5071. variables.push(this.variable);
  5072. }
  5073. }
  5074. bind() {
  5075. if (!this.variable && is_reference(this, this.parent)) {
  5076. this.variable = this.scope.findVariable(this.name);
  5077. this.variable.addReference(this);
  5078. this.isVariableReference = true;
  5079. }
  5080. }
  5081. declare(kind, destructuredInitPath, init) {
  5082. let variable;
  5083. const { treeshake } = this.scope.context.options;
  5084. if (kind === 'parameter') {
  5085. variable = this.scope.addParameterDeclaration(this, destructuredInitPath);
  5086. }
  5087. else {
  5088. variable = this.scope.addDeclaration(this, this.scope.context, init, destructuredInitPath, kind);
  5089. if (kind === 'var' && treeshake && treeshake.correctVarValueBeforeDeclaration) {
  5090. // Necessary to make sure the init is deoptimized. We cannot call deoptimizePath here.
  5091. variable.markInitializersForDeoptimization();
  5092. }
  5093. }
  5094. return [(this.variable = variable)];
  5095. }
  5096. deoptimizeAssignment(destructuredInitPath, init) {
  5097. this.deoptimizePath(EMPTY_PATH);
  5098. init.deoptimizePath([...destructuredInitPath, UnknownKey]);
  5099. }
  5100. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  5101. return (destructuredInitPath.length > 0 &&
  5102. init.hasEffectsOnInteractionAtPath(destructuredInitPath, NODE_INTERACTION_UNKNOWN_ACCESS, context));
  5103. }
  5104. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  5105. if (destructuredInitPath.length > 0 && !this.isDestructuringDeoptimized) {
  5106. this.isDestructuringDeoptimized = true;
  5107. init.deoptimizeArgumentsOnInteractionAtPath({
  5108. args: [new ObjectMember(init, destructuredInitPath.slice(0, -1))],
  5109. type: INTERACTION_ACCESSED
  5110. }, destructuredInitPath, SHARED_RECURSION_TRACKER);
  5111. }
  5112. const { propertyReadSideEffects } = this.scope.context.options
  5113. .treeshake;
  5114. let included = this.included;
  5115. if ((included ||=
  5116. destructuredInitPath.length > 0 &&
  5117. !context.brokenFlow &&
  5118. propertyReadSideEffects &&
  5119. (propertyReadSideEffects === 'always' ||
  5120. init.hasEffectsOnInteractionAtPath(destructuredInitPath, NODE_INTERACTION_UNKNOWN_ACCESS, createHasEffectsContext())))) {
  5121. if (this.variable && !this.variable.included) {
  5122. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  5123. }
  5124. init.includePath(destructuredInitPath, context);
  5125. }
  5126. if (!this.included && included) {
  5127. this.includeNode(context);
  5128. }
  5129. return this.included;
  5130. }
  5131. markDeclarationReached() {
  5132. this.variable.initReached = true;
  5133. }
  5134. render(code, { snippets: { getPropertyAccess }, useOriginalName }, { renderedParentType, isCalleeOfRenderedParent, isShorthandProperty } = BLANK) {
  5135. if (this.variable) {
  5136. const name = this.variable.getName(getPropertyAccess, useOriginalName);
  5137. if (name !== this.name) {
  5138. code.overwrite(this.start, this.end, name, {
  5139. contentOnly: true,
  5140. storeName: true
  5141. });
  5142. if (isShorthandProperty) {
  5143. code.prependRight(this.start, `${this.name}: `);
  5144. }
  5145. }
  5146. // In strict mode, any variable named "eval" must be the actual "eval" function
  5147. if (name === 'eval' &&
  5148. renderedParentType === CallExpression$1 &&
  5149. isCalleeOfRenderedParent) {
  5150. code.appendRight(this.start, '0, ');
  5151. }
  5152. }
  5153. }
  5154. }
  5155. const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
  5156. const base = 64;
  5157. function toBase64(value) {
  5158. let outString = '';
  5159. do {
  5160. const currentDigit = value % base;
  5161. value = (value / base) | 0;
  5162. outString = chars[currentDigit] + outString;
  5163. } while (value !== 0);
  5164. return outString;
  5165. }
  5166. function getSafeName(baseName, usedNames, forbiddenNames) {
  5167. let safeName = baseName;
  5168. let count = 1;
  5169. while (usedNames.has(safeName) || RESERVED_NAMES.has(safeName) || forbiddenNames?.has(safeName)) {
  5170. safeName = `${baseName}$${toBase64(count++)}`;
  5171. }
  5172. usedNames.add(safeName);
  5173. return safeName;
  5174. }
  5175. class Scope {
  5176. constructor() {
  5177. this.children = [];
  5178. this.variables = new Map();
  5179. }
  5180. /*
  5181. Redeclaration rules:
  5182. - var can redeclare var
  5183. - in function scopes, function and var can redeclare function and var
  5184. - var is hoisted across scopes, function remains in the scope it is declared
  5185. - var and function can redeclare function parameters, but parameters cannot redeclare parameters
  5186. - function cannot redeclare catch scope parameters
  5187. - var can redeclare catch scope parameters in a way
  5188. - if the parameter is an identifier and not a pattern
  5189. - then the variable is still declared in the hoisted outer scope, but the initializer is assigned to the parameter
  5190. - const, let, class, and function except in the cases above cannot redeclare anything
  5191. */
  5192. addDeclaration(identifier, context, init, destructuredInitPath, kind) {
  5193. const name = identifier.name;
  5194. const existingVariable = this.hoistedVariables?.get(name) || this.variables.get(name);
  5195. if (existingVariable) {
  5196. if (kind === 'var' && existingVariable.kind === 'var') {
  5197. existingVariable.addDeclaration(identifier, init);
  5198. return existingVariable;
  5199. }
  5200. context.error(logRedeclarationError(name), identifier.start);
  5201. }
  5202. const newVariable = new LocalVariable(identifier.name, identifier, init, destructuredInitPath, context, kind);
  5203. this.variables.set(name, newVariable);
  5204. return newVariable;
  5205. }
  5206. addHoistedVariable(name, variable) {
  5207. (this.hoistedVariables ||= new Map()).set(name, variable);
  5208. }
  5209. contains(name) {
  5210. return this.variables.has(name);
  5211. }
  5212. findVariable(_name) {
  5213. /* istanbul ignore next */
  5214. throw new Error('Internal Error: findVariable needs to be implemented by a subclass');
  5215. }
  5216. }
  5217. class ChildScope extends Scope {
  5218. constructor(parent, context) {
  5219. super();
  5220. this.parent = parent;
  5221. this.context = context;
  5222. this.accessedOutsideVariables = new Map();
  5223. parent.children.push(this);
  5224. }
  5225. addAccessedDynamicImport(importExpression) {
  5226. (this.accessedDynamicImports || (this.accessedDynamicImports = new Set())).add(importExpression);
  5227. if (this.parent instanceof ChildScope) {
  5228. this.parent.addAccessedDynamicImport(importExpression);
  5229. }
  5230. }
  5231. addAccessedGlobals(globals, accessedGlobalsByScope) {
  5232. const accessedGlobals = accessedGlobalsByScope.get(this) || new Set();
  5233. for (const name of globals) {
  5234. accessedGlobals.add(name);
  5235. }
  5236. accessedGlobalsByScope.set(this, accessedGlobals);
  5237. if (this.parent instanceof ChildScope) {
  5238. this.parent.addAccessedGlobals(globals, accessedGlobalsByScope);
  5239. }
  5240. }
  5241. addNamespaceMemberAccess(name, variable) {
  5242. this.accessedOutsideVariables.set(name, variable);
  5243. this.parent.addNamespaceMemberAccess(name, variable);
  5244. }
  5245. addReturnExpression(expression) {
  5246. if (this.parent instanceof ChildScope) {
  5247. this.parent.addReturnExpression(expression);
  5248. }
  5249. }
  5250. addUsedOutsideNames(usedNames, accessedGlobalsByScope) {
  5251. for (const variable of this.accessedOutsideVariables.values()) {
  5252. if (variable.included) {
  5253. usedNames.add(variable.getBaseVariableName());
  5254. }
  5255. }
  5256. const accessedGlobals = accessedGlobalsByScope.get(this);
  5257. if (accessedGlobals) {
  5258. for (const name of accessedGlobals) {
  5259. usedNames.add(name);
  5260. }
  5261. }
  5262. }
  5263. contains(name) {
  5264. return this.variables.has(name) || this.parent.contains(name);
  5265. }
  5266. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  5267. const usedNames = new Set();
  5268. this.addUsedOutsideNames(usedNames, accessedGlobalsByScope);
  5269. if (this.accessedDynamicImports) {
  5270. for (const importExpression of this.accessedDynamicImports) {
  5271. if (importExpression.inlineNamespace) {
  5272. usedNames.add(importExpression.inlineNamespace.getBaseVariableName());
  5273. }
  5274. }
  5275. }
  5276. for (const [name, variable] of this.variables) {
  5277. if (variable.included || variable.alwaysRendered) {
  5278. variable.setRenderNames(null, getSafeName(name, usedNames, variable.forbiddenNames));
  5279. }
  5280. }
  5281. for (const scope of this.children) {
  5282. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  5283. }
  5284. }
  5285. findLexicalBoundary() {
  5286. return this.parent.findLexicalBoundary();
  5287. }
  5288. findGlobal(name) {
  5289. const variable = this.parent.findVariable(name);
  5290. this.accessedOutsideVariables.set(name, variable);
  5291. return variable;
  5292. }
  5293. findVariable(name) {
  5294. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  5295. if (knownVariable) {
  5296. return knownVariable;
  5297. }
  5298. const variable = this.parent.findVariable(name);
  5299. this.accessedOutsideVariables.set(name, variable);
  5300. return variable;
  5301. }
  5302. }
  5303. function checkEffectForNodes(nodes, context) {
  5304. for (const node of nodes) {
  5305. if (node.hasEffects(context)) {
  5306. return true;
  5307. }
  5308. }
  5309. return false;
  5310. }
  5311. class MethodBase extends NodeBase {
  5312. constructor() {
  5313. super(...arguments);
  5314. this.accessedValue = null;
  5315. }
  5316. get computed() {
  5317. return isFlagSet(this.flags, 1024 /* Flag.computed */);
  5318. }
  5319. set computed(value) {
  5320. this.flags = setFlag(this.flags, 1024 /* Flag.computed */, value);
  5321. }
  5322. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  5323. if (interaction.type === INTERACTION_ACCESSED && this.kind === 'get' && path.length === 0) {
  5324. return this.value.deoptimizeArgumentsOnInteractionAtPath({
  5325. args: interaction.args,
  5326. type: INTERACTION_CALLED,
  5327. withNew: false
  5328. }, EMPTY_PATH, recursionTracker);
  5329. }
  5330. if (interaction.type === INTERACTION_ASSIGNED && this.kind === 'set' && path.length === 0) {
  5331. return this.value.deoptimizeArgumentsOnInteractionAtPath({
  5332. args: interaction.args,
  5333. type: INTERACTION_CALLED,
  5334. withNew: false
  5335. }, EMPTY_PATH, recursionTracker);
  5336. }
  5337. this.getAccessedValue()[0].deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  5338. }
  5339. // As getter properties directly receive their values from fixed function
  5340. // expressions, there is no known situation where a getter is deoptimized.
  5341. deoptimizeCache() { }
  5342. deoptimizePath(path) {
  5343. this.getAccessedValue()[0].deoptimizePath(path);
  5344. }
  5345. getLiteralValueAtPath(path, recursionTracker, origin) {
  5346. return this.getAccessedValue()[0].getLiteralValueAtPath(path, recursionTracker, origin);
  5347. }
  5348. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  5349. return this.getAccessedValue()[0].getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  5350. }
  5351. hasEffects(context) {
  5352. return this.key.hasEffects(context);
  5353. }
  5354. hasEffectsOnInteractionAtPath(path, interaction, context) {
  5355. if (this.kind === 'get' && interaction.type === INTERACTION_ACCESSED && path.length === 0) {
  5356. return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
  5357. args: interaction.args,
  5358. type: INTERACTION_CALLED,
  5359. withNew: false
  5360. }, context);
  5361. }
  5362. // setters are only called for empty paths
  5363. if (this.kind === 'set' && interaction.type === INTERACTION_ASSIGNED) {
  5364. return this.value.hasEffectsOnInteractionAtPath(EMPTY_PATH, {
  5365. args: interaction.args,
  5366. type: INTERACTION_CALLED,
  5367. withNew: false
  5368. }, context);
  5369. }
  5370. return this.getAccessedValue()[0].hasEffectsOnInteractionAtPath(path, interaction, context);
  5371. }
  5372. getAccessedValue() {
  5373. if (this.accessedValue === null) {
  5374. if (this.kind === 'get') {
  5375. this.accessedValue = UNKNOWN_RETURN_EXPRESSION;
  5376. return (this.accessedValue = this.value.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, SHARED_RECURSION_TRACKER, this));
  5377. }
  5378. else {
  5379. return (this.accessedValue = [this.value, false]);
  5380. }
  5381. }
  5382. return this.accessedValue;
  5383. }
  5384. }
  5385. MethodBase.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  5386. MethodBase.prototype.applyDeoptimizations = doNotDeoptimize;
  5387. class MethodDefinition extends MethodBase {
  5388. hasEffects(context) {
  5389. return super.hasEffects(context) || checkEffectForNodes(this.decorators, context);
  5390. }
  5391. }
  5392. class BlockScope extends ChildScope {
  5393. constructor(parent) {
  5394. super(parent, parent.context);
  5395. }
  5396. addDeclaration(identifier, context, init, destructuredInitPath, kind) {
  5397. if (kind === 'var') {
  5398. const name = identifier.name;
  5399. const existingVariable = this.hoistedVariables?.get(name) || this.variables.get(name);
  5400. if (existingVariable) {
  5401. if (existingVariable.kind === 'var' ||
  5402. (kind === 'var' && existingVariable.kind === 'parameter')) {
  5403. existingVariable.addDeclaration(identifier, init);
  5404. return existingVariable;
  5405. }
  5406. return context.error(logRedeclarationError(name), identifier.start);
  5407. }
  5408. const declaredVariable = this.parent.addDeclaration(identifier, context, init, destructuredInitPath, kind);
  5409. // Necessary to make sure the init is deoptimized for conditional declarations.
  5410. // We cannot call deoptimizePath here.
  5411. declaredVariable.markInitializersForDeoptimization();
  5412. // We add the variable to this and all parent scopes to reliably detect conflicts
  5413. this.addHoistedVariable(name, declaredVariable);
  5414. return declaredVariable;
  5415. }
  5416. return super.addDeclaration(identifier, context, init, destructuredInitPath, kind);
  5417. }
  5418. }
  5419. class StaticBlock extends NodeBase {
  5420. createScope(parentScope) {
  5421. this.scope = new BlockScope(parentScope);
  5422. }
  5423. hasEffects(context) {
  5424. for (const node of this.body) {
  5425. if (node.hasEffects(context))
  5426. return true;
  5427. }
  5428. return false;
  5429. }
  5430. include(context, includeChildrenRecursively) {
  5431. this.included = true;
  5432. for (const node of this.body) {
  5433. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  5434. node.include(context, includeChildrenRecursively);
  5435. }
  5436. }
  5437. render(code, options) {
  5438. if (this.body.length > 0) {
  5439. const bodyStartPos = findFirstOccurrenceOutsideComment(code.original.slice(this.start, this.end), '{') + 1;
  5440. renderStatementList(this.body, code, this.start + bodyStartPos, this.end - 1, options);
  5441. }
  5442. else {
  5443. super.render(code, options);
  5444. }
  5445. }
  5446. }
  5447. StaticBlock.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  5448. StaticBlock.prototype.applyDeoptimizations = doNotDeoptimize;
  5449. function isStaticBlock(statement) {
  5450. return statement.type === StaticBlock$1;
  5451. }
  5452. class ClassNode extends NodeBase {
  5453. constructor() {
  5454. super(...arguments);
  5455. this.objectEntity = null;
  5456. }
  5457. createScope(parentScope) {
  5458. this.scope = new ChildScope(parentScope, parentScope.context);
  5459. }
  5460. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  5461. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  5462. }
  5463. deoptimizeCache() {
  5464. this.getObjectEntity().deoptimizeAllProperties();
  5465. }
  5466. deoptimizePath(path) {
  5467. this.getObjectEntity().deoptimizePath(path);
  5468. }
  5469. getLiteralValueAtPath(path, recursionTracker, origin) {
  5470. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  5471. }
  5472. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  5473. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  5474. }
  5475. hasEffects(context) {
  5476. if (!this.deoptimized)
  5477. this.applyDeoptimizations();
  5478. const initEffect = this.superClass?.hasEffects(context) || this.body.hasEffects(context);
  5479. this.id?.markDeclarationReached();
  5480. return initEffect || super.hasEffects(context) || checkEffectForNodes(this.decorators, context);
  5481. }
  5482. hasEffectsOnInteractionAtPath(path, interaction, context) {
  5483. return interaction.type === INTERACTION_CALLED && path.length === 0
  5484. ? !interaction.withNew ||
  5485. (this.classConstructor === null
  5486. ? this.superClass?.hasEffectsOnInteractionAtPath(path, interaction, context)
  5487. : this.classConstructor.hasEffectsOnInteractionAtPath(path, interaction, context)) ||
  5488. false
  5489. : this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  5490. }
  5491. include(context, includeChildrenRecursively) {
  5492. if (!this.included)
  5493. this.includeNode(context);
  5494. this.superClass?.include(context, includeChildrenRecursively);
  5495. this.body.include(context, includeChildrenRecursively);
  5496. for (const decorator of this.decorators)
  5497. decorator.include(context, includeChildrenRecursively);
  5498. if (this.id) {
  5499. this.id.markDeclarationReached();
  5500. this.id.include(context, includeChildrenRecursively);
  5501. }
  5502. }
  5503. initialise() {
  5504. super.initialise();
  5505. this.id?.declare('class', EMPTY_PATH, this);
  5506. for (const method of this.body.body) {
  5507. if (method instanceof MethodDefinition && method.kind === 'constructor') {
  5508. this.classConstructor = method;
  5509. return;
  5510. }
  5511. }
  5512. this.classConstructor = null;
  5513. }
  5514. applyDeoptimizations() {
  5515. this.deoptimized = true;
  5516. for (const definition of this.body.body) {
  5517. if (!isStaticBlock(definition) &&
  5518. !(definition.static ||
  5519. (definition instanceof MethodDefinition && definition.kind === 'constructor'))) {
  5520. // Calls to methods are not tracked, ensure that the return value is deoptimized
  5521. definition.deoptimizePath(UNKNOWN_PATH);
  5522. }
  5523. }
  5524. this.scope.context.requestTreeshakingPass();
  5525. }
  5526. getObjectEntity() {
  5527. if (this.objectEntity !== null) {
  5528. return this.objectEntity;
  5529. }
  5530. const staticProperties = [];
  5531. const dynamicMethods = [];
  5532. for (const definition of this.body.body) {
  5533. if (isStaticBlock(definition))
  5534. continue;
  5535. const properties = definition.static ? staticProperties : dynamicMethods;
  5536. const definitionKind = definition.kind;
  5537. // Note that class fields do not end up on the prototype
  5538. if (properties === dynamicMethods && !definitionKind)
  5539. continue;
  5540. const kind = definitionKind === 'set' || definitionKind === 'get' ? definitionKind : 'init';
  5541. let key;
  5542. if (definition.computed) {
  5543. const keyValue = definition.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  5544. if (typeof keyValue === 'symbol') {
  5545. properties.push({
  5546. key: isAnyWellKnown(keyValue) ? keyValue : UnknownKey,
  5547. kind,
  5548. property: definition
  5549. });
  5550. continue;
  5551. }
  5552. else {
  5553. key = String(keyValue);
  5554. }
  5555. }
  5556. else {
  5557. key =
  5558. definition.key instanceof Identifier
  5559. ? definition.key.name
  5560. : String(definition.key.value);
  5561. }
  5562. properties.push({ key, kind, property: definition });
  5563. }
  5564. staticProperties.unshift({
  5565. key: 'prototype',
  5566. kind: 'init',
  5567. property: new ObjectEntity(dynamicMethods, this.superClass ? new ObjectMember(this.superClass, ['prototype']) : OBJECT_PROTOTYPE)
  5568. });
  5569. return (this.objectEntity = new ObjectEntity(staticProperties, this.superClass || OBJECT_PROTOTYPE));
  5570. }
  5571. }
  5572. ClassNode.prototype.includeNode = onlyIncludeSelf;
  5573. class ClassDeclaration extends ClassNode {
  5574. initialise() {
  5575. super.initialise();
  5576. if (this.id !== null) {
  5577. this.id.variable.isId = true;
  5578. }
  5579. }
  5580. parseNode(esTreeNode) {
  5581. if (esTreeNode.id !== null) {
  5582. this.id = new Identifier(this, this.scope.parent).parseNode(esTreeNode.id);
  5583. }
  5584. return super.parseNode(esTreeNode);
  5585. }
  5586. render(code, options) {
  5587. const { exportNamesByVariable, format, snippets: { _, getPropertyAccess } } = options;
  5588. if (this.id) {
  5589. const { variable, name } = this.id;
  5590. if (format === 'system' && exportNamesByVariable.has(variable)) {
  5591. code.appendLeft(this.end, `${_}${getSystemExportStatement([variable], options)};`);
  5592. }
  5593. const renderedVariable = variable.getName(getPropertyAccess);
  5594. if (renderedVariable !== name) {
  5595. this.decorators.map(decorator => decorator.render(code, options));
  5596. this.superClass?.render(code, options);
  5597. this.body.render(code, {
  5598. ...options,
  5599. useOriginalName: (_variable) => _variable === variable
  5600. });
  5601. code.prependRight(this.start, `let ${renderedVariable}${_}=${_}`);
  5602. code.prependLeft(this.end, ';');
  5603. return;
  5604. }
  5605. }
  5606. super.render(code, options);
  5607. }
  5608. applyDeoptimizations() {
  5609. super.applyDeoptimizations();
  5610. const { id, scope } = this;
  5611. if (id) {
  5612. const { name, variable } = id;
  5613. for (const accessedVariable of scope.accessedOutsideVariables.values()) {
  5614. if (accessedVariable !== variable) {
  5615. accessedVariable.forbidName(name);
  5616. }
  5617. }
  5618. }
  5619. }
  5620. }
  5621. class ArgumentsVariable extends LocalVariable {
  5622. constructor(context) {
  5623. super('arguments', null, UNKNOWN_EXPRESSION, EMPTY_PATH, context, 'other');
  5624. }
  5625. addArgumentToBeDeoptimized(_argument) { }
  5626. // Only If there is at least one reference, then we need to track all
  5627. // arguments in order to be able to deoptimize them.
  5628. addReference() {
  5629. this.deoptimizedArguments = [];
  5630. this.addArgumentToBeDeoptimized = addArgumentToBeDeoptimized;
  5631. }
  5632. hasEffectsOnInteractionAtPath(path, { type }) {
  5633. return type !== INTERACTION_ACCESSED || path.length > 1;
  5634. }
  5635. includePath(path, context) {
  5636. super.includePath(path, context);
  5637. for (const argument of this.deoptimizedArguments) {
  5638. argument.deoptimizePath(UNKNOWN_PATH);
  5639. }
  5640. this.deoptimizedArguments.length = 0;
  5641. }
  5642. }
  5643. function addArgumentToBeDeoptimized(argument) {
  5644. if (this.included) {
  5645. argument.deoptimizePath(UNKNOWN_PATH);
  5646. }
  5647. else {
  5648. this.deoptimizedArguments?.push(argument);
  5649. }
  5650. }
  5651. const MAX_TRACKED_INTERACTIONS = 20;
  5652. const NO_INTERACTIONS = EMPTY_ARRAY;
  5653. const UNKNOWN_DEOPTIMIZED_FIELD = new Set([UnknownKey]);
  5654. const EMPTY_PATH_TRACKER = new EntityPathTracker();
  5655. const UNKNOWN_DEOPTIMIZED_ENTITY = new Set([UNKNOWN_EXPRESSION]);
  5656. class ParameterVariable extends LocalVariable {
  5657. constructor(name, declarator, argumentPath, context) {
  5658. super(name, declarator, UNKNOWN_EXPRESSION, argumentPath, context, 'parameter');
  5659. this.includedPathTracker = new IncludedTopLevelPathTracker();
  5660. this.argumentsToBeDeoptimized = new Set();
  5661. this.deoptimizationInteractions = [];
  5662. this.deoptimizations = new EntityPathTracker();
  5663. this.deoptimizedFields = new Set();
  5664. this.expressionsDependingOnKnownValue = [];
  5665. this.knownValue = null;
  5666. this.knownValueLiteral = UnknownValue;
  5667. }
  5668. addArgumentForDeoptimization(entity) {
  5669. this.updateKnownValue(entity);
  5670. if (entity === UNKNOWN_EXPRESSION) {
  5671. // As unknown expressions fully deoptimize all interactions, we can clear
  5672. // the interaction cache at this point provided we keep this optimization
  5673. // in mind when adding new interactions
  5674. if (!this.argumentsToBeDeoptimized.has(UNKNOWN_EXPRESSION)) {
  5675. this.argumentsToBeDeoptimized.add(UNKNOWN_EXPRESSION);
  5676. for (const { interaction } of this.deoptimizationInteractions) {
  5677. deoptimizeInteraction(interaction);
  5678. }
  5679. this.deoptimizationInteractions = NO_INTERACTIONS;
  5680. }
  5681. }
  5682. else if (this.deoptimizedFields.has(UnknownKey)) {
  5683. // This means that we already deoptimized all interactions and no longer
  5684. // track them
  5685. entity.deoptimizePath([...this.initPath, UnknownKey]);
  5686. }
  5687. else if (!this.argumentsToBeDeoptimized.has(entity)) {
  5688. this.argumentsToBeDeoptimized.add(entity);
  5689. for (const field of this.deoptimizedFields) {
  5690. entity.deoptimizePath([...this.initPath, field]);
  5691. }
  5692. for (const { interaction, path } of this.deoptimizationInteractions) {
  5693. entity.deoptimizeArgumentsOnInteractionAtPath(interaction, [...this.initPath, ...path], SHARED_RECURSION_TRACKER);
  5694. }
  5695. }
  5696. }
  5697. /** This says we should not make assumptions about the value of the parameter.
  5698. * This is different from deoptimization that will also cause argument values
  5699. * to be deoptimized. */
  5700. markReassigned() {
  5701. if (this.isReassigned) {
  5702. return;
  5703. }
  5704. super.markReassigned();
  5705. for (const expression of this.expressionsDependingOnKnownValue) {
  5706. expression.deoptimizeCache();
  5707. }
  5708. this.expressionsDependingOnKnownValue = EMPTY_ARRAY;
  5709. }
  5710. deoptimizeCache() {
  5711. this.markReassigned();
  5712. }
  5713. /**
  5714. * Update the known value of the parameter variable.
  5715. * Must be called for every function call, so it can track all the arguments,
  5716. * and deoptimizeCache itself to mark reassigned if the argument is changed.
  5717. * @param argument The argument of the function call
  5718. */
  5719. updateKnownValue(argument) {
  5720. if (this.isReassigned) {
  5721. return;
  5722. }
  5723. if (this.knownValue === null) {
  5724. this.knownValue = argument;
  5725. this.knownValueLiteral = argument.getLiteralValueAtPath(this.initPath, SHARED_RECURSION_TRACKER, this);
  5726. return;
  5727. }
  5728. // the same literal or identifier, do nothing
  5729. if (this.knownValue === argument ||
  5730. (this.knownValue instanceof Identifier &&
  5731. argument instanceof Identifier &&
  5732. this.knownValue.variable === argument.variable)) {
  5733. return;
  5734. }
  5735. const { knownValueLiteral } = this;
  5736. if (typeof knownValueLiteral === 'symbol' ||
  5737. argument.getLiteralValueAtPath(this.initPath, SHARED_RECURSION_TRACKER, this) !==
  5738. knownValueLiteral) {
  5739. this.markReassigned();
  5740. }
  5741. }
  5742. /**
  5743. * This function freezes the known value of the parameter variable,
  5744. * so the optimization starts with a certain ExpressionEntity.
  5745. * The optimization can be undone by calling `markReassigned`.
  5746. * @returns the frozen value
  5747. */
  5748. getKnownValue() {
  5749. return this.knownValue || UNKNOWN_EXPRESSION;
  5750. }
  5751. getLiteralValueAtPath(path, recursionTracker, origin) {
  5752. if (this.isReassigned || path.length + this.initPath.length > MAX_PATH_DEPTH) {
  5753. return UnknownValue;
  5754. }
  5755. const knownValue = this.getKnownValue();
  5756. this.expressionsDependingOnKnownValue.push(origin);
  5757. return recursionTracker.withTrackedEntityAtPath(path, knownValue, () => knownValue.getLiteralValueAtPath([...this.initPath, ...path], recursionTracker, origin), UnknownValue);
  5758. }
  5759. hasEffectsOnInteractionAtPath(path, interaction, context) {
  5760. const { type } = interaction;
  5761. if (this.isReassigned ||
  5762. type === INTERACTION_ASSIGNED ||
  5763. path.length + this.initPath.length > MAX_PATH_DEPTH) {
  5764. return super.hasEffectsOnInteractionAtPath(path, interaction, context);
  5765. }
  5766. return (!(type === INTERACTION_CALLED
  5767. ? (interaction.withNew
  5768. ? context.instantiated
  5769. : context.called).trackEntityAtPathAndGetIfTracked(path, interaction.args, this)
  5770. : context.accessed.trackEntityAtPathAndGetIfTracked(path, this)) &&
  5771. this.getKnownValue().hasEffectsOnInteractionAtPath([...this.initPath, ...path], interaction, context));
  5772. }
  5773. deoptimizeArgumentsOnInteractionAtPath(interaction, path) {
  5774. // For performance reasons, we fully deoptimize all deeper interactions
  5775. if (path.length >= 2 ||
  5776. this.argumentsToBeDeoptimized.has(UNKNOWN_EXPRESSION) ||
  5777. this.deoptimizationInteractions.length >= MAX_TRACKED_INTERACTIONS ||
  5778. (path.length === 1 &&
  5779. (this.deoptimizedFields.has(UnknownKey) ||
  5780. (interaction.type === INTERACTION_CALLED && this.deoptimizedFields.has(path[0])))) ||
  5781. this.initPath.length + path.length > MAX_PATH_DEPTH) {
  5782. deoptimizeInteraction(interaction);
  5783. return;
  5784. }
  5785. if (!this.deoptimizations.trackEntityAtPathAndGetIfTracked(path, interaction.args)) {
  5786. for (const entity of this.argumentsToBeDeoptimized) {
  5787. entity.deoptimizeArgumentsOnInteractionAtPath(interaction, [...this.initPath, ...path], SHARED_RECURSION_TRACKER);
  5788. }
  5789. if (!this.argumentsToBeDeoptimized.has(UNKNOWN_EXPRESSION)) {
  5790. this.deoptimizationInteractions.push({
  5791. interaction,
  5792. path
  5793. });
  5794. }
  5795. }
  5796. }
  5797. deoptimizePath(path) {
  5798. if (path.length === 0) {
  5799. this.markReassigned();
  5800. return;
  5801. }
  5802. if (this.deoptimizedFields.has(UnknownKey)) {
  5803. return;
  5804. }
  5805. const key = path[0];
  5806. if (this.deoptimizedFields.has(key)) {
  5807. return;
  5808. }
  5809. this.deoptimizedFields.add(key);
  5810. for (const entity of this.argumentsToBeDeoptimized) {
  5811. // We do not need a recursion tracker here as we already track whether
  5812. // this field is deoptimized
  5813. entity.deoptimizePath([...this.initPath, key]);
  5814. }
  5815. if (key === UnknownKey) {
  5816. // save some memory
  5817. this.deoptimizationInteractions = NO_INTERACTIONS;
  5818. this.deoptimizations = EMPTY_PATH_TRACKER;
  5819. this.deoptimizedFields = UNKNOWN_DEOPTIMIZED_FIELD;
  5820. this.argumentsToBeDeoptimized = UNKNOWN_DEOPTIMIZED_ENTITY;
  5821. }
  5822. }
  5823. getReturnExpressionWhenCalledAtPath(path) {
  5824. // We deoptimize everything that is called as that will trivially deoptimize
  5825. // the corresponding return expressions as well and avoid badly performing
  5826. // and complicated alternatives
  5827. if (path.length === 0) {
  5828. this.deoptimizePath(UNKNOWN_PATH);
  5829. }
  5830. else if (!this.deoptimizedFields.has(path[0])) {
  5831. this.deoptimizePath([path[0]]);
  5832. }
  5833. return UNKNOWN_RETURN_EXPRESSION;
  5834. }
  5835. includeArgumentPaths(entity, context) {
  5836. this.includedPathTracker.includeAllPaths(entity, context, this.initPath);
  5837. }
  5838. }
  5839. class ThisVariable extends ParameterVariable {
  5840. constructor(context) {
  5841. super('this', null, EMPTY_PATH, context);
  5842. }
  5843. hasEffectsOnInteractionAtPath(path, interaction, context) {
  5844. return (context.replacedVariableInits.get(this) || UNKNOWN_EXPRESSION).hasEffectsOnInteractionAtPath(path, interaction, context);
  5845. }
  5846. }
  5847. class CatchBodyScope extends ChildScope {
  5848. constructor(parent) {
  5849. super(parent, parent.context);
  5850. this.parent = parent;
  5851. }
  5852. addDeclaration(identifier, context, init, destructuredInitPath, kind) {
  5853. if (kind === 'var') {
  5854. const name = identifier.name;
  5855. const existingVariable = this.hoistedVariables?.get(name) || this.variables.get(name);
  5856. if (existingVariable) {
  5857. const existingKind = existingVariable.kind;
  5858. if (existingKind === 'parameter' &&
  5859. // If this is a destructured parameter, it is forbidden to redeclare
  5860. existingVariable.declarations[0].parent.type === CatchClause$1) {
  5861. // If this is a var with the same name as the catch scope parameter,
  5862. // the assignment actually goes to the parameter and the var is
  5863. // hoisted without assignment. Locally, it is shadowed by the
  5864. // parameter
  5865. const declaredVariable = this.parent.parent.addDeclaration(identifier, context, UNDEFINED_EXPRESSION, destructuredInitPath, kind);
  5866. // To avoid the need to rewrite the declaration, we link the variable
  5867. // names. If we ever implement a logic that splits initialization and
  5868. // assignment for hoisted vars, the "renderLikeHoisted" logic can be
  5869. // removed again.
  5870. // We do not need to check whether there already is a linked
  5871. // variable because then declaredVariable would be that linked
  5872. // variable.
  5873. existingVariable.renderLikeHoisted(declaredVariable);
  5874. this.addHoistedVariable(name, declaredVariable);
  5875. return declaredVariable;
  5876. }
  5877. if (existingKind === 'var') {
  5878. existingVariable.addDeclaration(identifier, init);
  5879. return existingVariable;
  5880. }
  5881. return context.error(logRedeclarationError(name), identifier.start);
  5882. }
  5883. // We only add parameters to parameter scopes
  5884. const declaredVariable = this.parent.parent.addDeclaration(identifier, context, init, destructuredInitPath, kind);
  5885. // Necessary to make sure the init is deoptimized for conditional declarations.
  5886. // We cannot call deoptimizePath here.
  5887. declaredVariable.markInitializersForDeoptimization();
  5888. // We add the variable to this and all parent scopes to reliably detect conflicts
  5889. this.addHoistedVariable(name, declaredVariable);
  5890. return declaredVariable;
  5891. }
  5892. return super.addDeclaration(identifier, context, init, destructuredInitPath, kind);
  5893. }
  5894. }
  5895. class FunctionBodyScope extends ChildScope {
  5896. constructor(parent) {
  5897. super(parent, parent.context);
  5898. }
  5899. // There is stuff that is only allowed in function scopes, i.e. functions can
  5900. // be redeclared, functions and var can redeclare each other
  5901. addDeclaration(identifier, context, init, destructuredInitPath, kind) {
  5902. const name = identifier.name;
  5903. const existingVariable = this.hoistedVariables?.get(name) || this.variables.get(name);
  5904. if (existingVariable) {
  5905. const existingKind = existingVariable.kind;
  5906. if ((kind === 'var' || kind === 'function') &&
  5907. (existingKind === 'var' || existingKind === 'function' || existingKind === 'parameter')) {
  5908. existingVariable.addDeclaration(identifier, init);
  5909. return existingVariable;
  5910. }
  5911. context.error(logRedeclarationError(name), identifier.start);
  5912. }
  5913. const newVariable = new LocalVariable(identifier.name, identifier, init, destructuredInitPath, context, kind);
  5914. this.variables.set(name, newVariable);
  5915. return newVariable;
  5916. }
  5917. }
  5918. class ParameterScope extends ChildScope {
  5919. constructor(parent, isCatchScope) {
  5920. super(parent, parent.context);
  5921. this.hasRest = false;
  5922. this.parameters = [];
  5923. this.bodyScope = isCatchScope ? new CatchBodyScope(this) : new FunctionBodyScope(this);
  5924. }
  5925. /**
  5926. * Adds a parameter to this scope. Parameters must be added in the correct
  5927. * order, i.e. from left to right.
  5928. */
  5929. addParameterDeclaration(identifier, argumentPath) {
  5930. const { name, start } = identifier;
  5931. const existingParameter = this.variables.get(name);
  5932. if (existingParameter) {
  5933. return this.context.error(logDuplicateArgumentNameError(name), start);
  5934. }
  5935. const variable = new ParameterVariable(name, identifier, argumentPath, this.context);
  5936. this.variables.set(name, variable);
  5937. // We also add it to the body scope to detect name conflicts with local
  5938. // variables. We still need the intermediate scope, though, as parameter
  5939. // defaults are NOT taken from the body scope but from the parameters or
  5940. // outside scope.
  5941. this.bodyScope.addHoistedVariable(name, variable);
  5942. return variable;
  5943. }
  5944. addParameterVariables(parameters, hasRest) {
  5945. this.parameters = parameters;
  5946. for (const parameterList of parameters) {
  5947. for (const parameter of parameterList) {
  5948. parameter.alwaysRendered = true;
  5949. }
  5950. }
  5951. this.hasRest = hasRest;
  5952. }
  5953. includeCallArguments({ args }, context) {
  5954. let calledFromTryStatement = false;
  5955. let argumentIncluded = false;
  5956. const restParameter = this.hasRest && this.parameters[this.parameters.length - 1];
  5957. let lastExplicitlyIncludedIndex = args.length - 1;
  5958. // If there is a SpreadElement, we need to include all arguments after it
  5959. // because we no longer know which argument corresponds to which parameter.
  5960. for (let argumentIndex = 1; argumentIndex < args.length; argumentIndex++) {
  5961. const argument = args[argumentIndex];
  5962. if (argument instanceof SpreadElement && !argumentIncluded) {
  5963. argumentIncluded = true;
  5964. lastExplicitlyIncludedIndex = argumentIndex - 1;
  5965. }
  5966. if (argumentIncluded) {
  5967. argument.includePath(UNKNOWN_PATH, context);
  5968. argument.include(context, false);
  5969. }
  5970. }
  5971. // Now we go backwards either starting from the last argument or before the
  5972. // first SpreadElement to ensure all arguments before are included as needed
  5973. for (let index = lastExplicitlyIncludedIndex; index >= 1; index--) {
  5974. const parameterVariables = this.parameters[index - 1] || restParameter;
  5975. const argument = args[index];
  5976. if (parameterVariables) {
  5977. calledFromTryStatement = false;
  5978. if (parameterVariables.length === 0) {
  5979. // handle empty destructuring to avoid destructuring undefined
  5980. argumentIncluded = true;
  5981. }
  5982. else {
  5983. for (const parameterVariable of parameterVariables) {
  5984. if (parameterVariable.calledFromTryStatement) {
  5985. calledFromTryStatement = true;
  5986. }
  5987. if (parameterVariable.included) {
  5988. argumentIncluded = true;
  5989. if (calledFromTryStatement) {
  5990. argument.include(context, true);
  5991. }
  5992. else {
  5993. parameterVariable.includeArgumentPaths(argument, context);
  5994. argument.include(context, false);
  5995. }
  5996. }
  5997. }
  5998. }
  5999. }
  6000. if (argumentIncluded || argument.shouldBeIncluded(context)) {
  6001. argumentIncluded = true;
  6002. argument.include(context, calledFromTryStatement);
  6003. }
  6004. }
  6005. }
  6006. }
  6007. class ReturnValueScope extends ParameterScope {
  6008. constructor() {
  6009. super(...arguments);
  6010. this.returnExpression = null;
  6011. this.returnExpressions = [];
  6012. }
  6013. addReturnExpression(expression) {
  6014. this.returnExpressions.push(expression);
  6015. }
  6016. deoptimizeArgumentsOnCall({ args }) {
  6017. const { parameters } = this;
  6018. let position = 0;
  6019. for (; position < args.length - 1; position++) {
  6020. // Only the "this" argument arg[0] can be null
  6021. const argument = args[position + 1];
  6022. if (argument instanceof SpreadElement) {
  6023. // This deoptimizes the current and remaining parameters and arguments
  6024. for (; position < parameters.length; position++) {
  6025. args[position + 1]?.deoptimizePath(UNKNOWN_PATH);
  6026. for (const variable of parameters[position]) {
  6027. variable.markReassigned();
  6028. }
  6029. }
  6030. break;
  6031. }
  6032. if (this.hasRest && position >= parameters.length - 1) {
  6033. argument.deoptimizePath(UNKNOWN_PATH);
  6034. }
  6035. else {
  6036. const variables = parameters[position];
  6037. if (variables) {
  6038. for (const variable of variables) {
  6039. variable.addArgumentForDeoptimization(argument);
  6040. }
  6041. }
  6042. this.addArgumentToBeDeoptimized(argument);
  6043. }
  6044. }
  6045. const nonRestParameterLength = this.hasRest ? parameters.length - 1 : parameters.length;
  6046. for (; position < nonRestParameterLength; position++) {
  6047. for (const variable of parameters[position]) {
  6048. variable.addArgumentForDeoptimization(UNDEFINED_EXPRESSION);
  6049. }
  6050. }
  6051. }
  6052. getReturnExpression() {
  6053. if (this.returnExpression === null)
  6054. this.updateReturnExpression();
  6055. return this.returnExpression;
  6056. }
  6057. deoptimizeAllParameters() {
  6058. for (const parameter of this.parameters) {
  6059. for (const variable of parameter) {
  6060. variable.deoptimizePath(UNKNOWN_PATH);
  6061. variable.markReassigned();
  6062. }
  6063. }
  6064. }
  6065. reassignAllParameters() {
  6066. for (const parameter of this.parameters) {
  6067. for (const variable of parameter) {
  6068. variable.markReassigned();
  6069. }
  6070. }
  6071. }
  6072. addArgumentToBeDeoptimized(_argument) { }
  6073. updateReturnExpression() {
  6074. if (this.returnExpressions.length === 1) {
  6075. this.returnExpression = this.returnExpressions[0];
  6076. }
  6077. else {
  6078. this.returnExpression = UNKNOWN_EXPRESSION;
  6079. for (const expression of this.returnExpressions) {
  6080. expression.deoptimizePath(UNKNOWN_PATH);
  6081. }
  6082. }
  6083. }
  6084. }
  6085. class FunctionScope extends ReturnValueScope {
  6086. constructor(parent, functionNode) {
  6087. super(parent, false);
  6088. this.functionNode = functionNode;
  6089. const { context } = parent;
  6090. this.variables.set('arguments', (this.argumentsVariable = new ArgumentsVariable(context)));
  6091. this.variables.set('this', (this.thisVariable = new ThisVariable(context)));
  6092. }
  6093. findLexicalBoundary() {
  6094. return this;
  6095. }
  6096. includeCallArguments(interaction, context) {
  6097. super.includeCallArguments(interaction, context);
  6098. if (this.argumentsVariable.included) {
  6099. const { args } = interaction;
  6100. for (let argumentIndex = 1; argumentIndex < args.length; argumentIndex++) {
  6101. const argument = args[argumentIndex];
  6102. if (argument) {
  6103. argument.includePath(UNKNOWN_PATH, context);
  6104. argument.include(context, false);
  6105. }
  6106. }
  6107. }
  6108. }
  6109. addArgumentToBeDeoptimized(argument) {
  6110. this.argumentsVariable.addArgumentToBeDeoptimized(argument);
  6111. }
  6112. }
  6113. class ExpressionStatement extends NodeBase {
  6114. initialise() {
  6115. super.initialise();
  6116. if (this.directive &&
  6117. this.directive !== 'use strict' &&
  6118. this.parent.type === Program$1) {
  6119. this.scope.context.log(LOGLEVEL_WARN,
  6120. // This is necessary, because either way (deleting or not) can lead to errors.
  6121. logModuleLevelDirective(this.directive, this.scope.context.module.id), this.start);
  6122. }
  6123. }
  6124. removeAnnotations(code) {
  6125. this.expression.removeAnnotations(code);
  6126. }
  6127. render(code, options) {
  6128. super.render(code, options);
  6129. if (code.original[this.end - 1] !== ';') {
  6130. code.appendLeft(this.end, ';');
  6131. }
  6132. }
  6133. shouldBeIncluded(context) {
  6134. if (this.directive && this.directive !== 'use strict')
  6135. return this.parent.type !== Program$1;
  6136. return super.shouldBeIncluded(context);
  6137. }
  6138. }
  6139. ExpressionStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  6140. ExpressionStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  6141. class BlockStatement extends NodeBase {
  6142. get deoptimizeBody() {
  6143. return isFlagSet(this.flags, 32768 /* Flag.deoptimizeBody */);
  6144. }
  6145. set deoptimizeBody(value) {
  6146. this.flags = setFlag(this.flags, 32768 /* Flag.deoptimizeBody */, value);
  6147. }
  6148. get directlyIncluded() {
  6149. return isFlagSet(this.flags, 16384 /* Flag.directlyIncluded */);
  6150. }
  6151. set directlyIncluded(value) {
  6152. this.flags = setFlag(this.flags, 16384 /* Flag.directlyIncluded */, value);
  6153. }
  6154. addImplicitReturnExpressionToScope() {
  6155. const lastStatement = this.body[this.body.length - 1];
  6156. if (!lastStatement || lastStatement.type !== ReturnStatement$1) {
  6157. this.scope.addReturnExpression(UNKNOWN_EXPRESSION);
  6158. }
  6159. }
  6160. createScope(parentScope) {
  6161. this.scope = this.parent.preventChildBlockScope
  6162. ? parentScope
  6163. : new BlockScope(parentScope);
  6164. }
  6165. hasEffects(context) {
  6166. if (this.deoptimizeBody)
  6167. return true;
  6168. for (const node of this.body) {
  6169. if (context.brokenFlow)
  6170. break;
  6171. if (node.hasEffects(context))
  6172. return true;
  6173. }
  6174. return false;
  6175. }
  6176. include(context, includeChildrenRecursively) {
  6177. if (!(this.deoptimizeBody && this.directlyIncluded)) {
  6178. this.included = true;
  6179. this.directlyIncluded = true;
  6180. if (this.deoptimizeBody)
  6181. includeChildrenRecursively = true;
  6182. for (const node of this.body) {
  6183. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  6184. node.include(context, includeChildrenRecursively);
  6185. }
  6186. }
  6187. }
  6188. initialise() {
  6189. super.initialise();
  6190. this.scope.context.magicString.addSourcemapLocation(this.end - 1);
  6191. const firstBodyStatement = this.body[0];
  6192. this.deoptimizeBody =
  6193. firstBodyStatement instanceof ExpressionStatement &&
  6194. firstBodyStatement.directive === 'use asm';
  6195. }
  6196. render(code, options) {
  6197. if (this.body.length > 0) {
  6198. renderStatementList(this.body, code, this.start + 1, this.end - 1, options);
  6199. }
  6200. else {
  6201. super.render(code, options);
  6202. }
  6203. }
  6204. }
  6205. BlockStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  6206. BlockStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  6207. class RestElement extends NodeBase {
  6208. constructor() {
  6209. super(...arguments);
  6210. this.declarationInit = null;
  6211. }
  6212. addExportedVariables(variables, exportNamesByVariable) {
  6213. this.argument.addExportedVariables(variables, exportNamesByVariable);
  6214. }
  6215. declare(kind, destructuredInitPath, init) {
  6216. this.declarationInit = init;
  6217. return this.argument.declare(kind, getIncludedPatternPath$1(destructuredInitPath), init);
  6218. }
  6219. deoptimizeAssignment(destructuredInitPath, init) {
  6220. this.argument.deoptimizeAssignment(getIncludedPatternPath$1(destructuredInitPath), init);
  6221. }
  6222. deoptimizePath(path) {
  6223. if (path.length === 0) {
  6224. this.argument.deoptimizePath(EMPTY_PATH);
  6225. }
  6226. }
  6227. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6228. return (path.length > 0 ||
  6229. this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context));
  6230. }
  6231. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  6232. return this.argument.hasEffectsWhenDestructuring(context, getIncludedPatternPath$1(destructuredInitPath), init);
  6233. }
  6234. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  6235. const included = this.argument.includeDestructuredIfNecessary(context, getIncludedPatternPath$1(destructuredInitPath), init);
  6236. if (!this.included && included) {
  6237. this.includeNode(context);
  6238. }
  6239. return this.included;
  6240. }
  6241. include(context, includeChildrenRecursively) {
  6242. if (!this.included)
  6243. this.includeNode(context);
  6244. // This should just include the identifier, its properties should be
  6245. // included where the variable is used.
  6246. this.argument.include(context, includeChildrenRecursively);
  6247. }
  6248. markDeclarationReached() {
  6249. this.argument.markDeclarationReached();
  6250. }
  6251. applyDeoptimizations() {
  6252. this.deoptimized = true;
  6253. if (this.declarationInit !== null) {
  6254. this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
  6255. this.scope.context.requestTreeshakingPass();
  6256. }
  6257. }
  6258. }
  6259. RestElement.prototype.includeNode = onlyIncludeSelf;
  6260. const getIncludedPatternPath$1 = (destructuredInitPath) => destructuredInitPath.at(-1) === UnknownKey
  6261. ? destructuredInitPath
  6262. : [...destructuredInitPath, UnknownKey];
  6263. class FunctionBase extends NodeBase {
  6264. constructor() {
  6265. super(...arguments);
  6266. this.parameterVariableValuesDeoptimized = false;
  6267. this.includeCallArguments = this.scope.includeCallArguments.bind(this.scope);
  6268. }
  6269. get async() {
  6270. return isFlagSet(this.flags, 256 /* Flag.async */);
  6271. }
  6272. set async(value) {
  6273. this.flags = setFlag(this.flags, 256 /* Flag.async */, value);
  6274. }
  6275. get deoptimizedReturn() {
  6276. return isFlagSet(this.flags, 512 /* Flag.deoptimizedReturn */);
  6277. }
  6278. set deoptimizedReturn(value) {
  6279. this.flags = setFlag(this.flags, 512 /* Flag.deoptimizedReturn */, value);
  6280. }
  6281. get generator() {
  6282. return isFlagSet(this.flags, 4194304 /* Flag.generator */);
  6283. }
  6284. set generator(value) {
  6285. this.flags = setFlag(this.flags, 4194304 /* Flag.generator */, value);
  6286. }
  6287. get hasCachedEffects() {
  6288. return isFlagSet(this.flags, 67108864 /* Flag.hasEffects */);
  6289. }
  6290. set hasCachedEffects(value) {
  6291. this.flags = setFlag(this.flags, 67108864 /* Flag.hasEffects */, value);
  6292. }
  6293. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  6294. if (interaction.type === INTERACTION_CALLED && path.length === 0) {
  6295. this.scope.deoptimizeArgumentsOnCall(interaction);
  6296. }
  6297. else {
  6298. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  6299. }
  6300. }
  6301. deoptimizePath(path) {
  6302. this.getObjectEntity().deoptimizePath(path);
  6303. if (path.length === 1 && path[0] === UnknownKey) {
  6304. // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
  6305. // which means the return expression and parameters need to be reassigned
  6306. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  6307. this.scope.deoptimizeAllParameters();
  6308. }
  6309. }
  6310. getLiteralValueAtPath(path, recursionTracker, origin) {
  6311. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  6312. }
  6313. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  6314. if (path.length > 0) {
  6315. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  6316. }
  6317. if (this.async) {
  6318. if (!this.deoptimizedReturn) {
  6319. this.deoptimizedReturn = true;
  6320. this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
  6321. this.scope.context.requestTreeshakingPass();
  6322. }
  6323. return UNKNOWN_RETURN_EXPRESSION;
  6324. }
  6325. return [this.scope.getReturnExpression(), false];
  6326. }
  6327. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6328. if (path.length > 0 || interaction.type !== INTERACTION_CALLED) {
  6329. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  6330. }
  6331. if (this.hasCachedEffects) {
  6332. return true;
  6333. }
  6334. if (this.async) {
  6335. const { propertyReadSideEffects } = this.scope.context.options
  6336. .treeshake;
  6337. const returnExpression = this.scope.getReturnExpression();
  6338. if (returnExpression.hasEffectsOnInteractionAtPath(['then'], NODE_INTERACTION_UNKNOWN_CALL, context) ||
  6339. (propertyReadSideEffects &&
  6340. (propertyReadSideEffects === 'always' ||
  6341. returnExpression.hasEffectsOnInteractionAtPath(['then'], NODE_INTERACTION_UNKNOWN_ACCESS, context)))) {
  6342. this.hasCachedEffects = true;
  6343. return true;
  6344. }
  6345. }
  6346. const { propertyReadSideEffects } = this.scope.context.options
  6347. .treeshake;
  6348. for (let index = 0; index < this.params.length; index++) {
  6349. const parameter = this.params[index];
  6350. if (parameter.hasEffects(context) ||
  6351. (propertyReadSideEffects &&
  6352. parameter.hasEffectsWhenDestructuring(context, EMPTY_PATH, interaction.args[index + 1] || UNDEFINED_EXPRESSION))) {
  6353. this.hasCachedEffects = true;
  6354. return true;
  6355. }
  6356. }
  6357. return false;
  6358. }
  6359. /**
  6360. * If the function (expression or declaration) is only used as function calls
  6361. */
  6362. onlyFunctionCallUsed() {
  6363. let variable = null;
  6364. if (this.parent.type === VariableDeclarator$1) {
  6365. variable = this.parent.id.variable ?? null;
  6366. }
  6367. if (this.parent.type === ExportDefaultDeclaration$1) {
  6368. variable = this.parent.variable;
  6369. }
  6370. return variable?.getOnlyFunctionCallUsed() ?? false;
  6371. }
  6372. include(context, includeChildrenRecursively) {
  6373. if (!this.included)
  6374. this.includeNode(context);
  6375. if (!(this.parameterVariableValuesDeoptimized || this.onlyFunctionCallUsed())) {
  6376. this.parameterVariableValuesDeoptimized = true;
  6377. this.scope.reassignAllParameters();
  6378. }
  6379. const { brokenFlow } = context;
  6380. context.brokenFlow = false;
  6381. this.body.include(context, includeChildrenRecursively);
  6382. context.brokenFlow = brokenFlow;
  6383. }
  6384. initialise() {
  6385. super.initialise();
  6386. if (this.body instanceof BlockStatement) {
  6387. this.body.addImplicitReturnExpressionToScope();
  6388. }
  6389. else {
  6390. this.scope.addReturnExpression(this.body);
  6391. }
  6392. if (this.annotations &&
  6393. this.scope.context.options.treeshake.annotations) {
  6394. this.annotationNoSideEffects = this.annotations.some(comment => comment.type === 'noSideEffects');
  6395. }
  6396. }
  6397. parseNode(esTreeNode) {
  6398. const { body, params } = esTreeNode;
  6399. const { scope } = this;
  6400. const { bodyScope, context } = scope;
  6401. // We need to ensure that parameters are declared before the body is parsed
  6402. // so that the scope already knows all parameters and can detect conflicts
  6403. // when parsing the body.
  6404. const parameters = (this.params = params.map((parameter) => new (context.getNodeConstructor(parameter.type))(this, scope).parseNode(parameter)));
  6405. scope.addParameterVariables(parameters.map(parameter => parameter.declare('parameter', EMPTY_PATH, UNKNOWN_EXPRESSION)), parameters[parameters.length - 1] instanceof RestElement);
  6406. this.body = new (context.getNodeConstructor(body.type))(this, bodyScope).parseNode(body);
  6407. return super.parseNode(esTreeNode);
  6408. }
  6409. }
  6410. FunctionBase.prototype.preventChildBlockScope = true;
  6411. FunctionBase.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  6412. FunctionBase.prototype.applyDeoptimizations = doNotDeoptimize;
  6413. class FunctionNode extends FunctionBase {
  6414. constructor() {
  6415. super(...arguments);
  6416. this.objectEntity = null;
  6417. }
  6418. createScope(parentScope) {
  6419. this.scope = new FunctionScope(parentScope, this);
  6420. this.constructedEntity = new ObjectEntity(new Map(), OBJECT_PROTOTYPE);
  6421. // This makes sure that all deoptimizations of "this" are applied to the
  6422. // constructed entity.
  6423. this.scope.thisVariable.addArgumentForDeoptimization(this.constructedEntity);
  6424. }
  6425. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  6426. super.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  6427. if (interaction.type === INTERACTION_CALLED && path.length === 0 && interaction.args[0]) {
  6428. // args[0] is the "this" argument
  6429. this.scope.thisVariable.addArgumentForDeoptimization(interaction.args[0]);
  6430. }
  6431. }
  6432. hasEffects(context) {
  6433. if (this.annotationNoSideEffects) {
  6434. return false;
  6435. }
  6436. return !!this.id?.hasEffects(context);
  6437. }
  6438. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6439. if (this.annotationNoSideEffects &&
  6440. path.length === 0 &&
  6441. interaction.type === INTERACTION_CALLED) {
  6442. return false;
  6443. }
  6444. if (super.hasEffectsOnInteractionAtPath(path, interaction, context)) {
  6445. return true;
  6446. }
  6447. if (path.length === 0 && interaction.type === INTERACTION_CALLED) {
  6448. const thisInit = context.replacedVariableInits.get(this.scope.thisVariable);
  6449. context.replacedVariableInits.set(this.scope.thisVariable, interaction.withNew ? this.constructedEntity : UNKNOWN_EXPRESSION);
  6450. const { brokenFlow, ignore, replacedVariableInits } = context;
  6451. context.ignore = {
  6452. breaks: false,
  6453. continues: false,
  6454. labels: new Set(),
  6455. returnYield: true,
  6456. this: interaction.withNew
  6457. };
  6458. if (this.body.hasEffects(context)) {
  6459. this.hasCachedEffects = true;
  6460. return true;
  6461. }
  6462. context.brokenFlow = brokenFlow;
  6463. if (thisInit) {
  6464. replacedVariableInits.set(this.scope.thisVariable, thisInit);
  6465. }
  6466. else {
  6467. replacedVariableInits.delete(this.scope.thisVariable);
  6468. }
  6469. context.ignore = ignore;
  6470. }
  6471. return false;
  6472. }
  6473. include(context, includeChildrenRecursively) {
  6474. super.include(context, includeChildrenRecursively);
  6475. this.id?.include(context, includeChildrenRecursively);
  6476. const hasArguments = this.scope.argumentsVariable.included;
  6477. for (const parameter of this.params) {
  6478. if (!(parameter instanceof Identifier) || hasArguments) {
  6479. parameter.include(context, includeChildrenRecursively);
  6480. }
  6481. }
  6482. }
  6483. includeNode(context) {
  6484. this.included = true;
  6485. const hasArguments = this.scope.argumentsVariable.included;
  6486. for (const parameter of this.params) {
  6487. if (!(parameter instanceof Identifier) || hasArguments) {
  6488. parameter.includePath(UNKNOWN_PATH, context);
  6489. }
  6490. }
  6491. }
  6492. initialise() {
  6493. super.initialise();
  6494. this.id?.declare('function', EMPTY_PATH, this);
  6495. }
  6496. getObjectEntity() {
  6497. if (this.objectEntity !== null) {
  6498. return this.objectEntity;
  6499. }
  6500. return (this.objectEntity = new ObjectEntity([
  6501. {
  6502. key: 'prototype',
  6503. kind: 'init',
  6504. property: new ObjectEntity([], OBJECT_PROTOTYPE)
  6505. }
  6506. ], OBJECT_PROTOTYPE));
  6507. }
  6508. }
  6509. class FunctionDeclaration extends FunctionNode {
  6510. initialise() {
  6511. super.initialise();
  6512. if (this.id !== null) {
  6513. this.id.variable.isId = true;
  6514. }
  6515. }
  6516. onlyFunctionCallUsed() {
  6517. // call super.onlyFunctionCallUsed for export default anonymous function
  6518. return this.id?.variable.getOnlyFunctionCallUsed() ?? super.onlyFunctionCallUsed();
  6519. }
  6520. parseNode(esTreeNode) {
  6521. if (esTreeNode.id !== null) {
  6522. this.id = new Identifier(this, this.scope.parent).parseNode(esTreeNode.id);
  6523. }
  6524. return super.parseNode(esTreeNode);
  6525. }
  6526. }
  6527. // The header ends at the first non-white-space after "default"
  6528. function getDeclarationStart(code, start) {
  6529. return findNonWhiteSpace(code, findFirstOccurrenceOutsideComment(code, 'default', start) + 7);
  6530. }
  6531. function getFunctionIdInsertPosition(code, start) {
  6532. const declarationEnd = findFirstOccurrenceOutsideComment(code, 'function', start) + 'function'.length;
  6533. code = code.slice(declarationEnd, findFirstOccurrenceOutsideComment(code, '(', declarationEnd));
  6534. const generatorStarPos = findFirstOccurrenceOutsideComment(code, '*');
  6535. if (generatorStarPos === -1) {
  6536. return declarationEnd;
  6537. }
  6538. return declarationEnd + generatorStarPos + 1;
  6539. }
  6540. class ExportDefaultDeclaration extends NodeBase {
  6541. bind() {
  6542. super.bind();
  6543. const name = this.declarationName || this.scope.context.getModuleName();
  6544. // Check if there's already a variable with the same name in the scope. This
  6545. // can cause inconsistencies when using the cache.
  6546. this.variable.name = this.scope.variables.get(name) ? `${name}_default` : name;
  6547. }
  6548. include(context, includeChildrenRecursively) {
  6549. this.included = true;
  6550. this.declaration.include(context, includeChildrenRecursively);
  6551. if (includeChildrenRecursively) {
  6552. this.scope.context.includeVariableInModule(this.variable, UNKNOWN_PATH, context);
  6553. }
  6554. }
  6555. includePath(path, context) {
  6556. this.included = true;
  6557. this.declaration.includePath(path, context);
  6558. }
  6559. initialise() {
  6560. super.initialise();
  6561. const declaration = this.declaration;
  6562. this.declarationName =
  6563. (declaration.id && declaration.id.name) || this.declaration.name;
  6564. this.variable = this.scope.addExportDefaultDeclaration(this, this.scope.context);
  6565. this.scope.context.addExport(this);
  6566. }
  6567. removeAnnotations(code) {
  6568. this.declaration.removeAnnotations(code);
  6569. }
  6570. render(code, options, nodeRenderOptions) {
  6571. const { start, end } = nodeRenderOptions;
  6572. const declarationStart = getDeclarationStart(code.original, this.start);
  6573. if (this.declaration instanceof FunctionDeclaration) {
  6574. this.renderNamedDeclaration(code, declarationStart, this.declaration.id === null
  6575. ? getFunctionIdInsertPosition(code.original, declarationStart)
  6576. : null, options);
  6577. }
  6578. else if (this.declaration instanceof ClassDeclaration) {
  6579. this.renderNamedDeclaration(code, declarationStart, this.declaration.id === null
  6580. ? findFirstOccurrenceOutsideComment(code.original, 'class', start) + 'class'.length
  6581. : null, options);
  6582. }
  6583. else if (this.variable.getOriginalVariable() !== this.variable) {
  6584. // Remove altogether to prevent re-declaring the same variable
  6585. treeshakeNode(this, code, start, end);
  6586. return;
  6587. }
  6588. else if (this.variable.included) {
  6589. this.renderVariableDeclaration(code, declarationStart, options);
  6590. }
  6591. else {
  6592. code.remove(this.start, declarationStart);
  6593. this.declaration.render(code, options, {
  6594. renderedSurroundingElement: ExpressionStatement$1
  6595. });
  6596. if (code.original[this.end - 1] !== ';') {
  6597. code.appendLeft(this.end, ';');
  6598. }
  6599. return;
  6600. }
  6601. this.declaration.render(code, options);
  6602. }
  6603. renderNamedDeclaration(code, declarationStart, idInsertPosition, options) {
  6604. const { exportNamesByVariable, format, snippets: { getPropertyAccess } } = options;
  6605. const name = this.variable.getName(getPropertyAccess);
  6606. // Remove `export default`
  6607. code.remove(this.start, declarationStart);
  6608. if (idInsertPosition !== null) {
  6609. code.appendLeft(idInsertPosition, ` ${name}`);
  6610. }
  6611. if (format === 'system' &&
  6612. this.declaration instanceof ClassDeclaration &&
  6613. exportNamesByVariable.has(this.variable)) {
  6614. code.appendLeft(this.end, ` ${getSystemExportStatement([this.variable], options)};`);
  6615. }
  6616. }
  6617. renderVariableDeclaration(code, declarationStart, { format, exportNamesByVariable, snippets: { cnst, getPropertyAccess } }) {
  6618. const hasTrailingSemicolon = code.original.charCodeAt(this.end - 1) === 59; /*";"*/
  6619. const systemExportNames = format === 'system' && exportNamesByVariable.get(this.variable);
  6620. if (systemExportNames) {
  6621. code.overwrite(this.start, declarationStart, `${cnst} ${this.variable.getName(getPropertyAccess)} = exports(${JSON.stringify(systemExportNames[0])}, `);
  6622. code.appendRight(hasTrailingSemicolon ? this.end - 1 : this.end, ')' + (hasTrailingSemicolon ? '' : ';'));
  6623. }
  6624. else {
  6625. code.overwrite(this.start, declarationStart, `${cnst} ${this.variable.getName(getPropertyAccess)} = `);
  6626. if (!hasTrailingSemicolon) {
  6627. code.appendLeft(this.end, ';');
  6628. }
  6629. }
  6630. }
  6631. }
  6632. ExportDefaultDeclaration.prototype.needsBoundaries = true;
  6633. ExportDefaultDeclaration.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  6634. ExportDefaultDeclaration.prototype.applyDeoptimizations = doNotDeoptimize;
  6635. const needsEscapeRegEx = /[\n\r'\\\u2028\u2029]/;
  6636. const quoteNewlineRegEx = /([\n\r'\u2028\u2029])/g;
  6637. const backSlashRegEx = /\\/g;
  6638. function escapeId(id) {
  6639. if (!needsEscapeRegEx.test(id))
  6640. return id;
  6641. return id.replace(backSlashRegEx, '\\\\').replace(quoteNewlineRegEx, '\\$1');
  6642. }
  6643. const INTEROP_DEFAULT_VARIABLE = '_interopDefault';
  6644. const INTEROP_DEFAULT_COMPAT_VARIABLE = '_interopDefaultCompat';
  6645. const INTEROP_NAMESPACE_VARIABLE = '_interopNamespace';
  6646. const INTEROP_NAMESPACE_COMPAT_VARIABLE = '_interopNamespaceCompat';
  6647. const INTEROP_NAMESPACE_DEFAULT_VARIABLE = '_interopNamespaceDefault';
  6648. const INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE = '_interopNamespaceDefaultOnly';
  6649. const MERGE_NAMESPACES_VARIABLE = '_mergeNamespaces';
  6650. const DOCUMENT_CURRENT_SCRIPT = '_documentCurrentScript';
  6651. const defaultInteropHelpersByInteropType = {
  6652. auto: INTEROP_DEFAULT_VARIABLE,
  6653. compat: INTEROP_DEFAULT_COMPAT_VARIABLE,
  6654. default: null,
  6655. defaultOnly: null,
  6656. esModule: null
  6657. };
  6658. const isDefaultAProperty = (interopType, externalLiveBindings) => interopType === 'esModule' ||
  6659. (externalLiveBindings && (interopType === 'auto' || interopType === 'compat'));
  6660. const namespaceInteropHelpersByInteropType = {
  6661. auto: INTEROP_NAMESPACE_VARIABLE,
  6662. compat: INTEROP_NAMESPACE_COMPAT_VARIABLE,
  6663. default: INTEROP_NAMESPACE_DEFAULT_VARIABLE,
  6664. defaultOnly: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE,
  6665. esModule: null
  6666. };
  6667. const canDefaultBeTakenFromNamespace = (interopType, externalLiveBindings) => interopType !== 'esModule' && isDefaultAProperty(interopType, externalLiveBindings);
  6668. const getHelpersBlock = (additionalHelpers, accessedGlobals, indent, snippets, liveBindings, freeze, symbols) => {
  6669. const usedHelpers = new Set(additionalHelpers);
  6670. for (const variable of HELPER_NAMES) {
  6671. if (accessedGlobals.has(variable)) {
  6672. usedHelpers.add(variable);
  6673. }
  6674. }
  6675. return HELPER_NAMES.map(variable => usedHelpers.has(variable)
  6676. ? HELPER_GENERATORS[variable](indent, snippets, liveBindings, freeze, symbols, usedHelpers)
  6677. : '').join('');
  6678. };
  6679. const HELPER_GENERATORS = {
  6680. [DOCUMENT_CURRENT_SCRIPT](_t, { _, n }) {
  6681. return `var ${DOCUMENT_CURRENT_SCRIPT}${_}=${_}typeof document${_}!==${_}'undefined'${_}?${_}document.currentScript${_}:${_}null;${n}`;
  6682. },
  6683. [INTEROP_DEFAULT_COMPAT_VARIABLE](_t, snippets, liveBindings) {
  6684. const { _, getDirectReturnFunction, n } = snippets;
  6685. const [left, right] = getDirectReturnFunction(['e'], {
  6686. functionReturn: true,
  6687. lineBreakIndent: null,
  6688. name: INTEROP_DEFAULT_COMPAT_VARIABLE
  6689. });
  6690. return (`${left}${getIsCompatNamespace(snippets)}${_}?${_}` +
  6691. `${liveBindings ? getDefaultLiveBinding(snippets) : getDefaultStatic(snippets)}${right}${n}${n}`);
  6692. },
  6693. [INTEROP_DEFAULT_VARIABLE](_t, snippets, liveBindings) {
  6694. const { _, getDirectReturnFunction, n } = snippets;
  6695. const [left, right] = getDirectReturnFunction(['e'], {
  6696. functionReturn: true,
  6697. lineBreakIndent: null,
  6698. name: INTEROP_DEFAULT_VARIABLE
  6699. });
  6700. return (`${left}e${_}&&${_}e.__esModule${_}?${_}` +
  6701. `${liveBindings ? getDefaultLiveBinding(snippets) : getDefaultStatic(snippets)}${right}${n}${n}`);
  6702. },
  6703. [INTEROP_NAMESPACE_COMPAT_VARIABLE](t, snippets, liveBindings, freeze, symbols, usedHelpers) {
  6704. const { _, getDirectReturnFunction, n } = snippets;
  6705. if (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)) {
  6706. const [left, right] = getDirectReturnFunction(['e'], {
  6707. functionReturn: true,
  6708. lineBreakIndent: null,
  6709. name: INTEROP_NAMESPACE_COMPAT_VARIABLE
  6710. });
  6711. return `${left}${getIsCompatNamespace(snippets)}${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${right}${n}${n}`;
  6712. }
  6713. return (`function ${INTEROP_NAMESPACE_COMPAT_VARIABLE}(e)${_}{${n}` +
  6714. `${t}if${_}(${getIsCompatNamespace(snippets)})${_}return e;${n}` +
  6715. createNamespaceObject(t, t, snippets, liveBindings, freeze, symbols) +
  6716. `}${n}${n}`);
  6717. },
  6718. [INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE](_t, snippets, _liveBindings, freeze, symbols) {
  6719. const { getDirectReturnFunction, getObject, n, _ } = snippets;
  6720. const [left, right] = getDirectReturnFunction(['e'], {
  6721. functionReturn: true,
  6722. lineBreakIndent: null,
  6723. name: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE
  6724. });
  6725. return `${left}${getFrozen(freeze, getWithToStringTag(symbols, getObject([
  6726. [null, `__proto__:${_}null`],
  6727. ['default', 'e']
  6728. ], { lineBreakIndent: null }), snippets))}${right}${n}${n}`;
  6729. },
  6730. [INTEROP_NAMESPACE_DEFAULT_VARIABLE](t, snippets, liveBindings, freeze, symbols) {
  6731. const { _, n } = snippets;
  6732. return (`function ${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${_}{${n}` +
  6733. createNamespaceObject(t, t, snippets, liveBindings, freeze, symbols) +
  6734. `}${n}${n}`);
  6735. },
  6736. [INTEROP_NAMESPACE_VARIABLE](t, snippets, liveBindings, freeze, symbols, usedHelpers) {
  6737. const { _, getDirectReturnFunction, n } = snippets;
  6738. if (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)) {
  6739. const [left, right] = getDirectReturnFunction(['e'], {
  6740. functionReturn: true,
  6741. lineBreakIndent: null,
  6742. name: INTEROP_NAMESPACE_VARIABLE
  6743. });
  6744. return `${left}e${_}&&${_}e.__esModule${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${right}${n}${n}`;
  6745. }
  6746. return (`function ${INTEROP_NAMESPACE_VARIABLE}(e)${_}{${n}` +
  6747. `${t}if${_}(e${_}&&${_}e.__esModule)${_}return e;${n}` +
  6748. createNamespaceObject(t, t, snippets, liveBindings, freeze, symbols) +
  6749. `}${n}${n}`);
  6750. },
  6751. [MERGE_NAMESPACES_VARIABLE](t, snippets, liveBindings, freeze, symbols) {
  6752. const { _, cnst, n } = snippets;
  6753. const useForEach = cnst === 'var' && liveBindings;
  6754. return (`function ${MERGE_NAMESPACES_VARIABLE}(n, m)${_}{${n}` +
  6755. `${t}${loopOverNamespaces(`{${n}` +
  6756. `${t}${t}${t}if${_}(k${_}!==${_}'default'${_}&&${_}!(k in n))${_}{${n}` +
  6757. (liveBindings
  6758. ? useForEach
  6759. ? copyOwnPropertyLiveBinding
  6760. : copyPropertyLiveBinding
  6761. : copyPropertyStatic)(t, t + t + t + t, snippets) +
  6762. `${t}${t}${t}}${n}` +
  6763. `${t}${t}}`, useForEach, t, snippets)}${n}` +
  6764. `${t}return ${getFrozen(freeze, getWithToStringTag(symbols, 'n', snippets))};${n}` +
  6765. `}${n}${n}`);
  6766. }
  6767. };
  6768. const getDefaultLiveBinding = ({ _, getObject }) => `e${_}:${_}${getObject([['default', 'e']], { lineBreakIndent: null })}`;
  6769. const getDefaultStatic = ({ _, getPropertyAccess }) => `e${getPropertyAccess('default')}${_}:${_}e`;
  6770. const getIsCompatNamespace = ({ _ }) => `e${_}&&${_}typeof e${_}===${_}'object'${_}&&${_}'default'${_}in e`;
  6771. const createNamespaceObject = (t, index, snippets, liveBindings, freeze, symbols) => {
  6772. const { _, cnst, getObject, getPropertyAccess, n, s } = snippets;
  6773. const copyProperty = `{${n}` +
  6774. (liveBindings ? copyNonDefaultOwnPropertyLiveBinding : copyPropertyStatic)(t, index + t + t, snippets) +
  6775. `${index}${t}}`;
  6776. return (`${index}${cnst} n${_}=${_}Object.create(null${symbols ? `,${_}{${_}[Symbol.toStringTag]:${_}${getToStringTagValue(getObject)}${_}}` : ''});${n}` +
  6777. `${index}if${_}(e)${_}{${n}` +
  6778. `${index}${t}${loopOverKeys(copyProperty, !liveBindings, snippets)}${n}` +
  6779. `${index}}${n}` +
  6780. `${index}n${getPropertyAccess('default')}${_}=${_}e;${n}` +
  6781. `${index}return ${getFrozen(freeze, 'n')}${s}${n}`);
  6782. };
  6783. const loopOverKeys = (body, allowVariableLoopVariable, { _, cnst, getFunctionIntro, s }) => cnst !== 'var' || allowVariableLoopVariable
  6784. ? `for${_}(${cnst} k in e)${_}${body}`
  6785. : `Object.keys(e).forEach(${getFunctionIntro(['k'], {
  6786. isAsync: false,
  6787. name: null
  6788. })}${body})${s}`;
  6789. const loopOverNamespaces = (body, useForEach, t, { _, cnst, getDirectReturnFunction, getFunctionIntro, n }) => {
  6790. if (useForEach) {
  6791. const [left, right] = getDirectReturnFunction(['e'], {
  6792. functionReturn: false,
  6793. lineBreakIndent: { base: t, t },
  6794. name: null
  6795. });
  6796. return (`m.forEach(${left}` +
  6797. `e${_}&&${_}typeof e${_}!==${_}'string'${_}&&${_}!Array.isArray(e)${_}&&${_}Object.keys(e).forEach(${getFunctionIntro(['k'], {
  6798. isAsync: false,
  6799. name: null
  6800. })}${body})${right});`);
  6801. }
  6802. return (`for${_}(var i${_}=${_}0;${_}i${_}<${_}m.length;${_}i++)${_}{${n}` +
  6803. `${t}${t}${cnst} e${_}=${_}m[i];${n}` +
  6804. `${t}${t}if${_}(typeof e${_}!==${_}'string'${_}&&${_}!Array.isArray(e))${_}{${_}for${_}(${cnst} k in e)${_}${body}${_}}${n}${t}}`);
  6805. };
  6806. const copyNonDefaultOwnPropertyLiveBinding = (t, index, snippets) => {
  6807. const { _, n } = snippets;
  6808. return (`${index}if${_}(k${_}!==${_}'default')${_}{${n}` +
  6809. copyOwnPropertyLiveBinding(t, index + t, snippets) +
  6810. `${index}}${n}`);
  6811. };
  6812. const copyOwnPropertyLiveBinding = (t, index, { _, cnst, getDirectReturnFunction, n }) => {
  6813. const [left, right] = getDirectReturnFunction([], {
  6814. functionReturn: true,
  6815. lineBreakIndent: null,
  6816. name: null
  6817. });
  6818. return (`${index}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
  6819. `${index}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
  6820. `${index}${t}enumerable:${_}true,${n}` +
  6821. `${index}${t}get:${_}${left}e[k]${right}${n}` +
  6822. `${index}});${n}`);
  6823. };
  6824. const copyPropertyLiveBinding = (t, index, { _, cnst, getDirectReturnFunction, n }) => {
  6825. const [left, right] = getDirectReturnFunction([], {
  6826. functionReturn: true,
  6827. lineBreakIndent: null,
  6828. name: null
  6829. });
  6830. return (`${index}${cnst} d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
  6831. `${index}if${_}(d)${_}{${n}` +
  6832. `${index}${t}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
  6833. `${index}${t}${t}enumerable:${_}true,${n}` +
  6834. `${index}${t}${t}get:${_}${left}e[k]${right}${n}` +
  6835. `${index}${t}});${n}` +
  6836. `${index}}${n}`);
  6837. };
  6838. const copyPropertyStatic = (_t, index, { _, n }) => `${index}n[k]${_}=${_}e[k];${n}`;
  6839. const getFrozen = (freeze, fragment) => freeze ? `Object.freeze(${fragment})` : fragment;
  6840. const getWithToStringTag = (symbols, fragment, { _, getObject }) => symbols
  6841. ? `Object.defineProperty(${fragment},${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)})`
  6842. : fragment;
  6843. const HELPER_NAMES = Object.keys(HELPER_GENERATORS);
  6844. function getToStringTagValue(getObject) {
  6845. return getObject([['value', "'Module'"]], {
  6846. lineBreakIndent: null
  6847. });
  6848. }
  6849. class Literal extends NodeBase {
  6850. deoptimizeArgumentsOnInteractionAtPath() { }
  6851. getLiteralValueAtPath(path) {
  6852. if (path.length > 0 ||
  6853. // unknown literals can also be null but do not start with an "n"
  6854. (this.value === null && this.scope.context.code.charCodeAt(this.start) !== 110) ||
  6855. typeof this.value === 'bigint' ||
  6856. // to support shims for regular expressions
  6857. this.scope.context.code.charCodeAt(this.start) === 47) {
  6858. return UnknownValue;
  6859. }
  6860. return this.value;
  6861. }
  6862. getReturnExpressionWhenCalledAtPath(path) {
  6863. if (path.length !== 1)
  6864. return UNKNOWN_RETURN_EXPRESSION;
  6865. return getMemberReturnExpressionWhenCalled(this.members, path[0]);
  6866. }
  6867. hasEffectsOnInteractionAtPath(path, interaction, context) {
  6868. switch (interaction.type) {
  6869. case INTERACTION_ACCESSED: {
  6870. return path.length > (this.value === null ? 0 : 1);
  6871. }
  6872. case INTERACTION_ASSIGNED: {
  6873. return true;
  6874. }
  6875. case INTERACTION_CALLED: {
  6876. if (this.included &&
  6877. this.value instanceof RegExp &&
  6878. (this.value.global || this.value.sticky)) {
  6879. return true;
  6880. }
  6881. return (path.length !== 1 ||
  6882. hasMemberEffectWhenCalled(this.members, path[0], interaction, context));
  6883. }
  6884. }
  6885. }
  6886. initialise() {
  6887. super.initialise();
  6888. this.members = getLiteralMembersForValue(this.value);
  6889. }
  6890. parseNode(esTreeNode) {
  6891. this.value = esTreeNode.value;
  6892. this.regex = esTreeNode.regex;
  6893. return super.parseNode(esTreeNode);
  6894. }
  6895. render(code) {
  6896. if (typeof this.value === 'string') {
  6897. code.indentExclusionRanges.push([this.start + 1, this.end - 1]);
  6898. }
  6899. }
  6900. }
  6901. Literal.prototype.includeNode = onlyIncludeSelf;
  6902. function getChainElementLiteralValueAtPath(element, object, path, recursionTracker, origin) {
  6903. if ('getLiteralValueAtPathAsChainElement' in object) {
  6904. const calleeValue = object.getLiteralValueAtPathAsChainElement(EMPTY_PATH, SHARED_RECURSION_TRACKER, origin);
  6905. if (calleeValue === IS_SKIPPED_CHAIN || (element.optional && calleeValue == null)) {
  6906. return IS_SKIPPED_CHAIN;
  6907. }
  6908. }
  6909. else if (element.optional &&
  6910. object.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, origin) == null) {
  6911. return IS_SKIPPED_CHAIN;
  6912. }
  6913. return element.getLiteralValueAtPath(path, recursionTracker, origin);
  6914. }
  6915. function getResolvablePropertyKey(memberExpression) {
  6916. return memberExpression.computed
  6917. ? getResolvableComputedPropertyKey(memberExpression.property)
  6918. : memberExpression.property.name;
  6919. }
  6920. function getResolvableComputedPropertyKey(propertyKey) {
  6921. if (propertyKey instanceof Literal) {
  6922. return String(propertyKey.value);
  6923. }
  6924. return null;
  6925. }
  6926. function getPathIfNotComputed(memberExpression) {
  6927. const nextPathKey = memberExpression.propertyKey;
  6928. const object = memberExpression.object;
  6929. if (typeof nextPathKey === 'string') {
  6930. if (object instanceof Identifier) {
  6931. return [
  6932. { key: object.name, pos: object.start },
  6933. { key: nextPathKey, pos: memberExpression.property.start }
  6934. ];
  6935. }
  6936. if (object instanceof MemberExpression) {
  6937. const parentPath = getPathIfNotComputed(object);
  6938. return (parentPath && [...parentPath, { key: nextPathKey, pos: memberExpression.property.start }]);
  6939. }
  6940. }
  6941. return null;
  6942. }
  6943. function getStringFromPath(path) {
  6944. let pathString = path[0].key;
  6945. for (let index = 1; index < path.length; index++) {
  6946. pathString += '.' + path[index].key;
  6947. }
  6948. return pathString;
  6949. }
  6950. class MemberExpression extends NodeBase {
  6951. constructor() {
  6952. super(...arguments);
  6953. this.promiseHandler = null;
  6954. this.variable = null;
  6955. this.expressionsToBeDeoptimized = [];
  6956. }
  6957. get computed() {
  6958. return isFlagSet(this.flags, 1024 /* Flag.computed */);
  6959. }
  6960. set computed(value) {
  6961. this.flags = setFlag(this.flags, 1024 /* Flag.computed */, value);
  6962. }
  6963. get optional() {
  6964. return isFlagSet(this.flags, 128 /* Flag.optional */);
  6965. }
  6966. set optional(value) {
  6967. this.flags = setFlag(this.flags, 128 /* Flag.optional */, value);
  6968. }
  6969. get assignmentDeoptimized() {
  6970. return isFlagSet(this.flags, 16 /* Flag.assignmentDeoptimized */);
  6971. }
  6972. set assignmentDeoptimized(value) {
  6973. this.flags = setFlag(this.flags, 16 /* Flag.assignmentDeoptimized */, value);
  6974. }
  6975. get bound() {
  6976. return isFlagSet(this.flags, 32 /* Flag.bound */);
  6977. }
  6978. set bound(value) {
  6979. this.flags = setFlag(this.flags, 32 /* Flag.bound */, value);
  6980. }
  6981. get isUndefined() {
  6982. return isFlagSet(this.flags, 64 /* Flag.isUndefined */);
  6983. }
  6984. set isUndefined(value) {
  6985. this.flags = setFlag(this.flags, 64 /* Flag.isUndefined */, value);
  6986. }
  6987. bind() {
  6988. this.bound = true;
  6989. const path = getPathIfNotComputed(this);
  6990. const baseVariable = path && this.scope.findVariable(path[0].key);
  6991. if (baseVariable?.isNamespace) {
  6992. const resolvedVariable = resolveNamespaceVariables(baseVariable, path.slice(1), this.scope.context);
  6993. if (!resolvedVariable) {
  6994. super.bind();
  6995. }
  6996. else if (resolvedVariable === 'undefined') {
  6997. this.isUndefined = true;
  6998. }
  6999. else {
  7000. this.variable = resolvedVariable;
  7001. this.scope.addNamespaceMemberAccess(getStringFromPath(path), resolvedVariable);
  7002. }
  7003. }
  7004. else {
  7005. super.bind();
  7006. }
  7007. }
  7008. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  7009. if (this.promiseHandler) {
  7010. this.promiseHandler.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  7011. }
  7012. else if (this.variable) {
  7013. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  7014. }
  7015. else if (!this.isUndefined) {
  7016. if (path.length < MAX_PATH_DEPTH) {
  7017. this.object.deoptimizeArgumentsOnInteractionAtPath(interaction, this.propertyKey === UnknownKey ? UNKNOWN_PATH : [this.propertyKey, ...path], recursionTracker);
  7018. }
  7019. else {
  7020. deoptimizeInteraction(interaction);
  7021. }
  7022. }
  7023. }
  7024. deoptimizeAssignment(destructuredInitPath, init) {
  7025. this.deoptimizePath(EMPTY_PATH);
  7026. init.deoptimizePath([...destructuredInitPath, UnknownKey]);
  7027. }
  7028. deoptimizeCache() {
  7029. if (this.propertyKey === this.dynamicPropertyKey)
  7030. return;
  7031. const { expressionsToBeDeoptimized, object } = this;
  7032. this.expressionsToBeDeoptimized = EMPTY_ARRAY;
  7033. this.dynamicPropertyKey = this.propertyKey;
  7034. object.deoptimizePath(UNKNOWN_PATH);
  7035. if (this.included) {
  7036. object.includePath(UNKNOWN_PATH, createInclusionContext());
  7037. }
  7038. for (const expression of expressionsToBeDeoptimized) {
  7039. expression.deoptimizeCache();
  7040. }
  7041. }
  7042. deoptimizePath(path) {
  7043. if (path.length === 0)
  7044. this.disallowNamespaceReassignment();
  7045. if (this.variable) {
  7046. this.variable.deoptimizePath(path);
  7047. }
  7048. else if (!this.isUndefined) {
  7049. const { propertyKey } = this;
  7050. this.object.deoptimizePath([
  7051. propertyKey === UnknownKey ? UnknownNonAccessorKey : propertyKey,
  7052. ...(path.length < MAX_PATH_DEPTH
  7053. ? path
  7054. : [...path.slice(0, MAX_PATH_DEPTH), UnknownKey])
  7055. ]);
  7056. }
  7057. }
  7058. getLiteralValueAtPath(path, recursionTracker, origin) {
  7059. if (this.variable) {
  7060. return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
  7061. }
  7062. if (this.isUndefined) {
  7063. return undefined;
  7064. }
  7065. const propertyKey = this.getDynamicPropertyKey();
  7066. if (propertyKey !== UnknownKey && path.length < MAX_PATH_DEPTH) {
  7067. if (propertyKey !== this.propertyKey)
  7068. this.expressionsToBeDeoptimized.push(origin);
  7069. return this.object.getLiteralValueAtPath([propertyKey, ...path], recursionTracker, origin);
  7070. }
  7071. return UnknownValue;
  7072. }
  7073. getLiteralValueAtPathAsChainElement(path, recursionTracker, origin) {
  7074. if (this.variable) {
  7075. return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
  7076. }
  7077. if (this.isUndefined) {
  7078. return undefined;
  7079. }
  7080. return getChainElementLiteralValueAtPath(this, this.object, path, recursionTracker, origin);
  7081. }
  7082. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  7083. if (this.variable) {
  7084. return this.variable.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  7085. }
  7086. if (this.isUndefined) {
  7087. return [UNDEFINED_EXPRESSION, false];
  7088. }
  7089. const propertyKey = this.getDynamicPropertyKey();
  7090. if (propertyKey !== UnknownKey && path.length < MAX_PATH_DEPTH) {
  7091. if (propertyKey !== this.propertyKey)
  7092. this.expressionsToBeDeoptimized.push(origin);
  7093. return this.object.getReturnExpressionWhenCalledAtPath([propertyKey, ...path], interaction, recursionTracker, origin);
  7094. }
  7095. return UNKNOWN_RETURN_EXPRESSION;
  7096. }
  7097. hasEffects(context) {
  7098. if (!this.deoptimized)
  7099. this.applyDeoptimizations();
  7100. return (this.property.hasEffects(context) ||
  7101. this.object.hasEffects(context) ||
  7102. this.hasAccessEffect(context));
  7103. }
  7104. hasEffectsAsChainElement(context) {
  7105. if (this.variable || this.isUndefined)
  7106. return this.hasEffects(context);
  7107. const objectHasEffects = 'hasEffectsAsChainElement' in this.object
  7108. ? this.object.hasEffectsAsChainElement(context)
  7109. : this.object.hasEffects(context);
  7110. if (objectHasEffects === IS_SKIPPED_CHAIN)
  7111. return IS_SKIPPED_CHAIN;
  7112. if (this.optional &&
  7113. this.object.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) == null) {
  7114. return objectHasEffects || IS_SKIPPED_CHAIN;
  7115. }
  7116. // We only apply deoptimizations lazily once we know we are not skipping
  7117. if (!this.deoptimized)
  7118. this.applyDeoptimizations();
  7119. return objectHasEffects || this.property.hasEffects(context) || this.hasAccessEffect(context);
  7120. }
  7121. hasEffectsAsAssignmentTarget(context, checkAccess) {
  7122. if (checkAccess && !this.deoptimized)
  7123. this.applyDeoptimizations();
  7124. if (!this.assignmentDeoptimized)
  7125. this.applyAssignmentDeoptimization();
  7126. return (this.property.hasEffects(context) ||
  7127. this.object.hasEffects(context) ||
  7128. (checkAccess && this.hasAccessEffect(context)) ||
  7129. this.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.assignmentInteraction, context));
  7130. }
  7131. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7132. if (this.variable) {
  7133. return this.variable.hasEffectsOnInteractionAtPath(path, interaction, context);
  7134. }
  7135. if (this.isUndefined) {
  7136. return true;
  7137. }
  7138. if (path.length < MAX_PATH_DEPTH) {
  7139. return this.object.hasEffectsOnInteractionAtPath([this.getDynamicPropertyKey(), ...path], interaction, context);
  7140. }
  7141. return true;
  7142. }
  7143. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  7144. return (destructuredInitPath.length > 0 &&
  7145. init.hasEffectsOnInteractionAtPath(destructuredInitPath, NODE_INTERACTION_UNKNOWN_ACCESS, context));
  7146. }
  7147. include(context, includeChildrenRecursively) {
  7148. if (!this.included)
  7149. this.includeNode(context);
  7150. this.object.include(context, includeChildrenRecursively);
  7151. this.property.include(context, includeChildrenRecursively);
  7152. if (includeChildrenRecursively) {
  7153. this.variable?.includePath(UNKNOWN_PATH, context);
  7154. }
  7155. }
  7156. includeNode(context) {
  7157. this.included = true;
  7158. if (!this.deoptimized)
  7159. this.applyDeoptimizations();
  7160. if (this.variable) {
  7161. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  7162. }
  7163. else if (!this.isUndefined) {
  7164. this.object.includePath([this.propertyKey], context);
  7165. }
  7166. }
  7167. includeNodeAsAssignmentTarget(context) {
  7168. this.included = true;
  7169. if (!this.assignmentDeoptimized)
  7170. this.applyAssignmentDeoptimization();
  7171. if (this.variable) {
  7172. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  7173. }
  7174. else if (!this.isUndefined) {
  7175. this.object.includePath([this.propertyKey], context);
  7176. }
  7177. }
  7178. includePath(path, context) {
  7179. if (!this.included)
  7180. this.includeNode(context);
  7181. if (this.variable) {
  7182. this.variable?.includePath(path, context);
  7183. }
  7184. else if (!this.isUndefined) {
  7185. this.object.includePath([
  7186. this.propertyKey,
  7187. ...(path.length < MAX_PATH_DEPTH
  7188. ? path
  7189. : [...path.slice(0, MAX_PATH_DEPTH), UnknownKey])
  7190. ], context);
  7191. }
  7192. }
  7193. includeAsAssignmentTarget(context, includeChildrenRecursively, deoptimizeAccess) {
  7194. if (!this.included)
  7195. this.includeNodeAsAssignmentTarget(context);
  7196. if (deoptimizeAccess && !this.deoptimized)
  7197. this.applyDeoptimizations();
  7198. this.object.include(context, includeChildrenRecursively);
  7199. this.property.include(context, includeChildrenRecursively);
  7200. }
  7201. includeCallArguments(interaction, context) {
  7202. if (this.promiseHandler) {
  7203. this.promiseHandler.includeCallArguments(interaction, context);
  7204. }
  7205. else if (this.variable) {
  7206. this.variable.includeCallArguments(interaction, context);
  7207. }
  7208. else {
  7209. includeInteraction(interaction, context);
  7210. }
  7211. }
  7212. includeDestructuredIfNecessary() {
  7213. /* istanbul ignore next */
  7214. this.scope.context.error({
  7215. message: 'includeDestructuredIfNecessary is currently not supported for MemberExpressions'
  7216. }, this.start);
  7217. }
  7218. initialise() {
  7219. super.initialise();
  7220. this.dynamicPropertyKey = getResolvablePropertyKey(this);
  7221. this.propertyKey = this.dynamicPropertyKey === null ? UnknownKey : this.dynamicPropertyKey;
  7222. this.accessInteraction = { args: [this.object], type: INTERACTION_ACCESSED };
  7223. }
  7224. render(code, options, { renderedParentType, isCalleeOfRenderedParent, renderedSurroundingElement } = BLANK) {
  7225. if (this.variable || this.isUndefined) {
  7226. const { snippets: { getPropertyAccess } } = options;
  7227. let replacement = this.variable ? this.variable.getName(getPropertyAccess) : 'undefined';
  7228. if (renderedParentType && isCalleeOfRenderedParent)
  7229. replacement = '0, ' + replacement;
  7230. code.overwrite(this.start, this.end, replacement, {
  7231. contentOnly: true,
  7232. storeName: true
  7233. });
  7234. }
  7235. else {
  7236. if (renderedParentType && isCalleeOfRenderedParent) {
  7237. code.appendRight(this.start, '0, ');
  7238. }
  7239. this.object.render(code, options, { renderedSurroundingElement });
  7240. this.property.render(code, options);
  7241. }
  7242. }
  7243. setAssignedValue(value) {
  7244. this.assignmentInteraction = {
  7245. args: [this.object, value],
  7246. type: INTERACTION_ASSIGNED
  7247. };
  7248. }
  7249. applyDeoptimizations() {
  7250. this.deoptimized = true;
  7251. const { propertyReadSideEffects } = this.scope.context.options
  7252. .treeshake;
  7253. if (
  7254. // Namespaces are not bound and should not be deoptimized
  7255. this.bound &&
  7256. propertyReadSideEffects &&
  7257. !(this.variable || this.isUndefined || this.promiseHandler)) {
  7258. this.object.deoptimizeArgumentsOnInteractionAtPath(this.accessInteraction, [this.propertyKey], SHARED_RECURSION_TRACKER);
  7259. this.scope.context.requestTreeshakingPass();
  7260. }
  7261. if (this.variable) {
  7262. this.variable.addUsedPlace(this);
  7263. this.scope.context.requestTreeshakingPass();
  7264. }
  7265. }
  7266. applyAssignmentDeoptimization() {
  7267. this.assignmentDeoptimized = true;
  7268. const { propertyReadSideEffects } = this.scope.context.options
  7269. .treeshake;
  7270. if (
  7271. // Namespaces are not bound and should not be deoptimized
  7272. this.bound &&
  7273. propertyReadSideEffects &&
  7274. !(this.variable || this.isUndefined)) {
  7275. this.object.deoptimizeArgumentsOnInteractionAtPath(this.assignmentInteraction, [this.propertyKey], SHARED_RECURSION_TRACKER);
  7276. this.scope.context.requestTreeshakingPass();
  7277. }
  7278. }
  7279. disallowNamespaceReassignment() {
  7280. if (this.object instanceof Identifier) {
  7281. const variable = this.scope.findVariable(this.object.name);
  7282. if (variable.isNamespace) {
  7283. if (this.variable) {
  7284. this.scope.context.includeVariableInModule(this.variable, UNKNOWN_PATH, createInclusionContext());
  7285. }
  7286. this.scope.context.log(LOGLEVEL_WARN, logIllegalImportReassignment(this.object.name, this.scope.context.module.id), this.start);
  7287. }
  7288. }
  7289. }
  7290. getDynamicPropertyKey() {
  7291. if (this.dynamicPropertyKey === null) {
  7292. this.dynamicPropertyKey = this.propertyKey;
  7293. const value = this.property.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  7294. return (this.dynamicPropertyKey =
  7295. typeof value === 'symbol'
  7296. ? WELL_KNOWN_SYMBOLS.has(value)
  7297. ? value
  7298. : UnknownKey
  7299. : String(value));
  7300. }
  7301. return this.dynamicPropertyKey;
  7302. }
  7303. hasAccessEffect(context) {
  7304. const { propertyReadSideEffects } = this.scope.context.options
  7305. .treeshake;
  7306. return (!(this.variable || this.isUndefined) &&
  7307. propertyReadSideEffects &&
  7308. (propertyReadSideEffects === 'always' ||
  7309. this.object.hasEffectsOnInteractionAtPath([this.getDynamicPropertyKey()], this.accessInteraction, context)));
  7310. }
  7311. }
  7312. function resolveNamespaceVariables(baseVariable, path, astContext) {
  7313. if (path.length === 0)
  7314. return baseVariable;
  7315. if (!baseVariable.isNamespace || baseVariable instanceof ExternalVariable)
  7316. return null;
  7317. const exportName = path[0].key;
  7318. const [variable, options] = baseVariable.context.traceExport(exportName);
  7319. if (!variable) {
  7320. if (path.length === 1) {
  7321. const fileName = baseVariable.context.fileName;
  7322. astContext.log(LOGLEVEL_WARN, logMissingExport(exportName, astContext.module.id, fileName, !!options?.missingButExportExists), path[0].pos);
  7323. return 'undefined';
  7324. }
  7325. return null;
  7326. }
  7327. return resolveNamespaceVariables(variable, path.slice(1), astContext);
  7328. }
  7329. const FILE_PREFIX = 'ROLLUP_FILE_URL_';
  7330. const FILE_OBJ_PREFIX = 'ROLLUP_FILE_URL_OBJ_';
  7331. const IMPORT = 'import';
  7332. class MetaProperty extends NodeBase {
  7333. constructor() {
  7334. super(...arguments);
  7335. this.metaProperty = null;
  7336. this.preliminaryChunkId = null;
  7337. this.referenceId = null;
  7338. }
  7339. getReferencedFileName(outputPluginDriver) {
  7340. const { meta: { name }, metaProperty } = this;
  7341. if (name === IMPORT) {
  7342. if (metaProperty?.startsWith(FILE_OBJ_PREFIX)) {
  7343. return outputPluginDriver.getFileName(metaProperty.slice(FILE_OBJ_PREFIX.length));
  7344. }
  7345. else if (metaProperty?.startsWith(FILE_PREFIX)) {
  7346. return outputPluginDriver.getFileName(metaProperty.slice(FILE_PREFIX.length));
  7347. }
  7348. }
  7349. return null;
  7350. }
  7351. hasEffects() {
  7352. return false;
  7353. }
  7354. hasEffectsOnInteractionAtPath(path, { type }) {
  7355. return path.length > 1 || type !== INTERACTION_ACCESSED;
  7356. }
  7357. include() {
  7358. if (!this.included)
  7359. this.includeNode();
  7360. }
  7361. includeNode() {
  7362. this.included = true;
  7363. if (this.meta.name === IMPORT) {
  7364. this.scope.context.addImportMeta(this);
  7365. const parent = this.parent;
  7366. const metaProperty = (this.metaProperty =
  7367. parent instanceof MemberExpression && typeof parent.propertyKey === 'string'
  7368. ? parent.propertyKey
  7369. : null);
  7370. if (metaProperty?.startsWith(FILE_OBJ_PREFIX)) {
  7371. this.referenceId = metaProperty.slice(FILE_OBJ_PREFIX.length);
  7372. }
  7373. else if (metaProperty?.startsWith(FILE_PREFIX)) {
  7374. this.referenceId = metaProperty.slice(FILE_PREFIX.length);
  7375. }
  7376. }
  7377. }
  7378. render(code, renderOptions) {
  7379. const { format, pluginDriver, snippets } = renderOptions;
  7380. const { scope: { context: { module } }, meta: { name }, metaProperty, parent, preliminaryChunkId, referenceId, start, end } = this;
  7381. const { id: moduleId, info: { attributes } } = module;
  7382. if (name !== IMPORT)
  7383. return;
  7384. const chunkId = preliminaryChunkId;
  7385. if (referenceId) {
  7386. const fileName = pluginDriver.getFileName(referenceId);
  7387. const relativePath = normalize(relative(dirname(chunkId), fileName));
  7388. const isUrlObject = !!metaProperty?.startsWith(FILE_OBJ_PREFIX);
  7389. const replacement = pluginDriver.hookFirstSync('resolveFileUrl', [
  7390. { attributes, chunkId, fileName, format, moduleId, referenceId, relativePath }
  7391. ]) || relativeUrlMechanisms[format](relativePath, isUrlObject);
  7392. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  7393. return;
  7394. }
  7395. let replacement = pluginDriver.hookFirstSync('resolveImportMeta', [
  7396. metaProperty,
  7397. { attributes, chunkId, format, moduleId }
  7398. ]);
  7399. if (!replacement) {
  7400. replacement = importMetaMechanisms[format]?.(metaProperty, { chunkId, snippets });
  7401. renderOptions.accessedDocumentCurrentScript ||=
  7402. formatsMaybeAccessDocumentCurrentScript.includes(format) && replacement !== 'undefined';
  7403. }
  7404. if (typeof replacement === 'string') {
  7405. if (parent instanceof MemberExpression) {
  7406. code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
  7407. }
  7408. else {
  7409. code.overwrite(start, end, replacement, { contentOnly: true });
  7410. }
  7411. }
  7412. }
  7413. setResolution(format, accessedGlobalsByScope, preliminaryChunkId) {
  7414. this.preliminaryChunkId = preliminaryChunkId;
  7415. const accessedGlobals = (this.metaProperty?.startsWith(FILE_PREFIX) || this.metaProperty?.startsWith(FILE_OBJ_PREFIX)
  7416. ? accessedFileUrlGlobals
  7417. : accessedMetaUrlGlobals)[format];
  7418. if (accessedGlobals.length > 0) {
  7419. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  7420. }
  7421. }
  7422. }
  7423. const formatsMaybeAccessDocumentCurrentScript = ['cjs', 'iife', 'umd'];
  7424. const accessedMetaUrlGlobals = {
  7425. amd: ['document', 'module', 'URL'],
  7426. cjs: ['document', 'require', 'URL', DOCUMENT_CURRENT_SCRIPT],
  7427. es: [],
  7428. iife: ['document', 'URL', DOCUMENT_CURRENT_SCRIPT],
  7429. system: ['module'],
  7430. umd: ['document', 'require', 'URL', DOCUMENT_CURRENT_SCRIPT]
  7431. };
  7432. const accessedFileUrlGlobals = {
  7433. amd: ['document', 'require', 'URL'],
  7434. cjs: ['document', 'require', 'URL'],
  7435. es: [],
  7436. iife: ['document', 'URL'],
  7437. system: ['module', 'URL'],
  7438. umd: ['document', 'require', 'URL']
  7439. };
  7440. const getResolveUrl = (path, asObject, URL = 'URL') => `new ${URL}(${path})${asObject ? '' : '.href'}`;
  7441. const getRelativeUrlFromDocument = (relativePath, asObject, umd = false) => getResolveUrl(`'${escapeId(relativePath)}', ${umd ? `typeof document === 'undefined' ? location.href : ` : ''}document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT' && document.currentScript.src || document.baseURI`, asObject);
  7442. const getGenericImportMetaMechanism = (getUrl) => (property, { chunkId }) => {
  7443. const urlMechanism = getUrl(chunkId);
  7444. return property === null
  7445. ? `({ url: ${urlMechanism} })`
  7446. : property === 'url'
  7447. ? urlMechanism
  7448. : 'undefined';
  7449. };
  7450. const getFileUrlFromFullPath = (path, asObject) => `require('u' + 'rl').pathToFileURL(${path})${asObject ? '' : '.href'}`;
  7451. const getFileUrlFromRelativePath = (path, asObject) => getFileUrlFromFullPath(`__dirname + '/${escapeId(path)}'`, asObject);
  7452. 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)`;
  7453. const relativeUrlMechanisms = {
  7454. amd: (relativePath, asObject) => {
  7455. if (relativePath[0] !== '.')
  7456. relativePath = './' + relativePath;
  7457. return getResolveUrl(`require.toUrl('${escapeId(relativePath)}'), document.baseURI`, asObject);
  7458. },
  7459. cjs: (relativePath, asObject) => `(typeof document === 'undefined' ? ${getFileUrlFromRelativePath(relativePath, asObject)} : ${getRelativeUrlFromDocument(relativePath, asObject)})`,
  7460. es: (relativePath, asObject) => getResolveUrl(`'${escapeId(relativePath)}', import.meta.url`, asObject),
  7461. iife: (relativePath, asObject) => getRelativeUrlFromDocument(relativePath, asObject),
  7462. system: (relativePath, asObject) => getResolveUrl(`'${escapeId(relativePath)}', module.meta.url`, asObject),
  7463. umd: (relativePath, asObject) => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getFileUrlFromRelativePath(relativePath, asObject)} : ${getRelativeUrlFromDocument(relativePath, asObject, true)})`
  7464. };
  7465. const importMetaMechanisms = {
  7466. amd: getGenericImportMetaMechanism(() => getResolveUrl(`module.uri, document.baseURI`, false)),
  7467. cjs: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' ? ${getFileUrlFromFullPath('__filename', false)} : ${getUrlFromDocument(chunkId)})`),
  7468. iife: getGenericImportMetaMechanism(chunkId => getUrlFromDocument(chunkId)),
  7469. system: (property, { snippets: { getPropertyAccess } }) => property === null ? `module.meta` : `module.meta${getPropertyAccess(property)}`,
  7470. umd: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getFileUrlFromFullPath('__filename', false)} : ${getUrlFromDocument(chunkId, true)})`)
  7471. };
  7472. class UndefinedVariable extends Variable {
  7473. constructor() {
  7474. super('undefined');
  7475. }
  7476. getLiteralValueAtPath() {
  7477. return undefined;
  7478. }
  7479. }
  7480. class ExportDefaultVariable extends LocalVariable {
  7481. constructor(exportDefaultDeclaration, context) {
  7482. super('default', exportDefaultDeclaration, exportDefaultDeclaration.declaration, EMPTY_PATH, context, 'other');
  7483. this.hasId = false;
  7484. this.originalId = null;
  7485. this.originalVariable = null;
  7486. const declaration = exportDefaultDeclaration.declaration;
  7487. if ((declaration instanceof FunctionDeclaration || declaration instanceof ClassDeclaration) &&
  7488. declaration.id) {
  7489. this.hasId = true;
  7490. this.originalId = declaration.id;
  7491. }
  7492. else if (declaration instanceof Identifier) {
  7493. this.originalId = declaration;
  7494. }
  7495. }
  7496. addReference(identifier) {
  7497. if (!this.hasId) {
  7498. this.name = identifier.name;
  7499. }
  7500. }
  7501. addUsedPlace(usedPlace) {
  7502. const original = this.getOriginalVariable();
  7503. if (original === this) {
  7504. super.addUsedPlace(usedPlace);
  7505. }
  7506. else {
  7507. original.addUsedPlace(usedPlace);
  7508. }
  7509. }
  7510. forbidName(name) {
  7511. const original = this.getOriginalVariable();
  7512. if (original === this) {
  7513. super.forbidName(name);
  7514. }
  7515. else {
  7516. original.forbidName(name);
  7517. }
  7518. }
  7519. getAssignedVariableName() {
  7520. return (this.originalId && this.originalId.name) || null;
  7521. }
  7522. getBaseVariableName() {
  7523. const original = this.getOriginalVariable();
  7524. return original === this ? super.getBaseVariableName() : original.getBaseVariableName();
  7525. }
  7526. getDirectOriginalVariable() {
  7527. return this.originalId &&
  7528. (this.hasId ||
  7529. !(this.originalId.isPossibleTDZ() ||
  7530. this.originalId.variable.isReassigned ||
  7531. this.originalId.variable instanceof UndefinedVariable ||
  7532. // this avoids a circular dependency
  7533. 'syntheticNamespace' in this.originalId.variable))
  7534. ? this.originalId.variable
  7535. : null;
  7536. }
  7537. getName(getPropertyAccess) {
  7538. const original = this.getOriginalVariable();
  7539. return original === this
  7540. ? super.getName(getPropertyAccess)
  7541. : original.getName(getPropertyAccess);
  7542. }
  7543. getOriginalVariable() {
  7544. if (this.originalVariable)
  7545. return this.originalVariable;
  7546. // eslint-disable-next-line @typescript-eslint/no-this-alias
  7547. let original = this;
  7548. let currentVariable;
  7549. const checkedVariables = new Set();
  7550. do {
  7551. checkedVariables.add(original);
  7552. currentVariable = original;
  7553. original = currentVariable.getDirectOriginalVariable();
  7554. } while (original instanceof ExportDefaultVariable && !checkedVariables.has(original));
  7555. return (this.originalVariable = original || currentVariable);
  7556. }
  7557. }
  7558. class NamespaceVariable extends Variable {
  7559. constructor(context) {
  7560. super(context.getModuleName());
  7561. this.areAllMembersDeoptimized = false;
  7562. this.mergedNamespaces = [];
  7563. this.nonExplicitNamespacesIncluded = false;
  7564. this.referencedEarly = false;
  7565. this.references = [];
  7566. this.context = context;
  7567. this.module = context.module;
  7568. }
  7569. addReference(identifier) {
  7570. this.references.push(identifier);
  7571. this.name = identifier.name;
  7572. }
  7573. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  7574. if (path.length > 1 || (path.length === 1 && interaction.type === INTERACTION_CALLED)) {
  7575. const key = path[0];
  7576. if (typeof key === 'string') {
  7577. this.module
  7578. .getExportedVariablesByName()
  7579. .get(key)
  7580. ?.deoptimizeArgumentsOnInteractionAtPath(interaction, path.slice(1), recursionTracker);
  7581. }
  7582. else {
  7583. deoptimizeInteraction(interaction);
  7584. }
  7585. }
  7586. }
  7587. deoptimizePath(path) {
  7588. if (path.length > 1) {
  7589. const key = path[0];
  7590. if (typeof key === 'string') {
  7591. this.module.getExportedVariablesByName().get(key)?.deoptimizePath(path.slice(1));
  7592. }
  7593. else if (!this.areAllMembersDeoptimized) {
  7594. this.areAllMembersDeoptimized = true;
  7595. for (const variable of this.module.getExportedVariablesByName().values()) {
  7596. variable.deoptimizePath(UNKNOWN_PATH);
  7597. }
  7598. }
  7599. }
  7600. }
  7601. getLiteralValueAtPath(path) {
  7602. if (path[0] === SymbolToStringTag) {
  7603. return 'Module';
  7604. }
  7605. return UnknownValue;
  7606. }
  7607. hasEffectsOnInteractionAtPath(path, interaction, context) {
  7608. const { type } = interaction;
  7609. if (path.length === 0) {
  7610. // This can only be a call anyway
  7611. return true;
  7612. }
  7613. if (path.length === 1 && type !== INTERACTION_CALLED) {
  7614. return type === INTERACTION_ASSIGNED;
  7615. }
  7616. const key = path[0];
  7617. if (typeof key !== 'string') {
  7618. return true;
  7619. }
  7620. const memberVariable = this.module.getExportedVariablesByName().get(key);
  7621. return (!memberVariable ||
  7622. memberVariable.hasEffectsOnInteractionAtPath(path.slice(1), interaction, context));
  7623. }
  7624. includePath(path, context) {
  7625. super.includePath(path, context);
  7626. this.includeMemberPath(path, context);
  7627. }
  7628. includeMemberPath(path, context) {
  7629. if (path.length > 0) {
  7630. const [name, ...remainingPath] = path;
  7631. if (typeof name === 'string') {
  7632. const variable = this.module.getExportedVariablesByName().get(name);
  7633. if (variable) {
  7634. this.context.includeVariableInModule(variable, remainingPath, context);
  7635. }
  7636. else {
  7637. this.includeNonExplicitNamespaces();
  7638. }
  7639. }
  7640. else if (name) {
  7641. this.module.includeAllExports();
  7642. this.includeNonExplicitNamespaces();
  7643. }
  7644. }
  7645. }
  7646. prepare(accessedGlobalsByScope) {
  7647. if (this.mergedNamespaces.length > 0) {
  7648. this.module.scope.addAccessedGlobals([MERGE_NAMESPACES_VARIABLE], accessedGlobalsByScope);
  7649. }
  7650. }
  7651. renderBlock(options) {
  7652. const { exportNamesByVariable, format, freeze, indent: t, symbols, snippets: { _, cnst, getObject, getPropertyAccess, n, s } } = options;
  7653. const memberVariables = this.module.getExportedVariablesByName();
  7654. const members = [...memberVariables.entries()]
  7655. .filter(([name, variable]) => !name.startsWith('*') && variable.included)
  7656. .map(([name, variable]) => {
  7657. if (this.referencedEarly || variable.isReassigned || variable === this) {
  7658. return [
  7659. null,
  7660. `get ${stringifyObjectKeyIfNeeded(name)}${_}()${_}{${_}return ${variable.getName(getPropertyAccess)}${s}${_}}`
  7661. ];
  7662. }
  7663. return [name, variable.getName(getPropertyAccess)];
  7664. });
  7665. members.unshift([null, `__proto__:${_}null`]);
  7666. let output = getObject(members, { lineBreakIndent: { base: '', t } });
  7667. if (this.mergedNamespaces.length > 0) {
  7668. const assignmentArguments = this.mergedNamespaces.map(variable => variable.getName(getPropertyAccess));
  7669. output = `/*#__PURE__*/${MERGE_NAMESPACES_VARIABLE}(${output},${_}[${assignmentArguments.join(`,${_}`)}])`;
  7670. }
  7671. else {
  7672. // The helper to merge namespaces will also take care of freezing and toStringTag
  7673. if (symbols) {
  7674. output = `/*#__PURE__*/Object.defineProperty(${output},${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)})`;
  7675. }
  7676. if (freeze) {
  7677. output = `/*#__PURE__*/Object.freeze(${output})`;
  7678. }
  7679. }
  7680. const name = this.getName(getPropertyAccess);
  7681. output = `${cnst} ${name}${_}=${_}${output};`;
  7682. if (format === 'system' && exportNamesByVariable.has(this)) {
  7683. output += `${n}${getSystemExportStatement([this], options)};`;
  7684. }
  7685. return output;
  7686. }
  7687. renderFirst() {
  7688. return this.referencedEarly;
  7689. }
  7690. setMergedNamespaces(mergedNamespaces) {
  7691. this.mergedNamespaces = mergedNamespaces;
  7692. const moduleExecIndex = this.context.getModuleExecIndex();
  7693. for (const identifier of this.references) {
  7694. const { context } = identifier.scope;
  7695. if (context.getModuleExecIndex() <= moduleExecIndex) {
  7696. this.referencedEarly = true;
  7697. break;
  7698. }
  7699. }
  7700. }
  7701. includeNonExplicitNamespaces() {
  7702. if (!this.nonExplicitNamespacesIncluded) {
  7703. this.nonExplicitNamespacesIncluded = true;
  7704. this.setMergedNamespaces(this.module.includeAndGetAdditionalMergedNamespaces());
  7705. }
  7706. }
  7707. }
  7708. NamespaceVariable.prototype.isNamespace = true;
  7709. // This is a proxy that does not include the namespace object when a path is included
  7710. const getDynamicNamespaceVariable = (namespace) => Object.create(namespace, {
  7711. includePath: {
  7712. value(path, context) {
  7713. namespace.includeMemberPath(path, context);
  7714. }
  7715. }
  7716. });
  7717. class SyntheticNamedExportVariable extends Variable {
  7718. constructor(context, name, syntheticNamespace) {
  7719. super(name);
  7720. this.baseVariable = null;
  7721. this.context = context;
  7722. this.module = context.module;
  7723. this.syntheticNamespace = syntheticNamespace;
  7724. }
  7725. getBaseVariable() {
  7726. if (this.baseVariable)
  7727. return this.baseVariable;
  7728. let baseVariable = this.syntheticNamespace;
  7729. while (baseVariable instanceof ExportDefaultVariable ||
  7730. baseVariable instanceof SyntheticNamedExportVariable) {
  7731. if (baseVariable instanceof ExportDefaultVariable) {
  7732. const original = baseVariable.getOriginalVariable();
  7733. if (original === baseVariable)
  7734. break;
  7735. baseVariable = original;
  7736. }
  7737. if (baseVariable instanceof SyntheticNamedExportVariable) {
  7738. baseVariable = baseVariable.syntheticNamespace;
  7739. }
  7740. }
  7741. return (this.baseVariable = baseVariable);
  7742. }
  7743. getBaseVariableName() {
  7744. return this.syntheticNamespace.getBaseVariableName();
  7745. }
  7746. getName(getPropertyAccess) {
  7747. return `${this.syntheticNamespace.getName(getPropertyAccess)}${getPropertyAccess(this.name)}`;
  7748. }
  7749. includePath(path, context) {
  7750. super.includePath(path, context);
  7751. this.context.includeVariableInModule(this.syntheticNamespace, [this.name, ...path], context);
  7752. }
  7753. setRenderNames(baseName, name) {
  7754. super.setRenderNames(baseName, name);
  7755. }
  7756. }
  7757. class ExternalChunk {
  7758. constructor(module, options, inputBase) {
  7759. this.options = options;
  7760. this.inputBase = inputBase;
  7761. this.defaultVariableName = '';
  7762. this.namespaceVariableName = '';
  7763. this.variableName = '';
  7764. this.fileName = null;
  7765. this.importAttributes = null;
  7766. this.id = module.id;
  7767. this.moduleInfo = module.info;
  7768. this.renormalizeRenderPath = module.renormalizeRenderPath;
  7769. this.suggestedVariableName = module.suggestedVariableName;
  7770. }
  7771. getFileName() {
  7772. if (this.fileName) {
  7773. return this.fileName;
  7774. }
  7775. const { paths } = this.options;
  7776. return (this.fileName =
  7777. (typeof paths === 'function' ? paths(this.id) : paths[this.id]) ||
  7778. (this.renormalizeRenderPath ? normalize(relative(this.inputBase, this.id)) : this.id));
  7779. }
  7780. getImportAttributes(snippets) {
  7781. return (this.importAttributes ||= formatAttributes(['es', 'cjs'].includes(this.options.format) &&
  7782. this.options.externalImportAttributes &&
  7783. this.moduleInfo.attributes, snippets));
  7784. }
  7785. getImportPath(importer) {
  7786. return escapeId(this.renormalizeRenderPath
  7787. ? getImportPath(importer, this.getFileName(), this.options.format === 'amd', false)
  7788. : this.getFileName());
  7789. }
  7790. }
  7791. function formatAttributes(attributes, { getObject }) {
  7792. if (!attributes) {
  7793. return null;
  7794. }
  7795. const assertionEntries = Object.entries(attributes).map(([key, value]) => [key, `'${value}'`]);
  7796. if (assertionEntries.length > 0) {
  7797. return getObject(assertionEntries, { lineBreakIndent: null });
  7798. }
  7799. return null;
  7800. }
  7801. function removeJsExtension(name) {
  7802. return name.endsWith('.js') ? name.slice(0, -3) : name;
  7803. }
  7804. function getCompleteAmdId(options, chunkId) {
  7805. if (options.autoId) {
  7806. return `${options.basePath ? options.basePath + '/' : ''}${removeJsExtension(chunkId)}`;
  7807. }
  7808. return options.id ?? '';
  7809. }
  7810. function getExportBlock$1(exports$1, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal, mechanism = 'return ') {
  7811. const { _, getDirectReturnFunction, getFunctionIntro, getPropertyAccess, n, s } = snippets;
  7812. if (!namedExportsMode) {
  7813. return `${n}${n}${mechanism}${getSingleDefaultExport(exports$1, dependencies, interop, externalLiveBindings, getPropertyAccess)};`;
  7814. }
  7815. let exportBlock = '';
  7816. if (namedExportsMode) {
  7817. for (const { defaultVariableName, importPath, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  7818. if (!reexports) {
  7819. continue;
  7820. }
  7821. for (const specifier of reexports) {
  7822. if (specifier.reexported !== '*') {
  7823. const importName = getReexportedImportName(name, specifier.imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, importPath, externalLiveBindings, getPropertyAccess);
  7824. if (exportBlock)
  7825. exportBlock += n;
  7826. if (specifier.imported !== '*' && specifier.needsLiveBinding) {
  7827. const [left, right] = getDirectReturnFunction([], {
  7828. functionReturn: true,
  7829. lineBreakIndent: null,
  7830. name: null
  7831. });
  7832. exportBlock +=
  7833. `Object.defineProperty(exports,${_}${JSON.stringify(specifier.reexported)},${_}{${n}` +
  7834. `${t}enumerable:${_}true,${n}` +
  7835. `${t}get:${_}${left}${importName}${right}${n}});`;
  7836. }
  7837. else if (specifier.reexported === '__proto__') {
  7838. exportBlock +=
  7839. `Object.defineProperty(exports,${_}"__proto__",${_}{${n}` +
  7840. `${t}enumerable:${_}true,${n}` +
  7841. `${t}value:${_}${importName}${n}});`;
  7842. }
  7843. else {
  7844. exportBlock += `exports${getPropertyAccess(specifier.reexported)}${_}=${_}${importName};`;
  7845. }
  7846. }
  7847. }
  7848. }
  7849. }
  7850. for (const { exported, local } of exports$1) {
  7851. const lhs = `exports${getPropertyAccess(exported)}`;
  7852. const rhs = local;
  7853. if (lhs !== rhs) {
  7854. if (exportBlock)
  7855. exportBlock += n;
  7856. exportBlock +=
  7857. exported === '__proto__'
  7858. ? `Object.defineProperty(exports,${_}"__proto__",${_}{${n}` +
  7859. `${t}enumerable:${_}true,${n}` +
  7860. `${t}value:${_}${rhs}${n}});`
  7861. : `${lhs}${_}=${_}${rhs};`;
  7862. }
  7863. }
  7864. if (namedExportsMode) {
  7865. for (const { name, reexports } of dependencies) {
  7866. if (!reexports) {
  7867. continue;
  7868. }
  7869. for (const specifier of reexports) {
  7870. if (specifier.reexported === '*') {
  7871. if (exportBlock)
  7872. exportBlock += n;
  7873. if (!specifier.needsLiveBinding && reexportProtoFromExternal) {
  7874. const protoString = "'__proto__'";
  7875. exportBlock +=
  7876. `Object.prototype.hasOwnProperty.call(${name},${_}${protoString})${_}&&${n}` +
  7877. `${t}!Object.prototype.hasOwnProperty.call(exports,${_}${protoString})${_}&&${n}` +
  7878. `${t}Object.defineProperty(exports,${_}${protoString},${_}{${n}` +
  7879. `${t}${t}enumerable:${_}true,${n}` +
  7880. `${t}${t}value:${_}${name}[${protoString}]${n}` +
  7881. `${t}});${n}${n}`;
  7882. }
  7883. const copyPropertyIfNecessary = `{${n}${t}if${_}(k${_}!==${_}'default'${_}&&${_}!Object.prototype.hasOwnProperty.call(exports,${_}k))${_}${getDefineProperty(name, specifier.needsLiveBinding, t, snippets)}${s}${n}}`;
  7884. exportBlock += `Object.keys(${name}).forEach(${getFunctionIntro(['k'], {
  7885. isAsync: false,
  7886. name: null
  7887. })}${copyPropertyIfNecessary});`;
  7888. }
  7889. }
  7890. }
  7891. }
  7892. if (exportBlock) {
  7893. return `${n}${n}${exportBlock}`;
  7894. }
  7895. return '';
  7896. }
  7897. function getSingleDefaultExport(exports$1, dependencies, interop, externalLiveBindings, getPropertyAccess) {
  7898. if (exports$1.length > 0) {
  7899. return exports$1[0].local;
  7900. }
  7901. else {
  7902. for (const { defaultVariableName, importPath, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
  7903. if (reexports) {
  7904. return getReexportedImportName(name, reexports[0].imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, importPath, externalLiveBindings, getPropertyAccess);
  7905. }
  7906. }
  7907. }
  7908. }
  7909. function getReexportedImportName(moduleVariableName, imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, moduleId, externalLiveBindings, getPropertyAccess) {
  7910. if (imported === 'default') {
  7911. if (!isChunk) {
  7912. const moduleInterop = interop(moduleId);
  7913. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  7914. ? defaultVariableName
  7915. : moduleVariableName;
  7916. return isDefaultAProperty(moduleInterop, externalLiveBindings)
  7917. ? `${variableName}${getPropertyAccess('default')}`
  7918. : variableName;
  7919. }
  7920. return depNamedExportsMode
  7921. ? `${moduleVariableName}${getPropertyAccess('default')}`
  7922. : moduleVariableName;
  7923. }
  7924. if (imported === '*') {
  7925. return (isChunk ? !depNamedExportsMode : namespaceInteropHelpersByInteropType[interop(moduleId)])
  7926. ? namespaceVariableName
  7927. : moduleVariableName;
  7928. }
  7929. return `${moduleVariableName}${getPropertyAccess(imported)}`;
  7930. }
  7931. function getEsModuleValue(getObject) {
  7932. return getObject([['value', 'true']], {
  7933. lineBreakIndent: null
  7934. });
  7935. }
  7936. function getNamespaceMarkers(hasNamedExports, addEsModule, addNamespaceToStringTag, { _, getObject }) {
  7937. if (hasNamedExports) {
  7938. if (addEsModule) {
  7939. if (addNamespaceToStringTag) {
  7940. return `Object.defineProperties(exports,${_}${getObject([
  7941. ['__esModule', getEsModuleValue(getObject)],
  7942. [null, `[Symbol.toStringTag]:${_}${getToStringTagValue(getObject)}`]
  7943. ], {
  7944. lineBreakIndent: null
  7945. })});`;
  7946. }
  7947. return `Object.defineProperty(exports,${_}'__esModule',${_}${getEsModuleValue(getObject)});`;
  7948. }
  7949. if (addNamespaceToStringTag) {
  7950. return `Object.defineProperty(exports,${_}Symbol.toStringTag,${_}${getToStringTagValue(getObject)});`;
  7951. }
  7952. }
  7953. return '';
  7954. }
  7955. const getDefineProperty = (name, needsLiveBinding, t, { _, getDirectReturnFunction, n }) => {
  7956. if (needsLiveBinding) {
  7957. const [left, right] = getDirectReturnFunction([], {
  7958. functionReturn: true,
  7959. lineBreakIndent: null,
  7960. name: null
  7961. });
  7962. return (`Object.defineProperty(exports,${_}k,${_}{${n}` +
  7963. `${t}${t}enumerable:${_}true,${n}` +
  7964. `${t}${t}get:${_}${left}${name}[k]${right}${n}${t}})`);
  7965. }
  7966. return `exports[k]${_}=${_}${name}[k]`;
  7967. };
  7968. function getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, indent, snippets) {
  7969. const { _, cnst, n } = snippets;
  7970. const neededInteropHelpers = new Set();
  7971. const interopStatements = [];
  7972. const addInteropStatement = (helperVariableName, helper, dependencyVariableName) => {
  7973. neededInteropHelpers.add(helper);
  7974. interopStatements.push(`${cnst} ${helperVariableName}${_}=${_}/*#__PURE__*/${helper}(${dependencyVariableName});`);
  7975. };
  7976. for (const { defaultVariableName, imports, importPath, isChunk, name, namedExportsMode, namespaceVariableName, reexports } of dependencies) {
  7977. if (isChunk) {
  7978. for (const { imported, reexported } of [
  7979. ...(imports || []),
  7980. ...(reexports || [])
  7981. ]) {
  7982. if (imported === '*' && reexported !== '*') {
  7983. if (!namedExportsMode) {
  7984. addInteropStatement(namespaceVariableName, INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE, name);
  7985. }
  7986. break;
  7987. }
  7988. }
  7989. }
  7990. else {
  7991. const moduleInterop = interop(importPath);
  7992. let hasDefault = false;
  7993. let hasNamespace = false;
  7994. for (const { imported, reexported } of [
  7995. ...(imports || []),
  7996. ...(reexports || [])
  7997. ]) {
  7998. let helper;
  7999. let variableName;
  8000. if (imported === 'default') {
  8001. if (!hasDefault) {
  8002. hasDefault = true;
  8003. if (defaultVariableName !== namespaceVariableName) {
  8004. variableName = defaultVariableName;
  8005. helper = defaultInteropHelpersByInteropType[moduleInterop];
  8006. }
  8007. }
  8008. }
  8009. else if (imported === '*' && reexported !== '*' && !hasNamespace) {
  8010. hasNamespace = true;
  8011. helper = namespaceInteropHelpersByInteropType[moduleInterop];
  8012. variableName = namespaceVariableName;
  8013. }
  8014. if (helper) {
  8015. addInteropStatement(variableName, helper, name);
  8016. }
  8017. }
  8018. }
  8019. }
  8020. return `${getHelpersBlock(neededInteropHelpers, accessedGlobals, indent, snippets, externalLiveBindings, freeze, symbols)}${interopStatements.length > 0 ? `${interopStatements.join(n)}${n}${n}` : ''}`;
  8021. }
  8022. function throwOnPhase(outputFormat, chunkId, dependencies) {
  8023. const sourcePhaseDependency = dependencies.find(dependency => dependency.sourcePhaseImport);
  8024. if (sourcePhaseDependency) {
  8025. error(logSourcePhaseFormatUnsupported(outputFormat, chunkId, sourcePhaseDependency.importPath));
  8026. }
  8027. }
  8028. function addJsExtension(name) {
  8029. return name.endsWith('.js') ? name : name + '.js';
  8030. }
  8031. // AMD resolution will only respect the AMD baseUrl if the .js extension is omitted.
  8032. // The assumption is that this makes sense for all relative ids:
  8033. // https://requirejs.org/docs/api.html#jsfiles
  8034. function updateExtensionForRelativeAmdId(id, forceJsExtensionForImports) {
  8035. if (id[0] !== '.') {
  8036. return id;
  8037. }
  8038. return forceJsExtensionForImports ? addJsExtension(id) : removeJsExtension(id);
  8039. }
  8040. const builtinModules = [
  8041. "node:assert",
  8042. "assert",
  8043. "node:assert/strict",
  8044. "assert/strict",
  8045. "node:async_hooks",
  8046. "async_hooks",
  8047. "node:buffer",
  8048. "buffer",
  8049. "node:child_process",
  8050. "child_process",
  8051. "node:cluster",
  8052. "cluster",
  8053. "node:console",
  8054. "console",
  8055. "node:constants",
  8056. "constants",
  8057. "node:crypto",
  8058. "crypto",
  8059. "node:dgram",
  8060. "dgram",
  8061. "node:diagnostics_channel",
  8062. "diagnostics_channel",
  8063. "node:dns",
  8064. "dns",
  8065. "node:dns/promises",
  8066. "dns/promises",
  8067. "node:domain",
  8068. "domain",
  8069. "node:events",
  8070. "events",
  8071. "node:fs",
  8072. "fs",
  8073. "node:fs/promises",
  8074. "fs/promises",
  8075. "node:http",
  8076. "http",
  8077. "node:http2",
  8078. "http2",
  8079. "node:https",
  8080. "https",
  8081. "node:inspector",
  8082. "inspector",
  8083. "node:inspector/promises",
  8084. "inspector/promises",
  8085. "node:module",
  8086. "module",
  8087. "node:net",
  8088. "net",
  8089. "node:os",
  8090. "os",
  8091. "node:path",
  8092. "path",
  8093. "node:path/posix",
  8094. "path/posix",
  8095. "node:path/win32",
  8096. "path/win32",
  8097. "node:perf_hooks",
  8098. "perf_hooks",
  8099. "node:process",
  8100. "process",
  8101. "node:querystring",
  8102. "querystring",
  8103. "node:quic",
  8104. "node:readline",
  8105. "readline",
  8106. "node:readline/promises",
  8107. "readline/promises",
  8108. "node:repl",
  8109. "repl",
  8110. "node:sea",
  8111. "node:sqlite",
  8112. "node:stream",
  8113. "stream",
  8114. "node:stream/consumers",
  8115. "stream/consumers",
  8116. "node:stream/promises",
  8117. "stream/promises",
  8118. "node:stream/web",
  8119. "stream/web",
  8120. "node:string_decoder",
  8121. "string_decoder",
  8122. "node:test",
  8123. "node:test/reporters",
  8124. "node:timers",
  8125. "timers",
  8126. "node:timers/promises",
  8127. "timers/promises",
  8128. "node:tls",
  8129. "tls",
  8130. "node:trace_events",
  8131. "trace_events",
  8132. "node:tty",
  8133. "tty",
  8134. "node:url",
  8135. "url",
  8136. "node:util",
  8137. "util",
  8138. "node:util/types",
  8139. "util/types",
  8140. "node:v8",
  8141. "v8",
  8142. "node:vm",
  8143. "vm",
  8144. "node:wasi",
  8145. "wasi",
  8146. "node:worker_threads",
  8147. "worker_threads",
  8148. "node:zlib",
  8149. "zlib"
  8150. ];
  8151. const nodeBuiltins = new Set(builtinModules);
  8152. function warnOnBuiltins(log, dependencies) {
  8153. const externalBuiltins = dependencies
  8154. .map(({ importPath }) => importPath)
  8155. .filter(importPath => nodeBuiltins.has(importPath) || importPath.startsWith('node:'));
  8156. if (externalBuiltins.length === 0)
  8157. return;
  8158. log(LOGLEVEL_WARN, logMissingNodeBuiltins(externalBuiltins));
  8159. }
  8160. function amd(magicString, { accessedGlobals, dependencies, exports: exports$1, hasDefaultExport, hasExports, id, indent: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, log, outro, snippets }, { amd, esModule, externalLiveBindings, freeze, generatedCode: { symbols }, interop, reexportProtoFromExternal, strict }) {
  8161. warnOnBuiltins(log, dependencies);
  8162. throwOnPhase('amd', id, dependencies);
  8163. const deps = dependencies.map(m => `'${updateExtensionForRelativeAmdId(m.importPath, amd.forceJsExtensionForImports)}'`);
  8164. const parameters = dependencies.map(m => m.name);
  8165. const { n, getNonArrowFunctionIntro, _ } = snippets;
  8166. if (hasExports && (namedExportsMode || exports$1[0]?.local === 'exports.default')) {
  8167. parameters.unshift(`exports`);
  8168. deps.unshift(`'exports'`);
  8169. }
  8170. if (accessedGlobals.has('require')) {
  8171. parameters.unshift('require');
  8172. deps.unshift(`'require'`);
  8173. }
  8174. if (accessedGlobals.has('module')) {
  8175. parameters.unshift('module');
  8176. deps.unshift(`'module'`);
  8177. }
  8178. const completeAmdId = getCompleteAmdId(amd, id);
  8179. const defineParameters = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
  8180. (deps.length > 0 ? `[${deps.join(`,${_}`)}],${_}` : ``);
  8181. const useStrict = strict ? `${_}'use strict';` : '';
  8182. magicString.prepend(`${intro}${getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, t, snippets)}`);
  8183. const exportBlock = getExportBlock$1(exports$1, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal);
  8184. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && (esModule === true || (esModule === 'if-default-prop' && hasDefaultExport)), isModuleFacade && symbols, snippets);
  8185. if (namespaceMarkers) {
  8186. namespaceMarkers = n + n + namespaceMarkers;
  8187. }
  8188. magicString
  8189. .append(`${exportBlock}${namespaceMarkers}${outro}`)
  8190. .indent(t)
  8191. // factory function should be wrapped by parentheses to avoid lazy parsing,
  8192. // cf. https://v8.dev/blog/preparser#pife
  8193. .prepend(`${amd.define}(${defineParameters}(${getNonArrowFunctionIntro(parameters, {
  8194. isAsync: false,
  8195. name: null
  8196. })}{${useStrict}${n}${n}`)
  8197. .append(`${n}${n}}));`);
  8198. }
  8199. function cjs(magicString, { accessedGlobals, dependencies, exports: exports$1, hasDefaultExport, hasExports, id, indent: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, outro, snippets }, { compact, esModule, externalLiveBindings, freeze, interop, generatedCode: { symbols }, reexportProtoFromExternal, strict }) {
  8200. throwOnPhase('cjs', id, dependencies);
  8201. const { _, n } = snippets;
  8202. const useStrict = strict ? `'use strict';${n}${n}` : '';
  8203. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && (esModule === true || (esModule === 'if-default-prop' && hasDefaultExport)), isModuleFacade && symbols, snippets);
  8204. if (namespaceMarkers) {
  8205. namespaceMarkers += n + n;
  8206. }
  8207. const importBlock = getImportBlock$1(dependencies, snippets, compact);
  8208. const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, t, snippets);
  8209. magicString.prepend(`${useStrict}${intro}${namespaceMarkers}${importBlock}${interopBlock}`);
  8210. const exportBlock = getExportBlock$1(exports$1, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal, `module.exports${_}=${_}`);
  8211. magicString.append(`${exportBlock}${outro}`);
  8212. }
  8213. function getImportBlock$1(dependencies, { _, cnst, n }, compact) {
  8214. let importBlock = '';
  8215. let definingVariable = false;
  8216. for (const { importPath, name, reexports, imports } of dependencies) {
  8217. if (!reexports && !imports) {
  8218. if (importBlock) {
  8219. importBlock += compact && !definingVariable ? ',' : `;${n}`;
  8220. }
  8221. definingVariable = false;
  8222. importBlock += `require('${importPath}')`;
  8223. }
  8224. else {
  8225. importBlock += compact && definingVariable ? ',' : `${importBlock ? `;${n}` : ''}${cnst} `;
  8226. definingVariable = true;
  8227. importBlock += `${name}${_}=${_}require('${importPath}')`;
  8228. }
  8229. }
  8230. if (importBlock) {
  8231. return `${importBlock};${n}${n}`;
  8232. }
  8233. return '';
  8234. }
  8235. function es(magicString, { accessedGlobals, indent: t, intro, outro, dependencies, exports: exports$1, snippets }, { externalLiveBindings, freeze, generatedCode: { symbols }, importAttributesKey }) {
  8236. const { n } = snippets;
  8237. const importBlock = getImportBlock(dependencies, importAttributesKey, snippets);
  8238. if (importBlock.length > 0)
  8239. intro += importBlock.join(n) + n + n;
  8240. intro += getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, symbols);
  8241. if (intro)
  8242. magicString.prepend(intro);
  8243. const exportBlock = getExportBlock(exports$1, snippets);
  8244. if (exportBlock.length > 0)
  8245. magicString.append(n + n + exportBlock.join(n).trim());
  8246. if (outro)
  8247. magicString.append(outro);
  8248. magicString.trim();
  8249. }
  8250. function getImportBlock(dependencies, importAttributesKey, { _ }) {
  8251. const importBlock = [];
  8252. for (const { importPath, reexports, imports, name, attributes, sourcePhaseImport } of dependencies) {
  8253. const assertion = attributes ? `${_}${importAttributesKey}${_}${attributes}` : '';
  8254. const pathWithAssertion = `'${importPath}'${assertion};`;
  8255. if (sourcePhaseImport) {
  8256. importBlock.push(`import source ${sourcePhaseImport} from${_}${pathWithAssertion}`);
  8257. }
  8258. if (!reexports && !imports) {
  8259. if (!sourcePhaseImport) {
  8260. importBlock.push(`import${_}${pathWithAssertion}`);
  8261. }
  8262. continue;
  8263. }
  8264. if (imports) {
  8265. let defaultImport = null;
  8266. let starImport = null;
  8267. const importedNames = [];
  8268. for (const specifier of imports) {
  8269. if (specifier.imported === 'default') {
  8270. defaultImport = specifier;
  8271. }
  8272. else if (specifier.imported === '*') {
  8273. starImport = specifier;
  8274. }
  8275. else {
  8276. importedNames.push(specifier);
  8277. }
  8278. }
  8279. if (starImport) {
  8280. importBlock.push(`import${_}*${_}as ${starImport.local} from${_}${pathWithAssertion}`);
  8281. }
  8282. if (defaultImport && importedNames.length === 0) {
  8283. importBlock.push(`import ${defaultImport.local} from${_}${pathWithAssertion}`);
  8284. }
  8285. else if (importedNames.length > 0) {
  8286. importBlock.push(`import ${defaultImport ? `${defaultImport.local},${_}` : ''}{${_}${importedNames
  8287. .map(specifier => specifier.imported === specifier.local
  8288. ? specifier.imported
  8289. : `${stringifyIdentifierIfNeeded(specifier.imported)} as ${specifier.local}`)
  8290. .join(`,${_}`)}${_}}${_}from${_}${pathWithAssertion}`);
  8291. }
  8292. }
  8293. if (reexports) {
  8294. let starExport = null;
  8295. const namespaceReexports = [];
  8296. const namedReexports = [];
  8297. for (const specifier of reexports) {
  8298. if (specifier.reexported === '*') {
  8299. starExport = specifier;
  8300. }
  8301. else if (specifier.imported === '*') {
  8302. namespaceReexports.push(specifier);
  8303. }
  8304. else {
  8305. namedReexports.push(specifier);
  8306. }
  8307. }
  8308. if (starExport) {
  8309. importBlock.push(`export${_}*${_}from${_}${pathWithAssertion}`);
  8310. }
  8311. if (namespaceReexports.length > 0) {
  8312. if (!imports ||
  8313. !imports.some(specifier => specifier.imported === '*' && specifier.local === name)) {
  8314. importBlock.push(`import${_}*${_}as ${name} from${_}${pathWithAssertion}`);
  8315. }
  8316. for (const specifier of namespaceReexports) {
  8317. importBlock.push(`export${_}{${_}${name === specifier.reexported
  8318. ? name
  8319. : `${name} as ${stringifyIdentifierIfNeeded(specifier.reexported)}`} };`);
  8320. }
  8321. }
  8322. if (namedReexports.length > 0) {
  8323. importBlock.push(`export${_}{${_}${namedReexports
  8324. .map(specifier => specifier.imported === specifier.reexported
  8325. ? stringifyIdentifierIfNeeded(specifier.imported)
  8326. : `${stringifyIdentifierIfNeeded(specifier.imported)} as ${stringifyIdentifierIfNeeded(specifier.reexported)}`)
  8327. .join(`,${_}`)}${_}}${_}from${_}${pathWithAssertion}`);
  8328. }
  8329. }
  8330. }
  8331. return importBlock;
  8332. }
  8333. function getExportBlock(exports$1, { _, cnst }) {
  8334. const exportBlock = [];
  8335. const exportDeclaration = new Array(exports$1.length);
  8336. let index = 0;
  8337. for (const specifier of exports$1) {
  8338. if (specifier.expression) {
  8339. exportBlock.push(`${cnst} ${specifier.local}${_}=${_}${specifier.expression};`);
  8340. }
  8341. exportDeclaration[index++] =
  8342. specifier.exported === specifier.local
  8343. ? specifier.local
  8344. : `${specifier.local} as ${stringifyIdentifierIfNeeded(specifier.exported)}`;
  8345. }
  8346. if (exportDeclaration.length > 0) {
  8347. exportBlock.push(`export${_}{${_}${exportDeclaration.join(`,${_}`)}${_}};`);
  8348. }
  8349. return exportBlock;
  8350. }
  8351. const keypath = (keypath, getPropertyAccess) => keypath.split('.').map(getPropertyAccess).join('');
  8352. function setupNamespace(name, root, globals, { _, getPropertyAccess, s }, compact, log) {
  8353. const parts = name.split('.');
  8354. // Check if the key exists in the object's prototype.
  8355. const isReserved = parts[0] in Object.prototype;
  8356. if (log && isReserved) {
  8357. log(LOGLEVEL_WARN, logReservedNamespace(parts[0]));
  8358. }
  8359. parts[0] =
  8360. (typeof globals === 'function'
  8361. ? globals(parts[0])
  8362. : isReserved
  8363. ? parts[0]
  8364. : globals[parts[0]]) || parts[0];
  8365. parts.pop();
  8366. let propertyPath = root;
  8367. return (parts
  8368. .map(part => {
  8369. propertyPath += getPropertyAccess(part);
  8370. return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}${s}`;
  8371. })
  8372. .join(compact ? ',' : '\n') + (compact && parts.length > 0 ? ';' : '\n'));
  8373. }
  8374. function assignToDeepVariable(deepName, root, globals, assignment, { _, getPropertyAccess }, log) {
  8375. const parts = deepName.split('.');
  8376. // Check if the key exists in the object's prototype.
  8377. const isReserved = parts[0] in Object.prototype;
  8378. if (log && isReserved) {
  8379. log(LOGLEVEL_WARN, logReservedNamespace(parts[0]));
  8380. }
  8381. parts[0] =
  8382. (typeof globals === 'function'
  8383. ? globals(parts[0])
  8384. : isReserved
  8385. ? parts[0]
  8386. : globals[parts[0]]) || parts[0];
  8387. const last = parts.pop();
  8388. let propertyPath = root;
  8389. let deepAssignment = [
  8390. ...parts.map(part => {
  8391. propertyPath += getPropertyAccess(part);
  8392. return `${propertyPath}${_}=${_}${propertyPath}${_}||${_}{}`;
  8393. }),
  8394. `${propertyPath}${getPropertyAccess(last)}`
  8395. ].join(`,${_}`) + `${_}=${_}${assignment}`;
  8396. if (parts.length > 0) {
  8397. deepAssignment = `(${deepAssignment})`;
  8398. }
  8399. return deepAssignment;
  8400. }
  8401. function trimEmptyImports(dependencies) {
  8402. let index = dependencies.length;
  8403. while (index--) {
  8404. const { imports, reexports } = dependencies[index];
  8405. if (imports || reexports) {
  8406. return dependencies.slice(0, index + 1);
  8407. }
  8408. }
  8409. return [];
  8410. }
  8411. function iife(magicString, { accessedGlobals, dependencies, exports: exports$1, hasDefaultExport, hasExports, id, indent: t, intro, namedExportsMode, log, outro, snippets }, { compact, esModule, extend, freeze, externalLiveBindings, reexportProtoFromExternal, globals, interop, name, generatedCode: { symbols }, strict }) {
  8412. throwOnPhase('iife', id, dependencies);
  8413. const { _, getNonArrowFunctionIntro, getPropertyAccess, n } = snippets;
  8414. const isNamespaced = name && name.includes('.');
  8415. const useVariableAssignment = !extend && !isNamespaced;
  8416. if (name && useVariableAssignment && !isLegal(name)) {
  8417. return error(logIllegalIdentifierAsName(name));
  8418. }
  8419. warnOnBuiltins(log, dependencies);
  8420. const external = trimEmptyImports(dependencies);
  8421. const deps = external.map(dep => dep.globalName || 'null');
  8422. const parameters = external.map(m => m.name);
  8423. if (hasExports && !name) {
  8424. log(LOGLEVEL_WARN, logMissingNameOptionForIifeExport());
  8425. }
  8426. if (hasExports && (namedExportsMode || exports$1[0]?.local === 'exports.default')) {
  8427. if (extend) {
  8428. deps.unshift(`this${keypath(name, getPropertyAccess)}${_}=${_}this${keypath(name, getPropertyAccess)}${_}||${_}{}`);
  8429. parameters.unshift('exports');
  8430. }
  8431. else {
  8432. deps.unshift('{}');
  8433. parameters.unshift('exports');
  8434. }
  8435. }
  8436. const useStrict = strict ? `${t}'use strict';${n}` : '';
  8437. const interopBlock = getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, t, snippets);
  8438. magicString.prepend(`${intro}${interopBlock}`);
  8439. let wrapperIntro = `(${getNonArrowFunctionIntro(parameters, {
  8440. isAsync: false,
  8441. name: null
  8442. })}{${n}${useStrict}${n}`;
  8443. if (hasExports) {
  8444. if (name && !(extend && namedExportsMode)) {
  8445. wrapperIntro =
  8446. (useVariableAssignment ? `var ${name}` : `this${keypath(name, getPropertyAccess)}`) +
  8447. `${_}=${_}${wrapperIntro}`;
  8448. }
  8449. if (isNamespaced) {
  8450. wrapperIntro = setupNamespace(name, 'this', globals, snippets, compact, log) + wrapperIntro;
  8451. }
  8452. }
  8453. let wrapperOutro = `${n}${n}})(${deps.join(`,${_}`)});`;
  8454. if (hasExports && !extend && namedExportsMode) {
  8455. wrapperOutro = `${n}${n}${t}return exports;${wrapperOutro}`;
  8456. }
  8457. const exportBlock = getExportBlock$1(exports$1, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal);
  8458. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule === true || (esModule === 'if-default-prop' && hasDefaultExport), symbols, snippets);
  8459. if (namespaceMarkers) {
  8460. namespaceMarkers = n + n + namespaceMarkers;
  8461. }
  8462. magicString
  8463. .append(`${exportBlock}${namespaceMarkers}${outro}`)
  8464. .indent(t)
  8465. .prepend(wrapperIntro)
  8466. .append(wrapperOutro);
  8467. }
  8468. const MISSING_EXPORT_SHIM_VARIABLE = '_missingExportShim';
  8469. function system(magicString, { accessedGlobals, dependencies, exports: exports$1, hasExports, id, indent: t, intro, snippets, outro, usesTopLevelAwait }, { externalLiveBindings, freeze, name, generatedCode: { symbols }, strict, systemNullSetters }) {
  8470. throwOnPhase('system', id, dependencies);
  8471. const { _, getFunctionIntro, getNonArrowFunctionIntro, n, s } = snippets;
  8472. const { importBindings, setters, starExcludes } = analyzeDependencies(dependencies, exports$1, t, snippets);
  8473. const registeredName = name ? `'${name}',${_}` : '';
  8474. const wrapperParameters = accessedGlobals.has('module')
  8475. ? ['exports', 'module']
  8476. : hasExports
  8477. ? ['exports']
  8478. : [];
  8479. // factory function should be wrapped by parentheses to avoid lazy parsing,
  8480. // cf. https://v8.dev/blog/preparser#pife
  8481. let wrapperStart = `System.register(${registeredName}[` +
  8482. dependencies.map(({ importPath }) => `'${importPath}'`).join(`,${_}`) +
  8483. `],${_}(${getNonArrowFunctionIntro(wrapperParameters, {
  8484. isAsync: false,
  8485. name: null
  8486. })}{${n}${t}${strict ? "'use strict';" : ''}` +
  8487. getStarExcludesBlock(starExcludes, t, snippets) +
  8488. getImportBindingsBlock(importBindings, t, snippets) +
  8489. `${n}${t}return${_}{${setters.length > 0
  8490. ? `${n}${t}${t}setters:${_}[${setters
  8491. .map(setter => setter
  8492. ? `${getFunctionIntro(['module'], {
  8493. isAsync: false,
  8494. name: null
  8495. })}{${n}${t}${t}${t}${setter}${n}${t}${t}}`
  8496. : systemNullSetters
  8497. ? `null`
  8498. : `${getFunctionIntro([], { isAsync: false, name: null })}{}`)
  8499. .join(`,${_}`)}],`
  8500. : ''}${n}`;
  8501. wrapperStart += `${t}${t}execute:${_}(${getNonArrowFunctionIntro([], {
  8502. isAsync: usesTopLevelAwait,
  8503. name: null
  8504. })}{${n}${n}`;
  8505. const wrapperEnd = `${t}${t}})${n}${t}}${s}${n}}));`;
  8506. magicString
  8507. .prepend(intro +
  8508. getHelpersBlock(null, accessedGlobals, t, snippets, externalLiveBindings, freeze, symbols) +
  8509. getHoistedExportsBlock(exports$1, t, snippets))
  8510. .append(`${outro}${n}${n}` +
  8511. getSyntheticExportsBlock(exports$1, t, snippets) +
  8512. getMissingExportsBlock(exports$1, t, snippets))
  8513. .indent(`${t}${t}${t}`)
  8514. .append(wrapperEnd)
  8515. .prepend(wrapperStart);
  8516. }
  8517. function analyzeDependencies(dependencies, exports$1, t, { _, cnst, getObject, getPropertyAccess, n }) {
  8518. const importBindings = [];
  8519. const setters = [];
  8520. let starExcludes = null;
  8521. for (const { imports, reexports } of dependencies) {
  8522. const setter = [];
  8523. if (imports) {
  8524. for (const specifier of imports) {
  8525. importBindings.push(specifier.local);
  8526. if (specifier.imported === '*') {
  8527. setter.push(`${specifier.local}${_}=${_}module;`);
  8528. }
  8529. else {
  8530. setter.push(`${specifier.local}${_}=${_}module${getPropertyAccess(specifier.imported)};`);
  8531. }
  8532. }
  8533. }
  8534. if (reexports) {
  8535. const reexportedNames = [];
  8536. let hasStarReexport = false;
  8537. for (const { imported, reexported } of reexports) {
  8538. if (reexported === '*') {
  8539. hasStarReexport = true;
  8540. }
  8541. else {
  8542. reexportedNames.push([
  8543. reexported,
  8544. imported === '*' ? 'module' : `module${getPropertyAccess(imported)}`
  8545. ]);
  8546. }
  8547. }
  8548. if (reexportedNames.length > 1 || hasStarReexport) {
  8549. if (hasStarReexport) {
  8550. if (!starExcludes) {
  8551. starExcludes = getStarExcludes({ dependencies, exports: exports$1 });
  8552. }
  8553. reexportedNames.unshift([null, `__proto__:${_}null`]);
  8554. const exportMapping = getObject(reexportedNames, { lineBreakIndent: null });
  8555. setter.push(`${cnst} setter${_}=${_}${exportMapping};`, `for${_}(${cnst} name in module)${_}{`, `${t}if${_}(!_starExcludes[name])${_}setter[name]${_}=${_}module[name];`, '}', 'exports(setter);');
  8556. }
  8557. else {
  8558. const exportMapping = getObject(reexportedNames, { lineBreakIndent: null });
  8559. setter.push(`exports(${exportMapping});`);
  8560. }
  8561. }
  8562. else {
  8563. const [key, value] = reexportedNames[0];
  8564. setter.push(`exports(${JSON.stringify(key)},${_}${value});`);
  8565. }
  8566. }
  8567. setters.push(setter.join(`${n}${t}${t}${t}`));
  8568. }
  8569. return { importBindings, setters, starExcludes };
  8570. }
  8571. const getStarExcludes = ({ dependencies, exports: exports$1 }) => {
  8572. const starExcludes = new Set(exports$1.map(expt => expt.exported));
  8573. starExcludes.add('default');
  8574. for (const { reexports } of dependencies) {
  8575. if (reexports) {
  8576. for (const reexport of reexports) {
  8577. if (reexport.reexported !== '*')
  8578. starExcludes.add(reexport.reexported);
  8579. }
  8580. }
  8581. }
  8582. return starExcludes;
  8583. };
  8584. const getStarExcludesBlock = (starExcludes, t, { _, cnst, getObject, n }) => {
  8585. if (starExcludes) {
  8586. const fields = [...starExcludes].map(property => [
  8587. property,
  8588. '1'
  8589. ]);
  8590. fields.unshift([null, `__proto__:${_}null`]);
  8591. return `${n}${t}${cnst} _starExcludes${_}=${_}${getObject(fields, {
  8592. lineBreakIndent: { base: t, t }
  8593. })};`;
  8594. }
  8595. return '';
  8596. };
  8597. const getImportBindingsBlock = (importBindings, t, { _, n }) => (importBindings.length > 0 ? `${n}${t}var ${importBindings.join(`,${_}`)};` : '');
  8598. const getHoistedExportsBlock = (exports$1, t, snippets) => getExportsBlock(exports$1.filter(expt => expt.hoisted).map(expt => ({ name: expt.exported, value: expt.local })), t, snippets);
  8599. function getExportsBlock(exports$1, t, { _, n }) {
  8600. if (exports$1.length === 0) {
  8601. return '';
  8602. }
  8603. if (exports$1.length === 1) {
  8604. return `exports(${JSON.stringify(exports$1[0].name)},${_}${exports$1[0].value});${n}${n}`;
  8605. }
  8606. return (`exports({${n}` +
  8607. exports$1
  8608. .map(({ name, value }) => `${t}${stringifyObjectKeyIfNeeded(name)}:${_}${value}`)
  8609. .join(`,${n}`) +
  8610. `${n}});${n}${n}`);
  8611. }
  8612. const getSyntheticExportsBlock = (exports$1, t, snippets) => getExportsBlock(exports$1
  8613. .filter(expt => expt.expression)
  8614. .map(expt => ({ name: expt.exported, value: expt.local })), t, snippets);
  8615. const getMissingExportsBlock = (exports$1, t, snippets) => getExportsBlock(exports$1
  8616. .filter(expt => expt.local === MISSING_EXPORT_SHIM_VARIABLE)
  8617. .map(expt => ({ name: expt.exported, value: MISSING_EXPORT_SHIM_VARIABLE })), t, snippets);
  8618. function globalProperty(name, globalVariable, getPropertyAccess) {
  8619. if (!name)
  8620. return 'null';
  8621. return `${globalVariable}${keypath(name, getPropertyAccess)}`;
  8622. }
  8623. function safeAccess(name, globalVariable, { _, getPropertyAccess }) {
  8624. let propertyPath = globalVariable;
  8625. return name
  8626. .split('.')
  8627. .map(part => (propertyPath += getPropertyAccess(part)))
  8628. .join(`${_}&&${_}`);
  8629. }
  8630. function umd(magicString, { accessedGlobals, dependencies, exports: exports$1, hasDefaultExport, hasExports, id, indent: t, intro, namedExportsMode, log, outro, snippets }, { amd, compact, esModule, extend, externalLiveBindings, freeze, interop, name, generatedCode: { symbols }, globals, noConflict, reexportProtoFromExternal, strict }) {
  8631. const { _, cnst, getFunctionIntro, getNonArrowFunctionIntro, getPropertyAccess, n, s } = snippets;
  8632. const factoryVariable = compact ? 'f' : 'factory';
  8633. const globalVariable = compact ? 'g' : 'global';
  8634. if (hasExports && !name) {
  8635. return error(logMissingNameOptionForUmdExport());
  8636. }
  8637. throwOnPhase('umd', id, dependencies);
  8638. warnOnBuiltins(log, dependencies);
  8639. const amdDeps = dependencies.map(m => `'${updateExtensionForRelativeAmdId(m.importPath, amd.forceJsExtensionForImports)}'`);
  8640. const cjsDeps = dependencies.map(m => `require('${m.importPath}')`);
  8641. const trimmedImports = trimEmptyImports(dependencies);
  8642. const globalDeps = trimmedImports.map(module => globalProperty(module.globalName, globalVariable, getPropertyAccess));
  8643. const factoryParameters = trimmedImports.map(m => m.name);
  8644. if ((hasExports || noConflict) &&
  8645. (namedExportsMode || (hasExports && exports$1[0]?.local === 'exports.default'))) {
  8646. amdDeps.unshift(`'exports'`);
  8647. cjsDeps.unshift(`exports`);
  8648. globalDeps.unshift(assignToDeepVariable(name, globalVariable, globals, `${extend ? `${globalProperty(name, globalVariable, getPropertyAccess)}${_}||${_}` : ''}{}`, snippets, log));
  8649. factoryParameters.unshift('exports');
  8650. }
  8651. const completeAmdId = getCompleteAmdId(amd, id);
  8652. const amdParameters = (completeAmdId ? `'${completeAmdId}',${_}` : ``) +
  8653. (amdDeps.length > 0 ? `[${amdDeps.join(`,${_}`)}],${_}` : ``);
  8654. const define = amd.define;
  8655. const cjsExport = !namedExportsMode && hasExports ? `module.exports${_}=${_}` : ``;
  8656. const useStrict = strict ? `${_}'use strict';${n}` : ``;
  8657. let iifeExport;
  8658. if (noConflict) {
  8659. const noConflictExportsVariable = compact ? 'e' : 'exports';
  8660. let factory;
  8661. if (!namedExportsMode && hasExports) {
  8662. factory = `${cnst} ${noConflictExportsVariable}${_}=${_}${assignToDeepVariable(name, globalVariable, globals, `${factoryVariable}(${globalDeps.join(`,${_}`)})`, snippets, log)};`;
  8663. }
  8664. else {
  8665. const module = globalDeps.shift();
  8666. factory =
  8667. `${cnst} ${noConflictExportsVariable}${_}=${_}${module};${n}` +
  8668. `${t}${t}${factoryVariable}(${[noConflictExportsVariable, ...globalDeps].join(`,${_}`)});`;
  8669. }
  8670. iifeExport =
  8671. `(${getFunctionIntro([], { isAsync: false, name: null })}{${n}` +
  8672. `${t}${t}${cnst} current${_}=${_}${safeAccess(name, globalVariable, snippets)};${n}` +
  8673. `${t}${t}${factory}${n}` +
  8674. `${t}${t}${noConflictExportsVariable}.noConflict${_}=${_}${getFunctionIntro([], {
  8675. isAsync: false,
  8676. name: null
  8677. })}{${_}` +
  8678. `${globalProperty(name, globalVariable, getPropertyAccess)}${_}=${_}current;${_}return ${noConflictExportsVariable}${s}${_}};${n}` +
  8679. `${t}})()`;
  8680. }
  8681. else {
  8682. iifeExport = `${factoryVariable}(${globalDeps.join(`,${_}`)})`;
  8683. if (!namedExportsMode && hasExports) {
  8684. iifeExport = assignToDeepVariable(name, globalVariable, globals, iifeExport, snippets, log);
  8685. }
  8686. }
  8687. const iifeNeedsGlobal = hasExports || (noConflict && namedExportsMode) || globalDeps.length > 0;
  8688. const wrapperParameters = [factoryVariable];
  8689. if (iifeNeedsGlobal) {
  8690. wrapperParameters.unshift(globalVariable);
  8691. }
  8692. const globalArgument = iifeNeedsGlobal ? `this,${_}` : '';
  8693. const iifeStart = iifeNeedsGlobal
  8694. ? `(${globalVariable}${_}=${_}typeof globalThis${_}!==${_}'undefined'${_}?${_}globalThis${_}:${_}${globalVariable}${_}||${_}self,${_}`
  8695. : '';
  8696. const iifeEnd = iifeNeedsGlobal ? ')' : '';
  8697. const cjsIntro = iifeNeedsGlobal
  8698. ? `${t}typeof exports${_}===${_}'object'${_}&&${_}typeof module${_}!==${_}'undefined'${_}?` +
  8699. `${_}${cjsExport}${factoryVariable}(${cjsDeps.join(`,${_}`)})${_}:${n}`
  8700. : '';
  8701. const wrapperIntro = `(${getNonArrowFunctionIntro(wrapperParameters, { isAsync: false, name: null })}{${n}` +
  8702. cjsIntro +
  8703. `${t}typeof ${define}${_}===${_}'function'${_}&&${_}${define}.amd${_}?${_}${define}(${amdParameters}${factoryVariable})${_}:${n}` +
  8704. `${t}${iifeStart}${iifeExport}${iifeEnd};${n}` +
  8705. // factory function should be wrapped by parentheses to avoid lazy parsing,
  8706. // cf. https://v8.dev/blog/preparser#pife
  8707. `})(${globalArgument}(${getNonArrowFunctionIntro(factoryParameters, {
  8708. isAsync: false,
  8709. name: null
  8710. })}{${useStrict}${n}`;
  8711. const wrapperOutro = n + n + '}));';
  8712. magicString.prepend(`${intro}${getInteropBlock(dependencies, interop, externalLiveBindings, freeze, symbols, accessedGlobals, t, snippets)}`);
  8713. const exportBlock = getExportBlock$1(exports$1, dependencies, namedExportsMode, interop, snippets, t, externalLiveBindings, reexportProtoFromExternal);
  8714. let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule === true || (esModule === 'if-default-prop' && hasDefaultExport), symbols, snippets);
  8715. if (namespaceMarkers) {
  8716. namespaceMarkers = n + n + namespaceMarkers;
  8717. }
  8718. magicString
  8719. .append(`${exportBlock}${namespaceMarkers}${outro}`)
  8720. .trim()
  8721. .indent(t)
  8722. .append(wrapperOutro)
  8723. .prepend(wrapperIntro);
  8724. }
  8725. const finalisers = { amd, cjs, es, iife, system, umd };
  8726. function getDefaultExportFromCjs (x) {
  8727. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  8728. }
  8729. function getAugmentedNamespace(n) {
  8730. if (Object.prototype.hasOwnProperty.call(n, '__esModule')) return n;
  8731. var f = n.default;
  8732. if (typeof f == "function") {
  8733. var a = function a () {
  8734. var isInstance = false;
  8735. try {
  8736. isInstance = this instanceof a;
  8737. } catch {}
  8738. if (isInstance) {
  8739. return Reflect.construct(f, arguments, this.constructor);
  8740. }
  8741. return f.apply(this, arguments);
  8742. };
  8743. a.prototype = f.prototype;
  8744. } else a = {};
  8745. Object.defineProperty(a, '__esModule', {value: true});
  8746. Object.keys(n).forEach(function (k) {
  8747. var d = Object.getOwnPropertyDescriptor(n, k);
  8748. Object.defineProperty(a, k, d.get ? d : {
  8749. enumerable: true,
  8750. get: function () {
  8751. return n[k];
  8752. }
  8753. });
  8754. });
  8755. return a;
  8756. }
  8757. var utils = {};
  8758. var constants;
  8759. var hasRequiredConstants;
  8760. function requireConstants () {
  8761. if (hasRequiredConstants) return constants;
  8762. hasRequiredConstants = 1;
  8763. const WIN_SLASH = '\\\\/';
  8764. const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
  8765. const DEFAULT_MAX_EXTGLOB_RECURSION = 0;
  8766. /**
  8767. * Posix glob regex
  8768. */
  8769. const DOT_LITERAL = '\\.';
  8770. const PLUS_LITERAL = '\\+';
  8771. const QMARK_LITERAL = '\\?';
  8772. const SLASH_LITERAL = '\\/';
  8773. const ONE_CHAR = '(?=.)';
  8774. const QMARK = '[^/]';
  8775. const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
  8776. const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
  8777. const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
  8778. const NO_DOT = `(?!${DOT_LITERAL})`;
  8779. const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
  8780. const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
  8781. const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
  8782. const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
  8783. const STAR = `${QMARK}*?`;
  8784. const SEP = '/';
  8785. const POSIX_CHARS = {
  8786. DOT_LITERAL,
  8787. PLUS_LITERAL,
  8788. QMARK_LITERAL,
  8789. SLASH_LITERAL,
  8790. ONE_CHAR,
  8791. QMARK,
  8792. END_ANCHOR,
  8793. DOTS_SLASH,
  8794. NO_DOT,
  8795. NO_DOTS,
  8796. NO_DOT_SLASH,
  8797. NO_DOTS_SLASH,
  8798. QMARK_NO_DOT,
  8799. STAR,
  8800. START_ANCHOR,
  8801. SEP
  8802. };
  8803. /**
  8804. * Windows glob regex
  8805. */
  8806. const WINDOWS_CHARS = {
  8807. ...POSIX_CHARS,
  8808. SLASH_LITERAL: `[${WIN_SLASH}]`,
  8809. QMARK: WIN_NO_SLASH,
  8810. STAR: `${WIN_NO_SLASH}*?`,
  8811. DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
  8812. NO_DOT: `(?!${DOT_LITERAL})`,
  8813. NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  8814. NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
  8815. NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
  8816. QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
  8817. START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
  8818. END_ANCHOR: `(?:[${WIN_SLASH}]|$)`,
  8819. SEP: '\\'
  8820. };
  8821. /**
  8822. * POSIX Bracket Regex
  8823. */
  8824. const POSIX_REGEX_SOURCE = {
  8825. __proto__: null,
  8826. alnum: 'a-zA-Z0-9',
  8827. alpha: 'a-zA-Z',
  8828. ascii: '\\x00-\\x7F',
  8829. blank: ' \\t',
  8830. cntrl: '\\x00-\\x1F\\x7F',
  8831. digit: '0-9',
  8832. graph: '\\x21-\\x7E',
  8833. lower: 'a-z',
  8834. print: '\\x20-\\x7E ',
  8835. punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
  8836. space: ' \\t\\r\\n\\v\\f',
  8837. upper: 'A-Z',
  8838. word: 'A-Za-z0-9_',
  8839. xdigit: 'A-Fa-f0-9'
  8840. };
  8841. constants = {
  8842. DEFAULT_MAX_EXTGLOB_RECURSION,
  8843. MAX_LENGTH: 1024 * 64,
  8844. POSIX_REGEX_SOURCE,
  8845. // regular expressions
  8846. REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
  8847. REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
  8848. REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
  8849. REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
  8850. REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
  8851. REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
  8852. // Replace globs with equivalent patterns to reduce parsing time.
  8853. REPLACEMENTS: {
  8854. __proto__: null,
  8855. '***': '*',
  8856. '**/**': '**',
  8857. '**/**/**': '**'
  8858. },
  8859. // Digits
  8860. CHAR_0: 48, /* 0 */
  8861. CHAR_9: 57, /* 9 */
  8862. // Alphabet chars.
  8863. CHAR_UPPERCASE_A: 65, /* A */
  8864. CHAR_LOWERCASE_A: 97, /* a */
  8865. CHAR_UPPERCASE_Z: 90, /* Z */
  8866. CHAR_LOWERCASE_Z: 122, /* z */
  8867. CHAR_LEFT_PARENTHESES: 40, /* ( */
  8868. CHAR_RIGHT_PARENTHESES: 41, /* ) */
  8869. CHAR_ASTERISK: 42, /* * */
  8870. // Non-alphabetic chars.
  8871. CHAR_AMPERSAND: 38, /* & */
  8872. CHAR_AT: 64, /* @ */
  8873. CHAR_BACKWARD_SLASH: 92, /* \ */
  8874. CHAR_CARRIAGE_RETURN: 13, /* \r */
  8875. CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */
  8876. CHAR_COLON: 58, /* : */
  8877. CHAR_COMMA: 44, /* , */
  8878. CHAR_DOT: 46, /* . */
  8879. CHAR_DOUBLE_QUOTE: 34, /* " */
  8880. CHAR_EQUAL: 61, /* = */
  8881. CHAR_EXCLAMATION_MARK: 33, /* ! */
  8882. CHAR_FORM_FEED: 12, /* \f */
  8883. CHAR_FORWARD_SLASH: 47, /* / */
  8884. CHAR_GRAVE_ACCENT: 96, /* ` */
  8885. CHAR_HASH: 35, /* # */
  8886. CHAR_HYPHEN_MINUS: 45, /* - */
  8887. CHAR_LEFT_ANGLE_BRACKET: 60, /* < */
  8888. CHAR_LEFT_CURLY_BRACE: 123, /* { */
  8889. CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */
  8890. CHAR_LINE_FEED: 10, /* \n */
  8891. CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
  8892. CHAR_PERCENT: 37, /* % */
  8893. CHAR_PLUS: 43, /* + */
  8894. CHAR_QUESTION_MARK: 63, /* ? */
  8895. CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */
  8896. CHAR_RIGHT_CURLY_BRACE: 125, /* } */
  8897. CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */
  8898. CHAR_SEMICOLON: 59, /* ; */
  8899. CHAR_SINGLE_QUOTE: 39, /* ' */
  8900. CHAR_SPACE: 32, /* */
  8901. CHAR_TAB: 9, /* \t */
  8902. CHAR_UNDERSCORE: 95, /* _ */
  8903. CHAR_VERTICAL_LINE: 124, /* | */
  8904. CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
  8905. /**
  8906. * Create EXTGLOB_CHARS
  8907. */
  8908. extglobChars(chars) {
  8909. return {
  8910. '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
  8911. '?': { type: 'qmark', open: '(?:', close: ')?' },
  8912. '+': { type: 'plus', open: '(?:', close: ')+' },
  8913. '*': { type: 'star', open: '(?:', close: ')*' },
  8914. '@': { type: 'at', open: '(?:', close: ')' }
  8915. };
  8916. },
  8917. /**
  8918. * Create GLOB_CHARS
  8919. */
  8920. globChars(win32) {
  8921. return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
  8922. }
  8923. };
  8924. return constants;
  8925. }
  8926. /*global navigator*/
  8927. var hasRequiredUtils;
  8928. function requireUtils () {
  8929. if (hasRequiredUtils) return utils;
  8930. hasRequiredUtils = 1;
  8931. (function (exports$1) {
  8932. const {
  8933. REGEX_BACKSLASH,
  8934. REGEX_REMOVE_BACKSLASH,
  8935. REGEX_SPECIAL_CHARS,
  8936. REGEX_SPECIAL_CHARS_GLOBAL
  8937. } = /*@__PURE__*/ requireConstants();
  8938. exports$1.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
  8939. exports$1.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
  8940. exports$1.isRegexChar = str => str.length === 1 && exports$1.hasRegexChars(str);
  8941. exports$1.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
  8942. exports$1.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
  8943. exports$1.isWindows = () => {
  8944. if (typeof navigator !== 'undefined' && navigator.platform) {
  8945. const platform = navigator.platform.toLowerCase();
  8946. return platform === 'win32' || platform === 'windows';
  8947. }
  8948. if (typeof process !== 'undefined' && process.platform) {
  8949. return process.platform === 'win32';
  8950. }
  8951. return false;
  8952. };
  8953. exports$1.removeBackslashes = str => {
  8954. return str.replace(REGEX_REMOVE_BACKSLASH, match => {
  8955. return match === '\\' ? '' : match;
  8956. });
  8957. };
  8958. exports$1.escapeLast = (input, char, lastIdx) => {
  8959. const idx = input.lastIndexOf(char, lastIdx);
  8960. if (idx === -1) return input;
  8961. if (input[idx - 1] === '\\') return exports$1.escapeLast(input, char, idx - 1);
  8962. return `${input.slice(0, idx)}\\${input.slice(idx)}`;
  8963. };
  8964. exports$1.removePrefix = (input, state = {}) => {
  8965. let output = input;
  8966. if (output.startsWith('./')) {
  8967. output = output.slice(2);
  8968. state.prefix = './';
  8969. }
  8970. return output;
  8971. };
  8972. exports$1.wrapOutput = (input, state = {}, options = {}) => {
  8973. const prepend = options.contains ? '' : '^';
  8974. const append = options.contains ? '' : '$';
  8975. let output = `${prepend}(?:${input})${append}`;
  8976. if (state.negated === true) {
  8977. output = `(?:^(?!${output}).*$)`;
  8978. }
  8979. return output;
  8980. };
  8981. exports$1.basename = (path, { windows } = {}) => {
  8982. const segs = path.split(windows ? /[\\/]/ : '/');
  8983. const last = segs[segs.length - 1];
  8984. if (last === '') {
  8985. return segs[segs.length - 2];
  8986. }
  8987. return last;
  8988. };
  8989. } (utils));
  8990. return utils;
  8991. }
  8992. var scan_1;
  8993. var hasRequiredScan;
  8994. function requireScan () {
  8995. if (hasRequiredScan) return scan_1;
  8996. hasRequiredScan = 1;
  8997. const utils = /*@__PURE__*/ requireUtils();
  8998. const {
  8999. CHAR_ASTERISK, /* * */
  9000. CHAR_AT, /* @ */
  9001. CHAR_BACKWARD_SLASH, /* \ */
  9002. CHAR_COMMA, /* , */
  9003. CHAR_DOT, /* . */
  9004. CHAR_EXCLAMATION_MARK, /* ! */
  9005. CHAR_FORWARD_SLASH, /* / */
  9006. CHAR_LEFT_CURLY_BRACE, /* { */
  9007. CHAR_LEFT_PARENTHESES, /* ( */
  9008. CHAR_LEFT_SQUARE_BRACKET, /* [ */
  9009. CHAR_PLUS, /* + */
  9010. CHAR_QUESTION_MARK, /* ? */
  9011. CHAR_RIGHT_CURLY_BRACE, /* } */
  9012. CHAR_RIGHT_PARENTHESES, /* ) */
  9013. CHAR_RIGHT_SQUARE_BRACKET /* ] */
  9014. } = /*@__PURE__*/ requireConstants();
  9015. const isPathSeparator = code => {
  9016. return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
  9017. };
  9018. const depth = token => {
  9019. if (token.isPrefix !== true) {
  9020. token.depth = token.isGlobstar ? Infinity : 1;
  9021. }
  9022. };
  9023. /**
  9024. * Quickly scans a glob pattern and returns an object with a handful of
  9025. * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
  9026. * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
  9027. * with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
  9028. *
  9029. * ```js
  9030. * const pm = require('picomatch');
  9031. * console.log(pm.scan('foo/bar/*.js'));
  9032. * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
  9033. * ```
  9034. * @param {String} `str`
  9035. * @param {Object} `options`
  9036. * @return {Object} Returns an object with tokens and regex source string.
  9037. * @api public
  9038. */
  9039. const scan = (input, options) => {
  9040. const opts = options || {};
  9041. const length = input.length - 1;
  9042. const scanToEnd = opts.parts === true || opts.scanToEnd === true;
  9043. const slashes = [];
  9044. const tokens = [];
  9045. const parts = [];
  9046. let str = input;
  9047. let index = -1;
  9048. let start = 0;
  9049. let lastIndex = 0;
  9050. let isBrace = false;
  9051. let isBracket = false;
  9052. let isGlob = false;
  9053. let isExtglob = false;
  9054. let isGlobstar = false;
  9055. let braceEscaped = false;
  9056. let backslashes = false;
  9057. let negated = false;
  9058. let negatedExtglob = false;
  9059. let finished = false;
  9060. let braces = 0;
  9061. let prev;
  9062. let code;
  9063. let token = { value: '', depth: 0, isGlob: false };
  9064. const eos = () => index >= length;
  9065. const peek = () => str.charCodeAt(index + 1);
  9066. const advance = () => {
  9067. prev = code;
  9068. return str.charCodeAt(++index);
  9069. };
  9070. while (index < length) {
  9071. code = advance();
  9072. let next;
  9073. if (code === CHAR_BACKWARD_SLASH) {
  9074. backslashes = token.backslashes = true;
  9075. code = advance();
  9076. if (code === CHAR_LEFT_CURLY_BRACE) {
  9077. braceEscaped = true;
  9078. }
  9079. continue;
  9080. }
  9081. if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
  9082. braces++;
  9083. while (eos() !== true && (code = advance())) {
  9084. if (code === CHAR_BACKWARD_SLASH) {
  9085. backslashes = token.backslashes = true;
  9086. advance();
  9087. continue;
  9088. }
  9089. if (code === CHAR_LEFT_CURLY_BRACE) {
  9090. braces++;
  9091. continue;
  9092. }
  9093. if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
  9094. isBrace = token.isBrace = true;
  9095. isGlob = token.isGlob = true;
  9096. finished = true;
  9097. if (scanToEnd === true) {
  9098. continue;
  9099. }
  9100. break;
  9101. }
  9102. if (braceEscaped !== true && code === CHAR_COMMA) {
  9103. isBrace = token.isBrace = true;
  9104. isGlob = token.isGlob = true;
  9105. finished = true;
  9106. if (scanToEnd === true) {
  9107. continue;
  9108. }
  9109. break;
  9110. }
  9111. if (code === CHAR_RIGHT_CURLY_BRACE) {
  9112. braces--;
  9113. if (braces === 0) {
  9114. braceEscaped = false;
  9115. isBrace = token.isBrace = true;
  9116. finished = true;
  9117. break;
  9118. }
  9119. }
  9120. }
  9121. if (scanToEnd === true) {
  9122. continue;
  9123. }
  9124. break;
  9125. }
  9126. if (code === CHAR_FORWARD_SLASH) {
  9127. slashes.push(index);
  9128. tokens.push(token);
  9129. token = { value: '', depth: 0, isGlob: false };
  9130. if (finished === true) continue;
  9131. if (prev === CHAR_DOT && index === (start + 1)) {
  9132. start += 2;
  9133. continue;
  9134. }
  9135. lastIndex = index + 1;
  9136. continue;
  9137. }
  9138. if (opts.noext !== true) {
  9139. const isExtglobChar = code === CHAR_PLUS
  9140. || code === CHAR_AT
  9141. || code === CHAR_ASTERISK
  9142. || code === CHAR_QUESTION_MARK
  9143. || code === CHAR_EXCLAMATION_MARK;
  9144. if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
  9145. isGlob = token.isGlob = true;
  9146. isExtglob = token.isExtglob = true;
  9147. finished = true;
  9148. if (code === CHAR_EXCLAMATION_MARK && index === start) {
  9149. negatedExtglob = true;
  9150. }
  9151. if (scanToEnd === true) {
  9152. while (eos() !== true && (code = advance())) {
  9153. if (code === CHAR_BACKWARD_SLASH) {
  9154. backslashes = token.backslashes = true;
  9155. code = advance();
  9156. continue;
  9157. }
  9158. if (code === CHAR_RIGHT_PARENTHESES) {
  9159. isGlob = token.isGlob = true;
  9160. finished = true;
  9161. break;
  9162. }
  9163. }
  9164. continue;
  9165. }
  9166. break;
  9167. }
  9168. }
  9169. if (code === CHAR_ASTERISK) {
  9170. if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
  9171. isGlob = token.isGlob = true;
  9172. finished = true;
  9173. if (scanToEnd === true) {
  9174. continue;
  9175. }
  9176. break;
  9177. }
  9178. if (code === CHAR_QUESTION_MARK) {
  9179. isGlob = token.isGlob = true;
  9180. finished = true;
  9181. if (scanToEnd === true) {
  9182. continue;
  9183. }
  9184. break;
  9185. }
  9186. if (code === CHAR_LEFT_SQUARE_BRACKET) {
  9187. while (eos() !== true && (next = advance())) {
  9188. if (next === CHAR_BACKWARD_SLASH) {
  9189. backslashes = token.backslashes = true;
  9190. advance();
  9191. continue;
  9192. }
  9193. if (next === CHAR_RIGHT_SQUARE_BRACKET) {
  9194. isBracket = token.isBracket = true;
  9195. isGlob = token.isGlob = true;
  9196. finished = true;
  9197. break;
  9198. }
  9199. }
  9200. if (scanToEnd === true) {
  9201. continue;
  9202. }
  9203. break;
  9204. }
  9205. if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
  9206. negated = token.negated = true;
  9207. start++;
  9208. continue;
  9209. }
  9210. if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
  9211. isGlob = token.isGlob = true;
  9212. if (scanToEnd === true) {
  9213. while (eos() !== true && (code = advance())) {
  9214. if (code === CHAR_LEFT_PARENTHESES) {
  9215. backslashes = token.backslashes = true;
  9216. code = advance();
  9217. continue;
  9218. }
  9219. if (code === CHAR_RIGHT_PARENTHESES) {
  9220. finished = true;
  9221. break;
  9222. }
  9223. }
  9224. continue;
  9225. }
  9226. break;
  9227. }
  9228. if (isGlob === true) {
  9229. finished = true;
  9230. if (scanToEnd === true) {
  9231. continue;
  9232. }
  9233. break;
  9234. }
  9235. }
  9236. if (opts.noext === true) {
  9237. isExtglob = false;
  9238. isGlob = false;
  9239. }
  9240. let base = str;
  9241. let prefix = '';
  9242. let glob = '';
  9243. if (start > 0) {
  9244. prefix = str.slice(0, start);
  9245. str = str.slice(start);
  9246. lastIndex -= start;
  9247. }
  9248. if (base && isGlob === true && lastIndex > 0) {
  9249. base = str.slice(0, lastIndex);
  9250. glob = str.slice(lastIndex);
  9251. } else if (isGlob === true) {
  9252. base = '';
  9253. glob = str;
  9254. } else {
  9255. base = str;
  9256. }
  9257. if (base && base !== '' && base !== '/' && base !== str) {
  9258. if (isPathSeparator(base.charCodeAt(base.length - 1))) {
  9259. base = base.slice(0, -1);
  9260. }
  9261. }
  9262. if (opts.unescape === true) {
  9263. if (glob) glob = utils.removeBackslashes(glob);
  9264. if (base && backslashes === true) {
  9265. base = utils.removeBackslashes(base);
  9266. }
  9267. }
  9268. const state = {
  9269. prefix,
  9270. input,
  9271. start,
  9272. base,
  9273. glob,
  9274. isBrace,
  9275. isBracket,
  9276. isGlob,
  9277. isExtglob,
  9278. isGlobstar,
  9279. negated,
  9280. negatedExtglob
  9281. };
  9282. if (opts.tokens === true) {
  9283. state.maxDepth = 0;
  9284. if (!isPathSeparator(code)) {
  9285. tokens.push(token);
  9286. }
  9287. state.tokens = tokens;
  9288. }
  9289. if (opts.parts === true || opts.tokens === true) {
  9290. let prevIndex;
  9291. for (let idx = 0; idx < slashes.length; idx++) {
  9292. const n = prevIndex ? prevIndex + 1 : start;
  9293. const i = slashes[idx];
  9294. const value = input.slice(n, i);
  9295. if (opts.tokens) {
  9296. if (idx === 0 && start !== 0) {
  9297. tokens[idx].isPrefix = true;
  9298. tokens[idx].value = prefix;
  9299. } else {
  9300. tokens[idx].value = value;
  9301. }
  9302. depth(tokens[idx]);
  9303. state.maxDepth += tokens[idx].depth;
  9304. }
  9305. if (idx !== 0 || value !== '') {
  9306. parts.push(value);
  9307. }
  9308. prevIndex = i;
  9309. }
  9310. if (prevIndex && prevIndex + 1 < input.length) {
  9311. const value = input.slice(prevIndex + 1);
  9312. parts.push(value);
  9313. if (opts.tokens) {
  9314. tokens[tokens.length - 1].value = value;
  9315. depth(tokens[tokens.length - 1]);
  9316. state.maxDepth += tokens[tokens.length - 1].depth;
  9317. }
  9318. }
  9319. state.slashes = slashes;
  9320. state.parts = parts;
  9321. }
  9322. return state;
  9323. };
  9324. scan_1 = scan;
  9325. return scan_1;
  9326. }
  9327. var parse_1;
  9328. var hasRequiredParse;
  9329. function requireParse () {
  9330. if (hasRequiredParse) return parse_1;
  9331. hasRequiredParse = 1;
  9332. const constants = /*@__PURE__*/ requireConstants();
  9333. const utils = /*@__PURE__*/ requireUtils();
  9334. /**
  9335. * Constants
  9336. */
  9337. const {
  9338. MAX_LENGTH,
  9339. POSIX_REGEX_SOURCE,
  9340. REGEX_NON_SPECIAL_CHARS,
  9341. REGEX_SPECIAL_CHARS_BACKREF,
  9342. REPLACEMENTS
  9343. } = constants;
  9344. /**
  9345. * Helpers
  9346. */
  9347. const expandRange = (args, options) => {
  9348. if (typeof options.expandRange === 'function') {
  9349. return options.expandRange(...args, options);
  9350. }
  9351. args.sort();
  9352. const value = `[${args.join('-')}]`;
  9353. return value;
  9354. };
  9355. /**
  9356. * Create the message for a syntax error
  9357. */
  9358. const syntaxError = (type, char) => {
  9359. return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
  9360. };
  9361. const splitTopLevel = input => {
  9362. const parts = [];
  9363. let bracket = 0;
  9364. let paren = 0;
  9365. let quote = 0;
  9366. let value = '';
  9367. let escaped = false;
  9368. for (const ch of input) {
  9369. if (escaped === true) {
  9370. value += ch;
  9371. escaped = false;
  9372. continue;
  9373. }
  9374. if (ch === '\\') {
  9375. value += ch;
  9376. escaped = true;
  9377. continue;
  9378. }
  9379. if (ch === '"') {
  9380. quote = quote === 1 ? 0 : 1;
  9381. value += ch;
  9382. continue;
  9383. }
  9384. if (quote === 0) {
  9385. if (ch === '[') {
  9386. bracket++;
  9387. } else if (ch === ']' && bracket > 0) {
  9388. bracket--;
  9389. } else if (bracket === 0) {
  9390. if (ch === '(') {
  9391. paren++;
  9392. } else if (ch === ')' && paren > 0) {
  9393. paren--;
  9394. } else if (ch === '|' && paren === 0) {
  9395. parts.push(value);
  9396. value = '';
  9397. continue;
  9398. }
  9399. }
  9400. }
  9401. value += ch;
  9402. }
  9403. parts.push(value);
  9404. return parts;
  9405. };
  9406. const isPlainBranch = branch => {
  9407. let escaped = false;
  9408. for (const ch of branch) {
  9409. if (escaped === true) {
  9410. escaped = false;
  9411. continue;
  9412. }
  9413. if (ch === '\\') {
  9414. escaped = true;
  9415. continue;
  9416. }
  9417. if (/[?*+@!()[\]{}]/.test(ch)) {
  9418. return false;
  9419. }
  9420. }
  9421. return true;
  9422. };
  9423. const normalizeSimpleBranch = branch => {
  9424. let value = branch.trim();
  9425. let changed = true;
  9426. while (changed === true) {
  9427. changed = false;
  9428. if (/^@\([^\\()[\]{}|]+\)$/.test(value)) {
  9429. value = value.slice(2, -1);
  9430. changed = true;
  9431. }
  9432. }
  9433. if (!isPlainBranch(value)) {
  9434. return;
  9435. }
  9436. return value.replace(/\\(.)/g, '$1');
  9437. };
  9438. const hasRepeatedCharPrefixOverlap = branches => {
  9439. const values = branches.map(normalizeSimpleBranch).filter(Boolean);
  9440. for (let i = 0; i < values.length; i++) {
  9441. for (let j = i + 1; j < values.length; j++) {
  9442. const a = values[i];
  9443. const b = values[j];
  9444. const char = a[0];
  9445. if (!char || a !== char.repeat(a.length) || b !== char.repeat(b.length)) {
  9446. continue;
  9447. }
  9448. if (a === b || a.startsWith(b) || b.startsWith(a)) {
  9449. return true;
  9450. }
  9451. }
  9452. }
  9453. return false;
  9454. };
  9455. const parseRepeatedExtglob = (pattern, requireEnd = true) => {
  9456. if ((pattern[0] !== '+' && pattern[0] !== '*') || pattern[1] !== '(') {
  9457. return;
  9458. }
  9459. let bracket = 0;
  9460. let paren = 0;
  9461. let quote = 0;
  9462. let escaped = false;
  9463. for (let i = 1; i < pattern.length; i++) {
  9464. const ch = pattern[i];
  9465. if (escaped === true) {
  9466. escaped = false;
  9467. continue;
  9468. }
  9469. if (ch === '\\') {
  9470. escaped = true;
  9471. continue;
  9472. }
  9473. if (ch === '"') {
  9474. quote = quote === 1 ? 0 : 1;
  9475. continue;
  9476. }
  9477. if (quote === 1) {
  9478. continue;
  9479. }
  9480. if (ch === '[') {
  9481. bracket++;
  9482. continue;
  9483. }
  9484. if (ch === ']' && bracket > 0) {
  9485. bracket--;
  9486. continue;
  9487. }
  9488. if (bracket > 0) {
  9489. continue;
  9490. }
  9491. if (ch === '(') {
  9492. paren++;
  9493. continue;
  9494. }
  9495. if (ch === ')') {
  9496. paren--;
  9497. if (paren === 0) {
  9498. if (requireEnd === true && i !== pattern.length - 1) {
  9499. return;
  9500. }
  9501. return {
  9502. type: pattern[0],
  9503. body: pattern.slice(2, i),
  9504. end: i
  9505. };
  9506. }
  9507. }
  9508. }
  9509. };
  9510. const getStarExtglobSequenceOutput = pattern => {
  9511. let index = 0;
  9512. const chars = [];
  9513. while (index < pattern.length) {
  9514. const match = parseRepeatedExtglob(pattern.slice(index), false);
  9515. if (!match || match.type !== '*') {
  9516. return;
  9517. }
  9518. const branches = splitTopLevel(match.body).map(branch => branch.trim());
  9519. if (branches.length !== 1) {
  9520. return;
  9521. }
  9522. const branch = normalizeSimpleBranch(branches[0]);
  9523. if (!branch || branch.length !== 1) {
  9524. return;
  9525. }
  9526. chars.push(branch);
  9527. index += match.end + 1;
  9528. }
  9529. if (chars.length < 1) {
  9530. return;
  9531. }
  9532. const source = chars.length === 1
  9533. ? utils.escapeRegex(chars[0])
  9534. : `[${chars.map(ch => utils.escapeRegex(ch)).join('')}]`;
  9535. return `${source}*`;
  9536. };
  9537. const repeatedExtglobRecursion = pattern => {
  9538. let depth = 0;
  9539. let value = pattern.trim();
  9540. let match = parseRepeatedExtglob(value);
  9541. while (match) {
  9542. depth++;
  9543. value = match.body.trim();
  9544. match = parseRepeatedExtglob(value);
  9545. }
  9546. return depth;
  9547. };
  9548. const analyzeRepeatedExtglob = (body, options) => {
  9549. if (options.maxExtglobRecursion === false) {
  9550. return { risky: false };
  9551. }
  9552. const max =
  9553. typeof options.maxExtglobRecursion === 'number'
  9554. ? options.maxExtglobRecursion
  9555. : constants.DEFAULT_MAX_EXTGLOB_RECURSION;
  9556. const branches = splitTopLevel(body).map(branch => branch.trim());
  9557. if (branches.length > 1) {
  9558. if (
  9559. branches.some(branch => branch === '') ||
  9560. branches.some(branch => /^[*?]+$/.test(branch)) ||
  9561. hasRepeatedCharPrefixOverlap(branches)
  9562. ) {
  9563. return { risky: true };
  9564. }
  9565. }
  9566. for (const branch of branches) {
  9567. const safeOutput = getStarExtglobSequenceOutput(branch);
  9568. if (safeOutput) {
  9569. return { risky: true, safeOutput };
  9570. }
  9571. if (repeatedExtglobRecursion(branch) > max) {
  9572. return { risky: true };
  9573. }
  9574. }
  9575. return { risky: false };
  9576. };
  9577. /**
  9578. * Parse the given input string.
  9579. * @param {String} input
  9580. * @param {Object} options
  9581. * @return {Object}
  9582. */
  9583. const parse = (input, options) => {
  9584. if (typeof input !== 'string') {
  9585. throw new TypeError('Expected a string');
  9586. }
  9587. input = REPLACEMENTS[input] || input;
  9588. const opts = { ...options };
  9589. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  9590. let len = input.length;
  9591. if (len > max) {
  9592. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  9593. }
  9594. const bos = { type: 'bos', value: '', output: opts.prepend || '' };
  9595. const tokens = [bos];
  9596. const capture = opts.capture ? '' : '?:';
  9597. // create constants based on platform, for windows or posix
  9598. const PLATFORM_CHARS = constants.globChars(opts.windows);
  9599. const EXTGLOB_CHARS = constants.extglobChars(PLATFORM_CHARS);
  9600. const {
  9601. DOT_LITERAL,
  9602. PLUS_LITERAL,
  9603. SLASH_LITERAL,
  9604. ONE_CHAR,
  9605. DOTS_SLASH,
  9606. NO_DOT,
  9607. NO_DOT_SLASH,
  9608. NO_DOTS_SLASH,
  9609. QMARK,
  9610. QMARK_NO_DOT,
  9611. STAR,
  9612. START_ANCHOR
  9613. } = PLATFORM_CHARS;
  9614. const globstar = opts => {
  9615. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  9616. };
  9617. const nodot = opts.dot ? '' : NO_DOT;
  9618. const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
  9619. let star = opts.bash === true ? globstar(opts) : STAR;
  9620. if (opts.capture) {
  9621. star = `(${star})`;
  9622. }
  9623. // minimatch options support
  9624. if (typeof opts.noext === 'boolean') {
  9625. opts.noextglob = opts.noext;
  9626. }
  9627. const state = {
  9628. input,
  9629. index: -1,
  9630. start: 0,
  9631. dot: opts.dot === true,
  9632. consumed: '',
  9633. output: '',
  9634. prefix: '',
  9635. backtrack: false,
  9636. negated: false,
  9637. brackets: 0,
  9638. braces: 0,
  9639. parens: 0,
  9640. quotes: 0,
  9641. globstar: false,
  9642. tokens
  9643. };
  9644. input = utils.removePrefix(input, state);
  9645. len = input.length;
  9646. const extglobs = [];
  9647. const braces = [];
  9648. const stack = [];
  9649. let prev = bos;
  9650. let value;
  9651. /**
  9652. * Tokenizing helpers
  9653. */
  9654. const eos = () => state.index === len - 1;
  9655. const peek = state.peek = (n = 1) => input[state.index + n];
  9656. const advance = state.advance = () => input[++state.index] || '';
  9657. const remaining = () => input.slice(state.index + 1);
  9658. const consume = (value = '', num = 0) => {
  9659. state.consumed += value;
  9660. state.index += num;
  9661. };
  9662. const append = token => {
  9663. state.output += token.output != null ? token.output : token.value;
  9664. consume(token.value);
  9665. };
  9666. const negate = () => {
  9667. let count = 1;
  9668. while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
  9669. advance();
  9670. state.start++;
  9671. count++;
  9672. }
  9673. if (count % 2 === 0) {
  9674. return false;
  9675. }
  9676. state.negated = true;
  9677. state.start++;
  9678. return true;
  9679. };
  9680. const increment = type => {
  9681. state[type]++;
  9682. stack.push(type);
  9683. };
  9684. const decrement = type => {
  9685. state[type]--;
  9686. stack.pop();
  9687. };
  9688. /**
  9689. * Push tokens onto the tokens array. This helper speeds up
  9690. * tokenizing by 1) helping us avoid backtracking as much as possible,
  9691. * and 2) helping us avoid creating extra tokens when consecutive
  9692. * characters are plain text. This improves performance and simplifies
  9693. * lookbehinds.
  9694. */
  9695. const push = tok => {
  9696. if (prev.type === 'globstar') {
  9697. const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
  9698. const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));
  9699. if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
  9700. state.output = state.output.slice(0, -prev.output.length);
  9701. prev.type = 'star';
  9702. prev.value = '*';
  9703. prev.output = star;
  9704. state.output += prev.output;
  9705. }
  9706. }
  9707. if (extglobs.length && tok.type !== 'paren') {
  9708. extglobs[extglobs.length - 1].inner += tok.value;
  9709. }
  9710. if (tok.value || tok.output) append(tok);
  9711. if (prev && prev.type === 'text' && tok.type === 'text') {
  9712. prev.output = (prev.output || prev.value) + tok.value;
  9713. prev.value += tok.value;
  9714. return;
  9715. }
  9716. tok.prev = prev;
  9717. tokens.push(tok);
  9718. prev = tok;
  9719. };
  9720. const extglobOpen = (type, value) => {
  9721. const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };
  9722. token.prev = prev;
  9723. token.parens = state.parens;
  9724. token.output = state.output;
  9725. token.startIndex = state.index;
  9726. token.tokensIndex = tokens.length;
  9727. const output = (opts.capture ? '(' : '') + token.open;
  9728. increment('parens');
  9729. push({ type, value, output: state.output ? '' : ONE_CHAR });
  9730. push({ type: 'paren', extglob: true, value: advance(), output });
  9731. extglobs.push(token);
  9732. };
  9733. const extglobClose = token => {
  9734. const literal = input.slice(token.startIndex, state.index + 1);
  9735. const body = input.slice(token.startIndex + 2, state.index);
  9736. const analysis = analyzeRepeatedExtglob(body, opts);
  9737. if ((token.type === 'plus' || token.type === 'star') && analysis.risky) {
  9738. const safeOutput = analysis.safeOutput
  9739. ? (token.output ? '' : ONE_CHAR) + (opts.capture ? `(${analysis.safeOutput})` : analysis.safeOutput)
  9740. : undefined;
  9741. const open = tokens[token.tokensIndex];
  9742. open.type = 'text';
  9743. open.value = literal;
  9744. open.output = safeOutput || utils.escapeRegex(literal);
  9745. for (let i = token.tokensIndex + 1; i < tokens.length; i++) {
  9746. tokens[i].value = '';
  9747. tokens[i].output = '';
  9748. delete tokens[i].suffix;
  9749. }
  9750. state.output = token.output + open.output;
  9751. state.backtrack = true;
  9752. push({ type: 'paren', extglob: true, value, output: '' });
  9753. decrement('parens');
  9754. return;
  9755. }
  9756. let output = token.close + (opts.capture ? ')' : '');
  9757. let rest;
  9758. if (token.type === 'negate') {
  9759. let extglobStar = star;
  9760. if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
  9761. extglobStar = globstar(opts);
  9762. }
  9763. if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
  9764. output = token.close = `)$))${extglobStar}`;
  9765. }
  9766. if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
  9767. // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis.
  9768. // In this case, we need to parse the string and use it in the output of the original pattern.
  9769. // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`.
  9770. //
  9771. // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`.
  9772. const expression = parse(rest, { ...options, fastpaths: false }).output;
  9773. output = token.close = `)${expression})${extglobStar})`;
  9774. }
  9775. if (token.prev.type === 'bos') {
  9776. state.negatedExtglob = true;
  9777. }
  9778. }
  9779. push({ type: 'paren', extglob: true, value, output });
  9780. decrement('parens');
  9781. };
  9782. /**
  9783. * Fast paths
  9784. */
  9785. if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
  9786. let backslashes = false;
  9787. let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
  9788. if (first === '\\') {
  9789. backslashes = true;
  9790. return m;
  9791. }
  9792. if (first === '?') {
  9793. if (esc) {
  9794. return esc + first + (rest ? QMARK.repeat(rest.length) : '');
  9795. }
  9796. if (index === 0) {
  9797. return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
  9798. }
  9799. return QMARK.repeat(chars.length);
  9800. }
  9801. if (first === '.') {
  9802. return DOT_LITERAL.repeat(chars.length);
  9803. }
  9804. if (first === '*') {
  9805. if (esc) {
  9806. return esc + first + (rest ? star : '');
  9807. }
  9808. return star;
  9809. }
  9810. return esc ? m : `\\${m}`;
  9811. });
  9812. if (backslashes === true) {
  9813. if (opts.unescape === true) {
  9814. output = output.replace(/\\/g, '');
  9815. } else {
  9816. output = output.replace(/\\+/g, m => {
  9817. return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
  9818. });
  9819. }
  9820. }
  9821. if (output === input && opts.contains === true) {
  9822. state.output = input;
  9823. return state;
  9824. }
  9825. state.output = utils.wrapOutput(output, state, options);
  9826. return state;
  9827. }
  9828. /**
  9829. * Tokenize input until we reach end-of-string
  9830. */
  9831. while (!eos()) {
  9832. value = advance();
  9833. if (value === '\u0000') {
  9834. continue;
  9835. }
  9836. /**
  9837. * Escaped characters
  9838. */
  9839. if (value === '\\') {
  9840. const next = peek();
  9841. if (next === '/' && opts.bash !== true) {
  9842. continue;
  9843. }
  9844. if (next === '.' || next === ';') {
  9845. continue;
  9846. }
  9847. if (!next) {
  9848. value += '\\';
  9849. push({ type: 'text', value });
  9850. continue;
  9851. }
  9852. // collapse slashes to reduce potential for exploits
  9853. const match = /^\\+/.exec(remaining());
  9854. let slashes = 0;
  9855. if (match && match[0].length > 2) {
  9856. slashes = match[0].length;
  9857. state.index += slashes;
  9858. if (slashes % 2 !== 0) {
  9859. value += '\\';
  9860. }
  9861. }
  9862. if (opts.unescape === true) {
  9863. value = advance();
  9864. } else {
  9865. value += advance();
  9866. }
  9867. if (state.brackets === 0) {
  9868. push({ type: 'text', value });
  9869. continue;
  9870. }
  9871. }
  9872. /**
  9873. * If we're inside a regex character class, continue
  9874. * until we reach the closing bracket.
  9875. */
  9876. if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
  9877. if (opts.posix !== false && value === ':') {
  9878. const inner = prev.value.slice(1);
  9879. if (inner.includes('[')) {
  9880. prev.posix = true;
  9881. if (inner.includes(':')) {
  9882. const idx = prev.value.lastIndexOf('[');
  9883. const pre = prev.value.slice(0, idx);
  9884. const rest = prev.value.slice(idx + 2);
  9885. const posix = POSIX_REGEX_SOURCE[rest];
  9886. if (posix) {
  9887. prev.value = pre + posix;
  9888. state.backtrack = true;
  9889. advance();
  9890. if (!bos.output && tokens.indexOf(prev) === 1) {
  9891. bos.output = ONE_CHAR;
  9892. }
  9893. continue;
  9894. }
  9895. }
  9896. }
  9897. }
  9898. if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
  9899. value = `\\${value}`;
  9900. }
  9901. if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
  9902. value = `\\${value}`;
  9903. }
  9904. if (opts.posix === true && value === '!' && prev.value === '[') {
  9905. value = '^';
  9906. }
  9907. prev.value += value;
  9908. append({ value });
  9909. continue;
  9910. }
  9911. /**
  9912. * If we're inside a quoted string, continue
  9913. * until we reach the closing double quote.
  9914. */
  9915. if (state.quotes === 1 && value !== '"') {
  9916. value = utils.escapeRegex(value);
  9917. prev.value += value;
  9918. append({ value });
  9919. continue;
  9920. }
  9921. /**
  9922. * Double quotes
  9923. */
  9924. if (value === '"') {
  9925. state.quotes = state.quotes === 1 ? 0 : 1;
  9926. if (opts.keepQuotes === true) {
  9927. push({ type: 'text', value });
  9928. }
  9929. continue;
  9930. }
  9931. /**
  9932. * Parentheses
  9933. */
  9934. if (value === '(') {
  9935. increment('parens');
  9936. push({ type: 'paren', value });
  9937. continue;
  9938. }
  9939. if (value === ')') {
  9940. if (state.parens === 0 && opts.strictBrackets === true) {
  9941. throw new SyntaxError(syntaxError('opening', '('));
  9942. }
  9943. const extglob = extglobs[extglobs.length - 1];
  9944. if (extglob && state.parens === extglob.parens + 1) {
  9945. extglobClose(extglobs.pop());
  9946. continue;
  9947. }
  9948. push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
  9949. decrement('parens');
  9950. continue;
  9951. }
  9952. /**
  9953. * Square brackets
  9954. */
  9955. if (value === '[') {
  9956. if (opts.nobracket === true || !remaining().includes(']')) {
  9957. if (opts.nobracket !== true && opts.strictBrackets === true) {
  9958. throw new SyntaxError(syntaxError('closing', ']'));
  9959. }
  9960. value = `\\${value}`;
  9961. } else {
  9962. increment('brackets');
  9963. }
  9964. push({ type: 'bracket', value });
  9965. continue;
  9966. }
  9967. if (value === ']') {
  9968. if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
  9969. push({ type: 'text', value, output: `\\${value}` });
  9970. continue;
  9971. }
  9972. if (state.brackets === 0) {
  9973. if (opts.strictBrackets === true) {
  9974. throw new SyntaxError(syntaxError('opening', '['));
  9975. }
  9976. push({ type: 'text', value, output: `\\${value}` });
  9977. continue;
  9978. }
  9979. decrement('brackets');
  9980. const prevValue = prev.value.slice(1);
  9981. if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
  9982. value = `/${value}`;
  9983. }
  9984. prev.value += value;
  9985. append({ value });
  9986. // when literal brackets are explicitly disabled
  9987. // assume we should match with a regex character class
  9988. if (opts.literalBrackets === false || utils.hasRegexChars(prevValue)) {
  9989. continue;
  9990. }
  9991. const escaped = utils.escapeRegex(prev.value);
  9992. state.output = state.output.slice(0, -prev.value.length);
  9993. // when literal brackets are explicitly enabled
  9994. // assume we should escape the brackets to match literal characters
  9995. if (opts.literalBrackets === true) {
  9996. state.output += escaped;
  9997. prev.value = escaped;
  9998. continue;
  9999. }
  10000. // when the user specifies nothing, try to match both
  10001. prev.value = `(${capture}${escaped}|${prev.value})`;
  10002. state.output += prev.value;
  10003. continue;
  10004. }
  10005. /**
  10006. * Braces
  10007. */
  10008. if (value === '{' && opts.nobrace !== true) {
  10009. increment('braces');
  10010. const open = {
  10011. type: 'brace',
  10012. value,
  10013. output: '(',
  10014. outputIndex: state.output.length,
  10015. tokensIndex: state.tokens.length
  10016. };
  10017. braces.push(open);
  10018. push(open);
  10019. continue;
  10020. }
  10021. if (value === '}') {
  10022. const brace = braces[braces.length - 1];
  10023. if (opts.nobrace === true || !brace) {
  10024. push({ type: 'text', value, output: value });
  10025. continue;
  10026. }
  10027. let output = ')';
  10028. if (brace.dots === true) {
  10029. const arr = tokens.slice();
  10030. const range = [];
  10031. for (let i = arr.length - 1; i >= 0; i--) {
  10032. tokens.pop();
  10033. if (arr[i].type === 'brace') {
  10034. break;
  10035. }
  10036. if (arr[i].type !== 'dots') {
  10037. range.unshift(arr[i].value);
  10038. }
  10039. }
  10040. output = expandRange(range, opts);
  10041. state.backtrack = true;
  10042. }
  10043. if (brace.comma !== true && brace.dots !== true) {
  10044. const out = state.output.slice(0, brace.outputIndex);
  10045. const toks = state.tokens.slice(brace.tokensIndex);
  10046. brace.value = brace.output = '\\{';
  10047. value = output = '\\}';
  10048. state.output = out;
  10049. for (const t of toks) {
  10050. state.output += (t.output || t.value);
  10051. }
  10052. }
  10053. push({ type: 'brace', value, output });
  10054. decrement('braces');
  10055. braces.pop();
  10056. continue;
  10057. }
  10058. /**
  10059. * Pipes
  10060. */
  10061. if (value === '|') {
  10062. if (extglobs.length > 0) {
  10063. extglobs[extglobs.length - 1].conditions++;
  10064. }
  10065. push({ type: 'text', value });
  10066. continue;
  10067. }
  10068. /**
  10069. * Commas
  10070. */
  10071. if (value === ',') {
  10072. let output = value;
  10073. const brace = braces[braces.length - 1];
  10074. if (brace && stack[stack.length - 1] === 'braces') {
  10075. brace.comma = true;
  10076. output = '|';
  10077. }
  10078. push({ type: 'comma', value, output });
  10079. continue;
  10080. }
  10081. /**
  10082. * Slashes
  10083. */
  10084. if (value === '/') {
  10085. // if the beginning of the glob is "./", advance the start
  10086. // to the current index, and don't add the "./" characters
  10087. // to the state. This greatly simplifies lookbehinds when
  10088. // checking for BOS characters like "!" and "." (not "./")
  10089. if (prev.type === 'dot' && state.index === state.start + 1) {
  10090. state.start = state.index + 1;
  10091. state.consumed = '';
  10092. state.output = '';
  10093. tokens.pop();
  10094. prev = bos; // reset "prev" to the first token
  10095. continue;
  10096. }
  10097. push({ type: 'slash', value, output: SLASH_LITERAL });
  10098. continue;
  10099. }
  10100. /**
  10101. * Dots
  10102. */
  10103. if (value === '.') {
  10104. if (state.braces > 0 && prev.type === 'dot') {
  10105. if (prev.value === '.') prev.output = DOT_LITERAL;
  10106. const brace = braces[braces.length - 1];
  10107. prev.type = 'dots';
  10108. prev.output += value;
  10109. prev.value += value;
  10110. brace.dots = true;
  10111. continue;
  10112. }
  10113. if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
  10114. push({ type: 'text', value, output: DOT_LITERAL });
  10115. continue;
  10116. }
  10117. push({ type: 'dot', value, output: DOT_LITERAL });
  10118. continue;
  10119. }
  10120. /**
  10121. * Question marks
  10122. */
  10123. if (value === '?') {
  10124. const isGroup = prev && prev.value === '(';
  10125. if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  10126. extglobOpen('qmark', value);
  10127. continue;
  10128. }
  10129. if (prev && prev.type === 'paren') {
  10130. const next = peek();
  10131. let output = value;
  10132. if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {
  10133. output = `\\${value}`;
  10134. }
  10135. push({ type: 'text', value, output });
  10136. continue;
  10137. }
  10138. if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
  10139. push({ type: 'qmark', value, output: QMARK_NO_DOT });
  10140. continue;
  10141. }
  10142. push({ type: 'qmark', value, output: QMARK });
  10143. continue;
  10144. }
  10145. /**
  10146. * Exclamation
  10147. */
  10148. if (value === '!') {
  10149. if (opts.noextglob !== true && peek() === '(') {
  10150. if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
  10151. extglobOpen('negate', value);
  10152. continue;
  10153. }
  10154. }
  10155. if (opts.nonegate !== true && state.index === 0) {
  10156. negate();
  10157. continue;
  10158. }
  10159. }
  10160. /**
  10161. * Plus
  10162. */
  10163. if (value === '+') {
  10164. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  10165. extglobOpen('plus', value);
  10166. continue;
  10167. }
  10168. if ((prev && prev.value === '(') || opts.regex === false) {
  10169. push({ type: 'plus', value, output: PLUS_LITERAL });
  10170. continue;
  10171. }
  10172. if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {
  10173. push({ type: 'plus', value });
  10174. continue;
  10175. }
  10176. push({ type: 'plus', value: PLUS_LITERAL });
  10177. continue;
  10178. }
  10179. /**
  10180. * Plain text
  10181. */
  10182. if (value === '@') {
  10183. if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
  10184. push({ type: 'at', extglob: true, value, output: '' });
  10185. continue;
  10186. }
  10187. push({ type: 'text', value });
  10188. continue;
  10189. }
  10190. /**
  10191. * Plain text
  10192. */
  10193. if (value !== '*') {
  10194. if (value === '$' || value === '^') {
  10195. value = `\\${value}`;
  10196. }
  10197. const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
  10198. if (match) {
  10199. value += match[0];
  10200. state.index += match[0].length;
  10201. }
  10202. push({ type: 'text', value });
  10203. continue;
  10204. }
  10205. /**
  10206. * Stars
  10207. */
  10208. if (prev && (prev.type === 'globstar' || prev.star === true)) {
  10209. prev.type = 'star';
  10210. prev.star = true;
  10211. prev.value += value;
  10212. prev.output = star;
  10213. state.backtrack = true;
  10214. state.globstar = true;
  10215. consume(value);
  10216. continue;
  10217. }
  10218. let rest = remaining();
  10219. if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
  10220. extglobOpen('star', value);
  10221. continue;
  10222. }
  10223. if (prev.type === 'star') {
  10224. if (opts.noglobstar === true) {
  10225. consume(value);
  10226. continue;
  10227. }
  10228. const prior = prev.prev;
  10229. const before = prior.prev;
  10230. const isStart = prior.type === 'slash' || prior.type === 'bos';
  10231. const afterStar = before && (before.type === 'star' || before.type === 'globstar');
  10232. if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {
  10233. push({ type: 'star', value, output: '' });
  10234. continue;
  10235. }
  10236. const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
  10237. const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
  10238. if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
  10239. push({ type: 'star', value, output: '' });
  10240. continue;
  10241. }
  10242. // strip consecutive `/**/`
  10243. while (rest.slice(0, 3) === '/**') {
  10244. const after = input[state.index + 4];
  10245. if (after && after !== '/') {
  10246. break;
  10247. }
  10248. rest = rest.slice(3);
  10249. consume('/**', 3);
  10250. }
  10251. if (prior.type === 'bos' && eos()) {
  10252. prev.type = 'globstar';
  10253. prev.value += value;
  10254. prev.output = globstar(opts);
  10255. state.output = prev.output;
  10256. state.globstar = true;
  10257. consume(value);
  10258. continue;
  10259. }
  10260. if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
  10261. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  10262. prior.output = `(?:${prior.output}`;
  10263. prev.type = 'globstar';
  10264. prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
  10265. prev.value += value;
  10266. state.globstar = true;
  10267. state.output += prior.output + prev.output;
  10268. consume(value);
  10269. continue;
  10270. }
  10271. if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
  10272. const end = rest[1] !== void 0 ? '|$' : '';
  10273. state.output = state.output.slice(0, -(prior.output + prev.output).length);
  10274. prior.output = `(?:${prior.output}`;
  10275. prev.type = 'globstar';
  10276. prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
  10277. prev.value += value;
  10278. state.output += prior.output + prev.output;
  10279. state.globstar = true;
  10280. consume(value + advance());
  10281. push({ type: 'slash', value: '/', output: '' });
  10282. continue;
  10283. }
  10284. if (prior.type === 'bos' && rest[0] === '/') {
  10285. prev.type = 'globstar';
  10286. prev.value += value;
  10287. prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
  10288. state.output = prev.output;
  10289. state.globstar = true;
  10290. consume(value + advance());
  10291. push({ type: 'slash', value: '/', output: '' });
  10292. continue;
  10293. }
  10294. // remove single star from output
  10295. state.output = state.output.slice(0, -prev.output.length);
  10296. // reset previous token to globstar
  10297. prev.type = 'globstar';
  10298. prev.output = globstar(opts);
  10299. prev.value += value;
  10300. // reset output with globstar
  10301. state.output += prev.output;
  10302. state.globstar = true;
  10303. consume(value);
  10304. continue;
  10305. }
  10306. const token = { type: 'star', value, output: star };
  10307. if (opts.bash === true) {
  10308. token.output = '.*?';
  10309. if (prev.type === 'bos' || prev.type === 'slash') {
  10310. token.output = nodot + token.output;
  10311. }
  10312. push(token);
  10313. continue;
  10314. }
  10315. if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
  10316. token.output = value;
  10317. push(token);
  10318. continue;
  10319. }
  10320. if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
  10321. if (prev.type === 'dot') {
  10322. state.output += NO_DOT_SLASH;
  10323. prev.output += NO_DOT_SLASH;
  10324. } else if (opts.dot === true) {
  10325. state.output += NO_DOTS_SLASH;
  10326. prev.output += NO_DOTS_SLASH;
  10327. } else {
  10328. state.output += nodot;
  10329. prev.output += nodot;
  10330. }
  10331. if (peek() !== '*') {
  10332. state.output += ONE_CHAR;
  10333. prev.output += ONE_CHAR;
  10334. }
  10335. }
  10336. push(token);
  10337. }
  10338. while (state.brackets > 0) {
  10339. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
  10340. state.output = utils.escapeLast(state.output, '[');
  10341. decrement('brackets');
  10342. }
  10343. while (state.parens > 0) {
  10344. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
  10345. state.output = utils.escapeLast(state.output, '(');
  10346. decrement('parens');
  10347. }
  10348. while (state.braces > 0) {
  10349. if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
  10350. state.output = utils.escapeLast(state.output, '{');
  10351. decrement('braces');
  10352. }
  10353. if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
  10354. push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
  10355. }
  10356. // rebuild the output if we had to backtrack at any point
  10357. if (state.backtrack === true) {
  10358. state.output = '';
  10359. for (const token of state.tokens) {
  10360. state.output += token.output != null ? token.output : token.value;
  10361. if (token.suffix) {
  10362. state.output += token.suffix;
  10363. }
  10364. }
  10365. }
  10366. return state;
  10367. };
  10368. /**
  10369. * Fast paths for creating regular expressions for common glob patterns.
  10370. * This can significantly speed up processing and has very little downside
  10371. * impact when none of the fast paths match.
  10372. */
  10373. parse.fastpaths = (input, options) => {
  10374. const opts = { ...options };
  10375. const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  10376. const len = input.length;
  10377. if (len > max) {
  10378. throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
  10379. }
  10380. input = REPLACEMENTS[input] || input;
  10381. // create constants based on platform, for windows or posix
  10382. const {
  10383. DOT_LITERAL,
  10384. SLASH_LITERAL,
  10385. ONE_CHAR,
  10386. DOTS_SLASH,
  10387. NO_DOT,
  10388. NO_DOTS,
  10389. NO_DOTS_SLASH,
  10390. STAR,
  10391. START_ANCHOR
  10392. } = constants.globChars(opts.windows);
  10393. const nodot = opts.dot ? NO_DOTS : NO_DOT;
  10394. const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
  10395. const capture = opts.capture ? '' : '?:';
  10396. const state = { negated: false, prefix: '' };
  10397. let star = opts.bash === true ? '.*?' : STAR;
  10398. if (opts.capture) {
  10399. star = `(${star})`;
  10400. }
  10401. const globstar = opts => {
  10402. if (opts.noglobstar === true) return star;
  10403. return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
  10404. };
  10405. const create = str => {
  10406. switch (str) {
  10407. case '*':
  10408. return `${nodot}${ONE_CHAR}${star}`;
  10409. case '.*':
  10410. return `${DOT_LITERAL}${ONE_CHAR}${star}`;
  10411. case '*.*':
  10412. return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  10413. case '*/*':
  10414. return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
  10415. case '**':
  10416. return nodot + globstar(opts);
  10417. case '**/*':
  10418. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
  10419. case '**/*.*':
  10420. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
  10421. case '**/.*':
  10422. return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
  10423. default: {
  10424. const match = /^(.*?)\.(\w+)$/.exec(str);
  10425. if (!match) return;
  10426. const source = create(match[1]);
  10427. if (!source) return;
  10428. return source + DOT_LITERAL + match[2];
  10429. }
  10430. }
  10431. };
  10432. const output = utils.removePrefix(input, state);
  10433. let source = create(output);
  10434. if (source && opts.strictSlashes !== true) {
  10435. source += `${SLASH_LITERAL}?`;
  10436. }
  10437. return source;
  10438. };
  10439. parse_1 = parse;
  10440. return parse_1;
  10441. }
  10442. var picomatch_1$1;
  10443. var hasRequiredPicomatch$1;
  10444. function requirePicomatch$1 () {
  10445. if (hasRequiredPicomatch$1) return picomatch_1$1;
  10446. hasRequiredPicomatch$1 = 1;
  10447. const scan = /*@__PURE__*/ requireScan();
  10448. const parse = /*@__PURE__*/ requireParse();
  10449. const utils = /*@__PURE__*/ requireUtils();
  10450. const constants = /*@__PURE__*/ requireConstants();
  10451. const isObject = val => val && typeof val === 'object' && !Array.isArray(val);
  10452. /**
  10453. * Creates a matcher function from one or more glob patterns. The
  10454. * returned function takes a string to match as its first argument,
  10455. * and returns true if the string is a match. The returned matcher
  10456. * function also takes a boolean as the second argument that, when true,
  10457. * returns an object with additional information.
  10458. *
  10459. * ```js
  10460. * const picomatch = require('picomatch');
  10461. * // picomatch(glob[, options]);
  10462. *
  10463. * const isMatch = picomatch('*.!(*a)');
  10464. * console.log(isMatch('a.a')); //=> false
  10465. * console.log(isMatch('a.b')); //=> true
  10466. * ```
  10467. * @name picomatch
  10468. * @param {String|Array} `globs` One or more glob patterns.
  10469. * @param {Object=} `options`
  10470. * @return {Function=} Returns a matcher function.
  10471. * @api public
  10472. */
  10473. const picomatch = (glob, options, returnState = false) => {
  10474. if (Array.isArray(glob)) {
  10475. const fns = glob.map(input => picomatch(input, options, returnState));
  10476. const arrayMatcher = str => {
  10477. for (const isMatch of fns) {
  10478. const state = isMatch(str);
  10479. if (state) return state;
  10480. }
  10481. return false;
  10482. };
  10483. return arrayMatcher;
  10484. }
  10485. const isState = isObject(glob) && glob.tokens && glob.input;
  10486. if (glob === '' || (typeof glob !== 'string' && !isState)) {
  10487. throw new TypeError('Expected pattern to be a non-empty string');
  10488. }
  10489. const opts = options || {};
  10490. const posix = opts.windows;
  10491. const regex = isState
  10492. ? picomatch.compileRe(glob, options)
  10493. : picomatch.makeRe(glob, options, false, true);
  10494. const state = regex.state;
  10495. delete regex.state;
  10496. let isIgnored = () => false;
  10497. if (opts.ignore) {
  10498. const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
  10499. isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
  10500. }
  10501. const matcher = (input, returnObject = false) => {
  10502. const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix });
  10503. const result = { glob, state, regex, posix, input, output, match, isMatch };
  10504. if (typeof opts.onResult === 'function') {
  10505. opts.onResult(result);
  10506. }
  10507. if (isMatch === false) {
  10508. result.isMatch = false;
  10509. return returnObject ? result : false;
  10510. }
  10511. if (isIgnored(input)) {
  10512. if (typeof opts.onIgnore === 'function') {
  10513. opts.onIgnore(result);
  10514. }
  10515. result.isMatch = false;
  10516. return returnObject ? result : false;
  10517. }
  10518. if (typeof opts.onMatch === 'function') {
  10519. opts.onMatch(result);
  10520. }
  10521. return returnObject ? result : true;
  10522. };
  10523. if (returnState) {
  10524. matcher.state = state;
  10525. }
  10526. return matcher;
  10527. };
  10528. /**
  10529. * Test `input` with the given `regex`. This is used by the main
  10530. * `picomatch()` function to test the input string.
  10531. *
  10532. * ```js
  10533. * const picomatch = require('picomatch');
  10534. * // picomatch.test(input, regex[, options]);
  10535. *
  10536. * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
  10537. * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
  10538. * ```
  10539. * @param {String} `input` String to test.
  10540. * @param {RegExp} `regex`
  10541. * @return {Object} Returns an object with matching info.
  10542. * @api public
  10543. */
  10544. picomatch.test = (input, regex, options, { glob, posix } = {}) => {
  10545. if (typeof input !== 'string') {
  10546. throw new TypeError('Expected input to be a string');
  10547. }
  10548. if (input === '') {
  10549. return { isMatch: false, output: '' };
  10550. }
  10551. const opts = options || {};
  10552. const format = opts.format || (posix ? utils.toPosixSlashes : null);
  10553. let match = input === glob;
  10554. let output = (match && format) ? format(input) : input;
  10555. if (match === false) {
  10556. output = format ? format(input) : input;
  10557. match = output === glob;
  10558. }
  10559. if (match === false || opts.capture === true) {
  10560. if (opts.matchBase === true || opts.basename === true) {
  10561. match = picomatch.matchBase(input, regex, options, posix);
  10562. } else {
  10563. match = regex.exec(output);
  10564. }
  10565. }
  10566. return { isMatch: Boolean(match), match, output };
  10567. };
  10568. /**
  10569. * Match the basename of a filepath.
  10570. *
  10571. * ```js
  10572. * const picomatch = require('picomatch');
  10573. * // picomatch.matchBase(input, glob[, options]);
  10574. * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
  10575. * ```
  10576. * @param {String} `input` String to test.
  10577. * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
  10578. * @return {Boolean}
  10579. * @api public
  10580. */
  10581. picomatch.matchBase = (input, glob, options) => {
  10582. const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
  10583. return regex.test(utils.basename(input));
  10584. };
  10585. /**
  10586. * Returns true if **any** of the given glob `patterns` match the specified `string`.
  10587. *
  10588. * ```js
  10589. * const picomatch = require('picomatch');
  10590. * // picomatch.isMatch(string, patterns[, options]);
  10591. *
  10592. * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
  10593. * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
  10594. * ```
  10595. * @param {String|Array} str The string to test.
  10596. * @param {String|Array} patterns One or more glob patterns to use for matching.
  10597. * @param {Object} [options] See available [options](#options).
  10598. * @return {Boolean} Returns true if any patterns match `str`
  10599. * @api public
  10600. */
  10601. picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
  10602. /**
  10603. * Parse a glob pattern to create the source string for a regular
  10604. * expression.
  10605. *
  10606. * ```js
  10607. * const picomatch = require('picomatch');
  10608. * const result = picomatch.parse(pattern[, options]);
  10609. * ```
  10610. * @param {String} `pattern`
  10611. * @param {Object} `options`
  10612. * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
  10613. * @api public
  10614. */
  10615. picomatch.parse = (pattern, options) => {
  10616. if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options));
  10617. return parse(pattern, { ...options, fastpaths: false });
  10618. };
  10619. /**
  10620. * Scan a glob pattern to separate the pattern into segments.
  10621. *
  10622. * ```js
  10623. * const picomatch = require('picomatch');
  10624. * // picomatch.scan(input[, options]);
  10625. *
  10626. * const result = picomatch.scan('!./foo/*.js');
  10627. * console.log(result);
  10628. * { prefix: '!./',
  10629. * input: '!./foo/*.js',
  10630. * start: 3,
  10631. * base: 'foo',
  10632. * glob: '*.js',
  10633. * isBrace: false,
  10634. * isBracket: false,
  10635. * isGlob: true,
  10636. * isExtglob: false,
  10637. * isGlobstar: false,
  10638. * negated: true }
  10639. * ```
  10640. * @param {String} `input` Glob pattern to scan.
  10641. * @param {Object} `options`
  10642. * @return {Object} Returns an object with
  10643. * @api public
  10644. */
  10645. picomatch.scan = (input, options) => scan(input, options);
  10646. /**
  10647. * Compile a regular expression from the `state` object returned by the
  10648. * [parse()](#parse) method.
  10649. *
  10650. * ```js
  10651. * const picomatch = require('picomatch');
  10652. * const state = picomatch.parse('*.js');
  10653. * // picomatch.compileRe(state[, options]);
  10654. *
  10655. * console.log(picomatch.compileRe(state));
  10656. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  10657. * ```
  10658. * @param {Object} `state`
  10659. * @param {Object} `options`
  10660. * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
  10661. * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
  10662. * @return {RegExp}
  10663. * @api public
  10664. */
  10665. picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => {
  10666. if (returnOutput === true) {
  10667. return state.output;
  10668. }
  10669. const opts = options || {};
  10670. const prepend = opts.contains ? '' : '^';
  10671. const append = opts.contains ? '' : '$';
  10672. let source = `${prepend}(?:${state.output})${append}`;
  10673. if (state && state.negated === true) {
  10674. source = `^(?!${source}).*$`;
  10675. }
  10676. const regex = picomatch.toRegex(source, options);
  10677. if (returnState === true) {
  10678. regex.state = state;
  10679. }
  10680. return regex;
  10681. };
  10682. /**
  10683. * Create a regular expression from a parsed glob pattern.
  10684. *
  10685. * ```js
  10686. * const picomatch = require('picomatch');
  10687. * // picomatch.makeRe(state[, options]);
  10688. *
  10689. * const result = picomatch.makeRe('*.js');
  10690. * console.log(result);
  10691. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  10692. * ```
  10693. * @param {String} `state` The object returned from the `.parse` method.
  10694. * @param {Object} `options`
  10695. * @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.
  10696. * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
  10697. * @return {RegExp} Returns a regex created from the given pattern.
  10698. * @api public
  10699. */
  10700. picomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
  10701. if (!input || typeof input !== 'string') {
  10702. throw new TypeError('Expected a non-empty string');
  10703. }
  10704. let parsed = { negated: false, fastpaths: true };
  10705. if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
  10706. parsed.output = parse.fastpaths(input, options);
  10707. }
  10708. if (!parsed.output) {
  10709. parsed = parse(input, options);
  10710. }
  10711. return picomatch.compileRe(parsed, options, returnOutput, returnState);
  10712. };
  10713. /**
  10714. * Create a regular expression from the given regex source string.
  10715. *
  10716. * ```js
  10717. * const picomatch = require('picomatch');
  10718. * // picomatch.toRegex(source[, options]);
  10719. *
  10720. * const { output } = picomatch.parse('*.js');
  10721. * console.log(picomatch.toRegex(output));
  10722. * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
  10723. * ```
  10724. * @param {String} `source` Regular expression source string.
  10725. * @param {Object} `options`
  10726. * @return {RegExp}
  10727. * @api public
  10728. */
  10729. picomatch.toRegex = (source, options) => {
  10730. try {
  10731. const opts = options || {};
  10732. return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
  10733. } catch (err) {
  10734. if (options && options.debug === true) throw err;
  10735. return /$^/;
  10736. }
  10737. };
  10738. /**
  10739. * Picomatch constants.
  10740. * @return {Object}
  10741. */
  10742. picomatch.constants = constants;
  10743. /**
  10744. * Expose "picomatch"
  10745. */
  10746. picomatch_1$1 = picomatch;
  10747. return picomatch_1$1;
  10748. }
  10749. var picomatch_1;
  10750. var hasRequiredPicomatch;
  10751. function requirePicomatch () {
  10752. if (hasRequiredPicomatch) return picomatch_1;
  10753. hasRequiredPicomatch = 1;
  10754. const pico = /*@__PURE__*/ requirePicomatch$1();
  10755. const utils = /*@__PURE__*/ requireUtils();
  10756. function picomatch(glob, options, returnState = false) {
  10757. // default to os.platform()
  10758. if (options && (options.windows === null || options.windows === undefined)) {
  10759. // don't mutate the original options object
  10760. options = { ...options, windows: utils.isWindows() };
  10761. }
  10762. return pico(glob, options, returnState);
  10763. }
  10764. Object.assign(picomatch, pico);
  10765. picomatch_1 = picomatch;
  10766. return picomatch_1;
  10767. }
  10768. var picomatchExports = /*@__PURE__*/ requirePicomatch();
  10769. const picomatch = /*@__PURE__*/getDefaultExportFromCjs(picomatchExports);
  10770. const extractors = {
  10771. ArrayPattern(names, param) {
  10772. for (const element of param.elements) {
  10773. if (element)
  10774. extractors[element.type](names, element);
  10775. }
  10776. },
  10777. AssignmentPattern(names, param) {
  10778. extractors[param.left.type](names, param.left);
  10779. },
  10780. Identifier(names, param) {
  10781. names.push(param.name);
  10782. },
  10783. MemberExpression() { },
  10784. ObjectPattern(names, param) {
  10785. for (const prop of param.properties) {
  10786. // @ts-ignore Typescript reports that this is not a valid type
  10787. if (prop.type === 'RestElement') {
  10788. extractors.RestElement(names, prop);
  10789. }
  10790. else {
  10791. extractors[prop.value.type](names, prop.value);
  10792. }
  10793. }
  10794. },
  10795. RestElement(names, param) {
  10796. extractors[param.argument.type](names, param.argument);
  10797. }
  10798. };
  10799. const extractAssignedNames = function extractAssignedNames(param) {
  10800. const names = [];
  10801. extractors[param.type](names, param);
  10802. return names;
  10803. };
  10804. // Helper since Typescript can't detect readonly arrays with Array.isArray
  10805. function isArray(arg) {
  10806. return Array.isArray(arg);
  10807. }
  10808. function ensureArray$1(thing) {
  10809. if (isArray(thing))
  10810. return thing;
  10811. if (thing == null)
  10812. return [];
  10813. return [thing];
  10814. }
  10815. const normalizePathRegExp = new RegExp(`\\${win32.sep}`, 'g');
  10816. const normalizePath = function normalizePath(filename) {
  10817. return filename.replace(normalizePathRegExp, posix.sep);
  10818. };
  10819. function getMatcherString$1(id, resolutionBase) {
  10820. if (resolutionBase === false || isAbsolute(id) || id.startsWith('**')) {
  10821. return normalizePath(id);
  10822. }
  10823. // resolve('') is valid and will default to process.cwd()
  10824. const basePath = normalizePath(resolve(resolutionBase || ''))
  10825. // escape all possible (posix + win) path characters that might interfere with regex
  10826. .replace(/[-^$*+?.()|[\]{}]/g, '\\$&');
  10827. // Note that we use posix.join because:
  10828. // 1. the basePath has been normalized to use /
  10829. // 2. the incoming glob (id) matcher, also uses /
  10830. // otherwise Node will force backslash (\) on windows
  10831. return posix.join(basePath, normalizePath(id));
  10832. }
  10833. const createFilter$1 = function createFilter(include, exclude, options) {
  10834. const resolutionBase = options && options.resolve;
  10835. const getMatcher = (id) => id instanceof RegExp
  10836. ? id
  10837. : {
  10838. test: (what) => {
  10839. // this refactor is a tad overly verbose but makes for easy debugging
  10840. const pattern = getMatcherString$1(id, resolutionBase);
  10841. const fn = picomatch(pattern, { dot: true });
  10842. const result = fn(what);
  10843. return result;
  10844. }
  10845. };
  10846. const includeMatchers = ensureArray$1(include).map(getMatcher);
  10847. const excludeMatchers = ensureArray$1(exclude).map(getMatcher);
  10848. if (!includeMatchers.length && !excludeMatchers.length)
  10849. return (id) => typeof id === 'string' && !id.includes('\0');
  10850. return function result(id) {
  10851. if (typeof id !== 'string')
  10852. return false;
  10853. if (id.includes('\0'))
  10854. return false;
  10855. const pathId = normalizePath(id);
  10856. for (let i = 0; i < excludeMatchers.length; ++i) {
  10857. const matcher = excludeMatchers[i];
  10858. if (matcher instanceof RegExp) {
  10859. matcher.lastIndex = 0;
  10860. }
  10861. if (matcher.test(pathId))
  10862. return false;
  10863. }
  10864. for (let i = 0; i < includeMatchers.length; ++i) {
  10865. const matcher = includeMatchers[i];
  10866. if (matcher instanceof RegExp) {
  10867. matcher.lastIndex = 0;
  10868. }
  10869. if (matcher.test(pathId))
  10870. return true;
  10871. }
  10872. return !includeMatchers.length;
  10873. };
  10874. };
  10875. const reservedWords = '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';
  10876. 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';
  10877. const forbiddenIdentifiers = new Set(`${reservedWords} ${builtins}`.split(' '));
  10878. forbiddenIdentifiers.add('');
  10879. class ArrayPattern extends NodeBase {
  10880. addExportedVariables(variables, exportNamesByVariable) {
  10881. for (const element of this.elements) {
  10882. element?.addExportedVariables(variables, exportNamesByVariable);
  10883. }
  10884. }
  10885. declare(kind, destructuredInitPath, init) {
  10886. const variables = [];
  10887. const includedPatternPath = getIncludedPatternPath(destructuredInitPath);
  10888. for (const element of this.elements) {
  10889. if (element !== null) {
  10890. variables.push(...element.declare(kind, includedPatternPath, init));
  10891. }
  10892. }
  10893. return variables;
  10894. }
  10895. deoptimizeAssignment(destructuredInitPath, init) {
  10896. const includedPatternPath = getIncludedPatternPath(destructuredInitPath);
  10897. for (const element of this.elements) {
  10898. element?.deoptimizeAssignment(includedPatternPath, init);
  10899. }
  10900. }
  10901. // Patterns can only be deoptimized at the empty path at the moment
  10902. deoptimizePath() {
  10903. for (const element of this.elements) {
  10904. element?.deoptimizePath(EMPTY_PATH);
  10905. }
  10906. }
  10907. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  10908. const includedPatternPath = getIncludedPatternPath(destructuredInitPath);
  10909. for (const element of this.elements) {
  10910. if (element?.hasEffectsWhenDestructuring(context, includedPatternPath, init)) {
  10911. return true;
  10912. }
  10913. }
  10914. return false;
  10915. }
  10916. // Patterns are only checked at the empty path at the moment
  10917. hasEffectsOnInteractionAtPath(_path, interaction, context) {
  10918. for (const element of this.elements) {
  10919. if (element?.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context))
  10920. return true;
  10921. }
  10922. return false;
  10923. }
  10924. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  10925. let included = false;
  10926. const includedPatternPath = getIncludedPatternPath(destructuredInitPath);
  10927. for (const element of [...this.elements].reverse()) {
  10928. if (element) {
  10929. if (included && !element.included) {
  10930. element.includeNode(context);
  10931. }
  10932. included =
  10933. element.includeDestructuredIfNecessary(context, includedPatternPath, init) || included;
  10934. }
  10935. }
  10936. if (!this.included && included) {
  10937. this.includeNode(context);
  10938. }
  10939. return this.included;
  10940. }
  10941. render(code, options) {
  10942. let removedStart = this.start + 1;
  10943. for (const element of this.elements) {
  10944. if (!element)
  10945. continue;
  10946. if (element.included) {
  10947. element.render(code, options);
  10948. removedStart = element.end;
  10949. }
  10950. else {
  10951. code.remove(removedStart, this.end - 1);
  10952. break;
  10953. }
  10954. }
  10955. }
  10956. markDeclarationReached() {
  10957. for (const element of this.elements) {
  10958. element?.markDeclarationReached();
  10959. }
  10960. }
  10961. }
  10962. ArrayPattern.prototype.includeNode = onlyIncludeSelf;
  10963. const getIncludedPatternPath = (destructuredInitPath) => destructuredInitPath.at(-1) === UnknownKey
  10964. ? destructuredInitPath
  10965. : [...destructuredInitPath, UnknownInteger];
  10966. class ArrowFunctionExpression extends FunctionBase {
  10967. constructor() {
  10968. super(...arguments);
  10969. this.objectEntity = null;
  10970. }
  10971. get expression() {
  10972. return isFlagSet(this.flags, 8388608 /* Flag.expression */);
  10973. }
  10974. set expression(value) {
  10975. this.flags = setFlag(this.flags, 8388608 /* Flag.expression */, value);
  10976. }
  10977. createScope(parentScope) {
  10978. this.scope = new ReturnValueScope(parentScope, false);
  10979. }
  10980. hasEffects() {
  10981. return false;
  10982. }
  10983. hasEffectsOnInteractionAtPath(path, interaction, context) {
  10984. if (this.annotationNoSideEffects &&
  10985. path.length === 0 &&
  10986. interaction.type === INTERACTION_CALLED) {
  10987. return false;
  10988. }
  10989. if (super.hasEffectsOnInteractionAtPath(path, interaction, context)) {
  10990. return true;
  10991. }
  10992. if (interaction.type === INTERACTION_CALLED) {
  10993. const { ignore, brokenFlow } = context;
  10994. context.ignore = {
  10995. breaks: false,
  10996. continues: false,
  10997. labels: new Set(),
  10998. returnYield: true,
  10999. this: false
  11000. };
  11001. if (this.body.hasEffects(context))
  11002. return true;
  11003. context.ignore = ignore;
  11004. context.brokenFlow = brokenFlow;
  11005. }
  11006. return false;
  11007. }
  11008. onlyFunctionCallUsed() {
  11009. const isIIFE = this.parent.type === CallExpression$1 &&
  11010. this.parent.callee === this;
  11011. return isIIFE || super.onlyFunctionCallUsed();
  11012. }
  11013. include(context, includeChildrenRecursively) {
  11014. super.include(context, includeChildrenRecursively);
  11015. for (const parameter of this.params) {
  11016. if (!(parameter instanceof Identifier)) {
  11017. parameter.include(context, includeChildrenRecursively);
  11018. }
  11019. }
  11020. }
  11021. includeNode(context) {
  11022. this.included = true;
  11023. this.body.includePath(UNKNOWN_PATH, context);
  11024. for (const parameter of this.params) {
  11025. if (!(parameter instanceof Identifier)) {
  11026. parameter.includePath(UNKNOWN_PATH, context);
  11027. }
  11028. }
  11029. }
  11030. getObjectEntity() {
  11031. if (this.objectEntity !== null) {
  11032. return this.objectEntity;
  11033. }
  11034. return (this.objectEntity = new ObjectEntity([], OBJECT_PROTOTYPE));
  11035. }
  11036. }
  11037. class ObjectPattern extends NodeBase {
  11038. addExportedVariables(variables, exportNamesByVariable) {
  11039. for (const property of this.properties) {
  11040. if (property.type === Property$1) {
  11041. property.value.addExportedVariables(variables, exportNamesByVariable);
  11042. }
  11043. else {
  11044. property.argument.addExportedVariables(variables, exportNamesByVariable);
  11045. }
  11046. }
  11047. }
  11048. declare(kind, destructuredInitPath, init) {
  11049. const variables = [];
  11050. for (const property of this.properties) {
  11051. variables.push(...property.declare(kind, destructuredInitPath, init));
  11052. }
  11053. return variables;
  11054. }
  11055. deoptimizeAssignment(destructuredInitPath, init) {
  11056. for (const property of this.properties) {
  11057. property.deoptimizeAssignment(destructuredInitPath, init);
  11058. }
  11059. }
  11060. deoptimizePath(path) {
  11061. if (path.length === 0) {
  11062. for (const property of this.properties) {
  11063. property.deoptimizePath(path);
  11064. }
  11065. }
  11066. }
  11067. hasEffectsOnInteractionAtPath(
  11068. // At the moment, this is only triggered for assignment left-hand sides,
  11069. // where the path is empty
  11070. _path, interaction, context) {
  11071. for (const property of this.properties) {
  11072. if (property.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context))
  11073. return true;
  11074. }
  11075. return false;
  11076. }
  11077. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  11078. for (const property of this.properties) {
  11079. if (property.hasEffectsWhenDestructuring(context, destructuredInitPath, init))
  11080. return true;
  11081. }
  11082. return false;
  11083. }
  11084. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  11085. if (!this.properties.length)
  11086. return this.included;
  11087. const lastProperty = this.properties.at(-1);
  11088. let included = lastProperty.includeDestructuredIfNecessary(context, destructuredInitPath, init);
  11089. const lastPropertyIsRestElement = lastProperty.type === RestElement$1;
  11090. for (const property of this.properties.slice(0, -1)) {
  11091. if (lastPropertyIsRestElement && included && !property.included) {
  11092. property.includeNode(context);
  11093. }
  11094. included =
  11095. property.includeDestructuredIfNecessary(context, destructuredInitPath, init) || included;
  11096. }
  11097. if (!this.included && included) {
  11098. this.includeNode(context);
  11099. }
  11100. return this.included;
  11101. }
  11102. markDeclarationReached() {
  11103. for (const property of this.properties) {
  11104. property.markDeclarationReached();
  11105. }
  11106. }
  11107. render(code, options) {
  11108. if (this.properties.length > 0) {
  11109. const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.properties, code, this.start + 1, this.end - 1);
  11110. let lastSeparatorPos = null;
  11111. for (const { node, separator, start, end } of separatedNodes) {
  11112. if (!node.included) {
  11113. treeshakeNode(node, code, start, end);
  11114. continue;
  11115. }
  11116. lastSeparatorPos = separator;
  11117. node.render(code, options);
  11118. }
  11119. if (lastSeparatorPos) {
  11120. code.remove(lastSeparatorPos, this.end - 1);
  11121. }
  11122. }
  11123. }
  11124. }
  11125. ObjectPattern.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  11126. ObjectPattern.prototype.applyDeoptimizations = doNotDeoptimize;
  11127. class AssignmentExpression extends NodeBase {
  11128. constructor() {
  11129. super(...arguments);
  11130. this.isConstReassignment = false;
  11131. }
  11132. hasEffects(context) {
  11133. const { deoptimized, isConstReassignment, left, operator, right } = this;
  11134. if (!deoptimized)
  11135. this.applyDeoptimizations();
  11136. // MemberExpressions do not access the property before assignments if the
  11137. // operator is '='.
  11138. return (isConstReassignment ||
  11139. right.hasEffects(context) ||
  11140. left.hasEffectsAsAssignmentTarget(context, operator !== '=') ||
  11141. this.left.hasEffectsWhenDestructuring?.(context, EMPTY_PATH, right));
  11142. }
  11143. hasEffectsOnInteractionAtPath(path, interaction, context) {
  11144. return ((interaction.type === INTERACTION_ASSIGNED && this.left.included) ||
  11145. this.right.hasEffectsOnInteractionAtPath(path, interaction, context));
  11146. }
  11147. include(context, includeChildrenRecursively) {
  11148. const { deoptimized, isConstReassignment, left, right, operator } = this;
  11149. if (!deoptimized)
  11150. this.applyDeoptimizations();
  11151. if (!this.included)
  11152. this.includeNode(context);
  11153. const hasEffectsContext = createHasEffectsContext();
  11154. if (includeChildrenRecursively ||
  11155. isConstReassignment ||
  11156. operator !== '=' ||
  11157. left.included ||
  11158. left.hasEffectsAsAssignmentTarget(hasEffectsContext, false) ||
  11159. left.hasEffectsWhenDestructuring?.(hasEffectsContext, EMPTY_PATH, right)) {
  11160. left.includeAsAssignmentTarget(context, includeChildrenRecursively, operator !== '=');
  11161. }
  11162. right.include(context, includeChildrenRecursively);
  11163. }
  11164. includeNode(context) {
  11165. this.included = true;
  11166. if (!this.deoptimized)
  11167. this.applyDeoptimizations();
  11168. this.right.includePath(UNKNOWN_PATH, context);
  11169. }
  11170. initialise() {
  11171. super.initialise();
  11172. if (this.left instanceof Identifier) {
  11173. const variable = this.scope.variables.get(this.left.name);
  11174. if (variable?.kind === 'const') {
  11175. this.isConstReassignment = true;
  11176. this.scope.context.log(LOGLEVEL_WARN, logConstVariableReassignError(), this.left.start);
  11177. }
  11178. }
  11179. this.left.setAssignedValue(this.right);
  11180. }
  11181. render(code, options, { preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  11182. const { left, right, start, end, parent } = this;
  11183. if (left.included) {
  11184. left.render(code, options);
  11185. right.render(code, options);
  11186. }
  11187. else {
  11188. const inclusionStart = findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, '=', left.end) + 1);
  11189. code.remove(start, inclusionStart);
  11190. if (preventASI) {
  11191. removeLineBreaks(code, inclusionStart, right.start);
  11192. }
  11193. right.render(code, options, {
  11194. renderedParentType: renderedParentType || parent.type,
  11195. renderedSurroundingElement: renderedSurroundingElement || parent.type
  11196. });
  11197. }
  11198. if (options.format === 'system') {
  11199. if (left instanceof Identifier) {
  11200. const variable = left.variable;
  11201. const exportNames = options.exportNamesByVariable.get(variable);
  11202. if (exportNames) {
  11203. if (exportNames.length === 1) {
  11204. renderSystemExportExpression(variable, start, end, code, options);
  11205. }
  11206. else {
  11207. renderSystemExportSequenceAfterExpression(variable, start, end, parent.type !== ExpressionStatement$1, code, options);
  11208. }
  11209. return;
  11210. }
  11211. }
  11212. else {
  11213. const systemPatternExports = [];
  11214. left.addExportedVariables(systemPatternExports, options.exportNamesByVariable);
  11215. if (systemPatternExports.length > 0) {
  11216. renderSystemExportFunction(systemPatternExports, start, end, renderedSurroundingElement === ExpressionStatement$1, code, options);
  11217. return;
  11218. }
  11219. }
  11220. }
  11221. if (left.included &&
  11222. left instanceof ObjectPattern &&
  11223. (renderedSurroundingElement === ExpressionStatement$1 ||
  11224. renderedSurroundingElement === ArrowFunctionExpression$1)) {
  11225. code.appendRight(start, '(');
  11226. code.prependLeft(end, ')');
  11227. }
  11228. }
  11229. applyDeoptimizations() {
  11230. this.deoptimized = true;
  11231. this.left.deoptimizeAssignment(EMPTY_PATH, this.right);
  11232. this.scope.context.requestTreeshakingPass();
  11233. }
  11234. }
  11235. class AssignmentPattern extends NodeBase {
  11236. addExportedVariables(variables, exportNamesByVariable) {
  11237. this.left.addExportedVariables(variables, exportNamesByVariable);
  11238. }
  11239. declare(kind, destructuredInitPath, init) {
  11240. return this.left.declare(kind, destructuredInitPath, init);
  11241. }
  11242. deoptimizeAssignment(destructuredInitPath, init) {
  11243. this.left.deoptimizeAssignment(destructuredInitPath, init);
  11244. }
  11245. deoptimizePath(path) {
  11246. if (path.length === 0) {
  11247. this.left.deoptimizePath(path);
  11248. }
  11249. }
  11250. hasEffectsOnInteractionAtPath(path, interaction, context) {
  11251. return (path.length > 0 || this.left.hasEffectsOnInteractionAtPath(EMPTY_PATH, interaction, context));
  11252. }
  11253. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  11254. return this.left.hasEffectsWhenDestructuring(context, destructuredInitPath, init);
  11255. }
  11256. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  11257. let included = this.left.includeDestructuredIfNecessary(context, destructuredInitPath, init) ||
  11258. this.included;
  11259. if ((included ||= this.right.shouldBeIncluded(context))) {
  11260. this.right.include(context, false);
  11261. if (!this.left.included) {
  11262. this.left.includeNode(context);
  11263. // Unfortunately, we need to include the left side again now, so that
  11264. // any declared variables are properly included.
  11265. this.left.includeDestructuredIfNecessary(context, destructuredInitPath, init);
  11266. }
  11267. }
  11268. if (!this.included && included) {
  11269. this.includeNode(context);
  11270. }
  11271. return this.included;
  11272. }
  11273. includeNode(context) {
  11274. this.included = true;
  11275. if (!this.deoptimized)
  11276. this.applyDeoptimizations();
  11277. this.right.includePath(UNKNOWN_PATH, context);
  11278. }
  11279. markDeclarationReached() {
  11280. this.left.markDeclarationReached();
  11281. }
  11282. render(code, options, { isShorthandProperty } = BLANK) {
  11283. this.left.render(code, options, { isShorthandProperty });
  11284. this.right.render(code, options);
  11285. }
  11286. applyDeoptimizations() {
  11287. this.deoptimized = true;
  11288. this.left.deoptimizePath(EMPTY_PATH);
  11289. this.right.deoptimizePath(UNKNOWN_PATH);
  11290. this.scope.context.requestTreeshakingPass();
  11291. }
  11292. }
  11293. class AwaitExpression extends NodeBase {
  11294. deoptimizePath(path) {
  11295. this.argument.deoptimizePath(path);
  11296. }
  11297. hasEffects() {
  11298. if (!this.deoptimized)
  11299. this.applyDeoptimizations();
  11300. return true;
  11301. }
  11302. initialise() {
  11303. super.initialise();
  11304. let parent = this.parent;
  11305. do {
  11306. if (parent instanceof FunctionNode || parent instanceof ArrowFunctionExpression)
  11307. return;
  11308. } while ((parent = parent.parent));
  11309. this.scope.context.usesTopLevelAwait = true;
  11310. }
  11311. include(context, includeChildrenRecursively) {
  11312. if (!this.included)
  11313. this.includeNode(context);
  11314. this.argument.include(context, includeChildrenRecursively);
  11315. }
  11316. includeNode(context) {
  11317. this.included = true;
  11318. if (!this.deoptimized)
  11319. this.applyDeoptimizations();
  11320. // Thenables need to be included
  11321. this.argument.includePath(THEN_PATH, context);
  11322. }
  11323. includePath(path, context) {
  11324. if (!this.deoptimized)
  11325. this.applyDeoptimizations();
  11326. if (!this.included)
  11327. this.includeNode(context);
  11328. this.argument.includePath(path, context);
  11329. }
  11330. }
  11331. const THEN_PATH = ['then'];
  11332. function getRenderedLiteralValue(value) {
  11333. if (value === undefined) {
  11334. return 'void 0';
  11335. }
  11336. if (typeof value === 'boolean') {
  11337. return String(value);
  11338. }
  11339. if (typeof value === 'string') {
  11340. return JSON.stringify(value);
  11341. }
  11342. if (typeof value === 'number') {
  11343. return getSimplifiedNumber(value);
  11344. }
  11345. return UnknownValue;
  11346. }
  11347. function getSimplifiedNumber(value) {
  11348. if (Object.is(-0, value)) {
  11349. return '-0';
  11350. }
  11351. const exp = value.toExponential();
  11352. const [base, exponent] = exp.split('e');
  11353. const floatLength = base.split('.')[1]?.length || 0;
  11354. const finalizedExp = `${base.replace('.', '')}e${parseInt(exponent) - floatLength}`;
  11355. const stringifiedValue = String(value).replace('+', '');
  11356. return finalizedExp.length < stringifiedValue.length ? finalizedExp : stringifiedValue;
  11357. }
  11358. const binaryOperators = {
  11359. '!=': (left, right) => left != right,
  11360. '!==': (left, right) => left !== right,
  11361. '%': (left, right) => left % right,
  11362. '&': (left, right) => left & right,
  11363. '*': (left, right) => left * right,
  11364. // At the moment, "**" will be transpiled to Math.pow
  11365. '**': (left, right) => left ** right,
  11366. '+': (left, right) => left + right,
  11367. '-': (left, right) => left - right,
  11368. '/': (left, right) => left / right,
  11369. '<': (left, right) => left < right,
  11370. '<<': (left, right) => left << right,
  11371. '<=': (left, right) => left <= right,
  11372. '==': (left, right) => left == right,
  11373. '===': (left, right) => left === right,
  11374. '>': (left, right) => left > right,
  11375. '>=': (left, right) => left >= right,
  11376. '>>': (left, right) => left >> right,
  11377. '>>>': (left, right) => left >>> right,
  11378. '^': (left, right) => left ^ right,
  11379. '|': (left, right) => left | right
  11380. // We use the fallback for cases where we return something unknown
  11381. // in: () => UnknownValue,
  11382. // instanceof: () => UnknownValue,
  11383. };
  11384. const UNASSIGNED$1 = Symbol('Unassigned');
  11385. class BinaryExpression extends NodeBase {
  11386. constructor() {
  11387. super(...arguments);
  11388. this.renderedLiteralValue = UNASSIGNED$1;
  11389. }
  11390. deoptimizeCache() {
  11391. this.renderedLiteralValue = UnknownValue;
  11392. }
  11393. getLiteralValueAtPath(path, recursionTracker, origin) {
  11394. if (path.length > 0)
  11395. return UnknownValue;
  11396. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  11397. if (typeof leftValue === 'symbol')
  11398. return UnknownValue;
  11399. // Optimize `'export' in namespace`
  11400. if (this.operator === 'in' && this.right.variable instanceof NamespaceVariable) {
  11401. const [variable] = this.right.variable.context.traceExport(String(leftValue));
  11402. if (variable instanceof ExternalVariable)
  11403. return UnknownValue;
  11404. if (variable instanceof SyntheticNamedExportVariable)
  11405. return UnknownValue;
  11406. return !!variable;
  11407. }
  11408. const rightValue = this.right.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  11409. if (typeof rightValue === 'symbol')
  11410. return UnknownValue;
  11411. const operatorFunction = binaryOperators[this.operator];
  11412. if (!operatorFunction)
  11413. return UnknownValue;
  11414. return operatorFunction(leftValue, rightValue);
  11415. }
  11416. getRenderedLiteralValue() {
  11417. // Only optimize `'export' in ns`
  11418. if (this.operator !== 'in' || !(this.right.variable instanceof NamespaceVariable)) {
  11419. return UnknownValue;
  11420. }
  11421. if (this.renderedLiteralValue !== UNASSIGNED$1)
  11422. return this.renderedLiteralValue;
  11423. return (this.renderedLiteralValue = getRenderedLiteralValue(this.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this)));
  11424. }
  11425. hasEffects(context) {
  11426. // support some implicit type coercion runtime errors
  11427. if (this.operator === '+' &&
  11428. this.parent instanceof ExpressionStatement &&
  11429. this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) === '') {
  11430. return true;
  11431. }
  11432. return super.hasEffects(context);
  11433. }
  11434. hasEffectsOnInteractionAtPath(path, { type }) {
  11435. return type !== INTERACTION_ACCESSED || path.length > 1;
  11436. }
  11437. include(context, includeChildrenRecursively, options) {
  11438. if (!this.included)
  11439. this.includeNode(context);
  11440. if (typeof this.getRenderedLiteralValue() === 'symbol') {
  11441. this.left.include(context, includeChildrenRecursively, options);
  11442. this.right.include(context, includeChildrenRecursively, options);
  11443. // `instanceof` will attempt to call RHS's `Symbol.hasInstance` if it exists.
  11444. if (this.operator === 'instanceof')
  11445. this.right.includePath(INSTANCEOF_PATH, context);
  11446. }
  11447. }
  11448. includeNode(context) {
  11449. this.included = true;
  11450. if (this.operator === 'in' && typeof this.getRenderedLiteralValue() === 'symbol') {
  11451. this.right.includePath(UNKNOWN_PATH, context);
  11452. }
  11453. }
  11454. removeAnnotations(code) {
  11455. this.left.removeAnnotations(code);
  11456. }
  11457. render(code, options, { renderedSurroundingElement } = BLANK) {
  11458. const renderedLiteralValue = this.getRenderedLiteralValue();
  11459. if (typeof renderedLiteralValue !== 'symbol') {
  11460. code.overwrite(this.start, this.end, renderedLiteralValue);
  11461. }
  11462. else {
  11463. this.left.render(code, options, { renderedSurroundingElement });
  11464. this.right.render(code, options);
  11465. }
  11466. }
  11467. }
  11468. BinaryExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  11469. class BreakStatement extends NodeBase {
  11470. hasEffects(context) {
  11471. if (this.label) {
  11472. if (!context.ignore.labels.has(this.label.name))
  11473. return true;
  11474. context.includedLabels.add(this.label.name);
  11475. }
  11476. else {
  11477. if (!context.ignore.breaks)
  11478. return true;
  11479. context.hasBreak = true;
  11480. }
  11481. context.brokenFlow = true;
  11482. return false;
  11483. }
  11484. include(context, includeChildrenRecursively) {
  11485. this.included = true;
  11486. if (this.label) {
  11487. this.label.include(context, includeChildrenRecursively);
  11488. context.includedLabels.add(this.label.name);
  11489. }
  11490. else {
  11491. context.hasBreak = true;
  11492. }
  11493. context.brokenFlow = true;
  11494. }
  11495. }
  11496. BreakStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  11497. BreakStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  11498. function renderCallArguments(code, options, node) {
  11499. if (node.arguments.length > 0) {
  11500. if (node.arguments[node.arguments.length - 1].included) {
  11501. for (const argument of node.arguments) {
  11502. argument.render(code, options);
  11503. }
  11504. }
  11505. else {
  11506. let lastIncludedIndex = node.arguments.length - 2;
  11507. while (lastIncludedIndex >= 0 && !node.arguments[lastIncludedIndex].included) {
  11508. lastIncludedIndex--;
  11509. }
  11510. if (lastIncludedIndex >= 0) {
  11511. for (let index = 0; index <= lastIncludedIndex; index++) {
  11512. node.arguments[index].render(code, options);
  11513. }
  11514. code.remove(findFirstOccurrenceOutsideComment(code.original, ',', node.arguments[lastIncludedIndex].end), node.end - 1);
  11515. }
  11516. else {
  11517. code.remove(findFirstOccurrenceOutsideComment(code.original, '(', node.callee.end) + 1, node.end - 1);
  11518. }
  11519. }
  11520. }
  11521. }
  11522. class CallExpressionBase extends NodeBase {
  11523. constructor() {
  11524. super(...arguments);
  11525. this.returnExpression = null;
  11526. this.deoptimizableDependentExpressions = [];
  11527. this.expressionsToBeDeoptimized = new Set();
  11528. }
  11529. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  11530. const { args } = interaction;
  11531. const [returnExpression, isPure] = this.getReturnExpression(recursionTracker);
  11532. if (isPure)
  11533. return;
  11534. const deoptimizedExpressions = args.filter(expression => !!expression && expression !== UNKNOWN_EXPRESSION);
  11535. if (deoptimizedExpressions.length === 0)
  11536. return;
  11537. if (returnExpression === UNKNOWN_EXPRESSION) {
  11538. for (const expression of deoptimizedExpressions) {
  11539. expression.deoptimizePath(UNKNOWN_PATH);
  11540. }
  11541. }
  11542. else {
  11543. recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  11544. for (const expression of deoptimizedExpressions) {
  11545. this.expressionsToBeDeoptimized.add(expression);
  11546. }
  11547. returnExpression.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  11548. }, null);
  11549. }
  11550. }
  11551. deoptimizeCache() {
  11552. if (this.returnExpression?.[0] !== UNKNOWN_EXPRESSION) {
  11553. this.returnExpression = UNKNOWN_RETURN_EXPRESSION;
  11554. const { deoptimizableDependentExpressions, expressionsToBeDeoptimized } = this;
  11555. this.expressionsToBeDeoptimized = EMPTY_SET;
  11556. this.deoptimizableDependentExpressions = EMPTY_ARRAY;
  11557. for (const expression of deoptimizableDependentExpressions) {
  11558. expression.deoptimizeCache();
  11559. }
  11560. for (const expression of expressionsToBeDeoptimized) {
  11561. expression.deoptimizePath(UNKNOWN_PATH);
  11562. }
  11563. }
  11564. }
  11565. deoptimizePath(path) {
  11566. if (path.length === 0 ||
  11567. this.scope.context.deoptimizationTracker.trackEntityAtPathAndGetIfTracked(path, this)) {
  11568. return;
  11569. }
  11570. const [returnExpression] = this.getReturnExpression();
  11571. if (returnExpression !== UNKNOWN_EXPRESSION) {
  11572. returnExpression.deoptimizePath(path);
  11573. }
  11574. }
  11575. getLiteralValueAtPath(path, recursionTracker, origin) {
  11576. const [returnExpression] = this.getReturnExpression(recursionTracker);
  11577. if (returnExpression === UNKNOWN_EXPRESSION) {
  11578. return UnknownValue;
  11579. }
  11580. return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  11581. this.deoptimizableDependentExpressions.push(origin);
  11582. return returnExpression.getLiteralValueAtPath(path, recursionTracker, origin);
  11583. }, UnknownValue);
  11584. }
  11585. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  11586. const returnExpression = this.getReturnExpression(recursionTracker);
  11587. if (returnExpression[0] === UNKNOWN_EXPRESSION) {
  11588. return returnExpression;
  11589. }
  11590. return recursionTracker.withTrackedEntityAtPath(path, returnExpression, () => {
  11591. this.deoptimizableDependentExpressions.push(origin);
  11592. const [expression, isPure] = returnExpression[0].getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  11593. return [expression, isPure || returnExpression[1]];
  11594. }, UNKNOWN_RETURN_EXPRESSION);
  11595. }
  11596. hasEffectsOnInteractionAtPath(path, interaction, context) {
  11597. const { type } = interaction;
  11598. if (type === INTERACTION_CALLED) {
  11599. const { args, withNew } = interaction;
  11600. if ((withNew ? context.instantiated : context.called).trackEntityAtPathAndGetIfTracked(path, args, this)) {
  11601. return false;
  11602. }
  11603. }
  11604. else if ((type === INTERACTION_ASSIGNED
  11605. ? context.assigned
  11606. : context.accessed).trackEntityAtPathAndGetIfTracked(path, this)) {
  11607. return false;
  11608. }
  11609. const [returnExpression, isPure] = this.getReturnExpression();
  11610. return ((type === INTERACTION_ASSIGNED || !isPure) &&
  11611. returnExpression.hasEffectsOnInteractionAtPath(path, interaction, context));
  11612. }
  11613. }
  11614. class CallExpression extends CallExpressionBase {
  11615. get hasCheckedForWarnings() {
  11616. return isFlagSet(this.flags, 134217728 /* Flag.checkedForWarnings */);
  11617. }
  11618. set hasCheckedForWarnings(value) {
  11619. this.flags = setFlag(this.flags, 134217728 /* Flag.checkedForWarnings */, value);
  11620. }
  11621. get optional() {
  11622. return isFlagSet(this.flags, 128 /* Flag.optional */);
  11623. }
  11624. set optional(value) {
  11625. this.flags = setFlag(this.flags, 128 /* Flag.optional */, value);
  11626. }
  11627. bind() {
  11628. super.bind();
  11629. this.interaction = {
  11630. args: [
  11631. this.callee instanceof MemberExpression && !this.callee.variable
  11632. ? this.callee.object
  11633. : null,
  11634. ...this.arguments
  11635. ],
  11636. type: INTERACTION_CALLED,
  11637. withNew: false
  11638. };
  11639. }
  11640. getLiteralValueAtPathAsChainElement(path, recursionTracker, origin) {
  11641. return getChainElementLiteralValueAtPath(this, this.callee, path, recursionTracker, origin);
  11642. }
  11643. hasEffects(context) {
  11644. if (!this.deoptimized)
  11645. this.applyDeoptimizations();
  11646. for (const argument of this.arguments) {
  11647. if (argument.hasEffects(context))
  11648. return true;
  11649. }
  11650. if (this.annotationPure) {
  11651. return false;
  11652. }
  11653. return (this.callee.hasEffects(context) ||
  11654. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  11655. }
  11656. hasEffectsAsChainElement(context) {
  11657. const calleeHasEffects = 'hasEffectsAsChainElement' in this.callee
  11658. ? this.callee.hasEffectsAsChainElement(context)
  11659. : this.callee.hasEffects(context);
  11660. if (calleeHasEffects === IS_SKIPPED_CHAIN)
  11661. return IS_SKIPPED_CHAIN;
  11662. if (this.optional &&
  11663. this.callee.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) == null) {
  11664. return (!this.annotationPure && calleeHasEffects) || IS_SKIPPED_CHAIN;
  11665. }
  11666. // We only apply deoptimizations lazily once we know we are not skipping
  11667. if (!this.deoptimized)
  11668. this.applyDeoptimizations();
  11669. for (const argument of this.arguments) {
  11670. if (argument.hasEffects(context))
  11671. return true;
  11672. }
  11673. return (!this.annotationPure &&
  11674. (calleeHasEffects ||
  11675. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context)));
  11676. }
  11677. include(context, includeChildrenRecursively) {
  11678. if (!this.included)
  11679. this.includeNode(context);
  11680. if (includeChildrenRecursively) {
  11681. super.include(context, true);
  11682. if (includeChildrenRecursively === INCLUDE_PARAMETERS &&
  11683. this.callee instanceof Identifier &&
  11684. this.callee.variable) {
  11685. this.callee.variable.markCalledFromTryStatement();
  11686. }
  11687. }
  11688. else {
  11689. this.callee.include(context, false);
  11690. this.callee.includeCallArguments(this.interaction, context);
  11691. }
  11692. }
  11693. includeNode(_context) {
  11694. this.included = true;
  11695. if (!this.deoptimized)
  11696. this.applyDeoptimizations();
  11697. }
  11698. initialise() {
  11699. super.initialise();
  11700. if (this.annotations &&
  11701. this.scope.context.options.treeshake.annotations) {
  11702. this.annotationPure = this.annotations.some(comment => comment.type === 'pure');
  11703. }
  11704. }
  11705. render(code, options, { renderedSurroundingElement } = BLANK) {
  11706. this.callee.render(code, options, {
  11707. isCalleeOfRenderedParent: true,
  11708. renderedSurroundingElement
  11709. });
  11710. renderCallArguments(code, options, this);
  11711. if (this.callee instanceof Identifier && !this.hasCheckedForWarnings) {
  11712. this.hasCheckedForWarnings = true;
  11713. const variable = this.scope.findVariable(this.callee.name);
  11714. if (variable.isNamespace) {
  11715. this.scope.context.log(LOGLEVEL_WARN, logCannotCallNamespace(this.callee.name), this.start);
  11716. }
  11717. if (this.callee.name === 'eval') {
  11718. this.scope.context.log(LOGLEVEL_WARN, logEval(this.scope.context.module.id), this.start);
  11719. }
  11720. }
  11721. }
  11722. applyDeoptimizations() {
  11723. this.deoptimized = true;
  11724. this.callee.deoptimizeArgumentsOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  11725. this.scope.context.requestTreeshakingPass();
  11726. }
  11727. getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) {
  11728. if (this.returnExpression === null) {
  11729. this.returnExpression = UNKNOWN_RETURN_EXPRESSION;
  11730. return (this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.interaction, recursionTracker, this));
  11731. }
  11732. return this.returnExpression;
  11733. }
  11734. }
  11735. class CatchClause extends NodeBase {
  11736. createScope(parentScope) {
  11737. this.scope = new ParameterScope(parentScope, true);
  11738. }
  11739. parseNode(esTreeNode) {
  11740. const { body, param, type } = esTreeNode;
  11741. this.type = type;
  11742. if (param) {
  11743. this.param = new (this.scope.context.getNodeConstructor(param.type))(this, this.scope).parseNode(param);
  11744. this.param.declare('parameter', EMPTY_PATH, UNKNOWN_EXPRESSION);
  11745. }
  11746. this.body = new BlockStatement(this, this.scope.bodyScope).parseNode(body);
  11747. return super.parseNode(esTreeNode);
  11748. }
  11749. }
  11750. CatchClause.prototype.preventChildBlockScope = true;
  11751. CatchClause.prototype.includeNode = onlyIncludeSelf;
  11752. class ChainExpression extends NodeBase {
  11753. // deoptimizations are not relevant as we are not caching values
  11754. deoptimizeCache() { }
  11755. getLiteralValueAtPath(path, recursionTracker, origin) {
  11756. const literalValue = this.expression.getLiteralValueAtPathAsChainElement(path, recursionTracker, origin);
  11757. return literalValue === IS_SKIPPED_CHAIN ? undefined : literalValue;
  11758. }
  11759. hasEffects(context) {
  11760. return this.expression.hasEffectsAsChainElement(context) === true;
  11761. }
  11762. includePath(path, context) {
  11763. this.included = true;
  11764. this.expression.includePath(path, context);
  11765. }
  11766. removeAnnotations(code) {
  11767. this.expression.removeAnnotations(code);
  11768. }
  11769. }
  11770. ChainExpression.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  11771. ChainExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  11772. class ClassBodyScope extends ChildScope {
  11773. constructor(parent, classNode) {
  11774. const { context } = parent;
  11775. super(parent, context);
  11776. this.variables.set('this', (this.thisVariable = new LocalVariable('this', null, classNode, EMPTY_PATH, context, 'other')));
  11777. this.instanceScope = new ChildScope(this, context);
  11778. this.instanceScope.variables.set('this', new ThisVariable(context));
  11779. }
  11780. findLexicalBoundary() {
  11781. return this;
  11782. }
  11783. }
  11784. class ClassBody extends NodeBase {
  11785. createScope(parentScope) {
  11786. this.scope = new ClassBodyScope(parentScope, this.parent);
  11787. }
  11788. include(context, includeChildrenRecursively) {
  11789. this.included = true;
  11790. this.scope.context.includeVariableInModule(this.scope.thisVariable, UNKNOWN_PATH, context);
  11791. for (const definition of this.body) {
  11792. definition.include(context, includeChildrenRecursively);
  11793. }
  11794. }
  11795. parseNode(esTreeNode) {
  11796. const body = (this.body = new Array(esTreeNode.body.length));
  11797. let index = 0;
  11798. for (const definition of esTreeNode.body) {
  11799. body[index++] = new (this.scope.context.getNodeConstructor(definition.type))(this, definition.static ? this.scope : this.scope.instanceScope).parseNode(definition);
  11800. }
  11801. return super.parseNode(esTreeNode);
  11802. }
  11803. }
  11804. ClassBody.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  11805. ClassBody.prototype.applyDeoptimizations = doNotDeoptimize;
  11806. class ClassExpression extends ClassNode {
  11807. render(code, options, { renderedSurroundingElement } = BLANK) {
  11808. super.render(code, options);
  11809. if (renderedSurroundingElement === ExpressionStatement$1) {
  11810. code.appendRight(this.start, '(');
  11811. code.prependLeft(this.end, ')');
  11812. }
  11813. }
  11814. }
  11815. function tryCastLiteralValueToBoolean(literalValue) {
  11816. if (typeof literalValue === 'symbol') {
  11817. if (literalValue === UnknownFalsyValue) {
  11818. return false;
  11819. }
  11820. if (literalValue === UnknownTruthyValue) {
  11821. return true;
  11822. }
  11823. return UnknownValue;
  11824. }
  11825. return !!literalValue;
  11826. }
  11827. class MultiExpression extends ExpressionEntity {
  11828. constructor(expressions) {
  11829. super();
  11830. this.expressions = expressions;
  11831. }
  11832. deoptimizePath(path) {
  11833. for (const expression of this.expressions) {
  11834. expression.deoptimizePath(path);
  11835. }
  11836. }
  11837. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  11838. return [
  11839. new MultiExpression(this.expressions.map(expression => expression.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0])),
  11840. false
  11841. ];
  11842. }
  11843. hasEffectsOnInteractionAtPath(path, interaction, context) {
  11844. for (const expression of this.expressions) {
  11845. if (expression.hasEffectsOnInteractionAtPath(path, interaction, context))
  11846. return true;
  11847. }
  11848. return false;
  11849. }
  11850. }
  11851. class ConditionalExpression extends NodeBase {
  11852. constructor() {
  11853. super(...arguments);
  11854. this.expressionsToBeDeoptimized = [];
  11855. this.usedBranch = null;
  11856. }
  11857. get isBranchResolutionAnalysed() {
  11858. return isFlagSet(this.flags, 65536 /* Flag.isBranchResolutionAnalysed */);
  11859. }
  11860. set isBranchResolutionAnalysed(value) {
  11861. this.flags = setFlag(this.flags, 65536 /* Flag.isBranchResolutionAnalysed */, value);
  11862. }
  11863. get hasDeoptimizedCache() {
  11864. return isFlagSet(this.flags, 33554432 /* Flag.hasDeoptimizedCache */);
  11865. }
  11866. set hasDeoptimizedCache(value) {
  11867. this.flags = setFlag(this.flags, 33554432 /* Flag.hasDeoptimizedCache */, value);
  11868. }
  11869. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  11870. this.consequent.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  11871. this.alternate.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  11872. }
  11873. deoptimizeCache() {
  11874. if (this.hasDeoptimizedCache)
  11875. return;
  11876. this.hasDeoptimizedCache = true;
  11877. if (this.usedBranch !== null) {
  11878. const unusedBranch = this.usedBranch === this.consequent ? this.alternate : this.consequent;
  11879. this.usedBranch = null;
  11880. unusedBranch.deoptimizePath(UNKNOWN_PATH);
  11881. if (this.included) {
  11882. unusedBranch.includePath(UNKNOWN_PATH, createInclusionContext());
  11883. }
  11884. const { expressionsToBeDeoptimized } = this;
  11885. this.expressionsToBeDeoptimized = EMPTY_ARRAY;
  11886. for (const expression of expressionsToBeDeoptimized) {
  11887. expression.deoptimizeCache();
  11888. }
  11889. }
  11890. }
  11891. deoptimizePath(path) {
  11892. const usedBranch = this.getUsedBranch();
  11893. if (usedBranch) {
  11894. usedBranch.deoptimizePath(path);
  11895. }
  11896. else {
  11897. this.consequent.deoptimizePath(path);
  11898. this.alternate.deoptimizePath(path);
  11899. }
  11900. }
  11901. getLiteralValueAtPath(path, recursionTracker, origin) {
  11902. const usedBranch = this.getUsedBranch();
  11903. if (!usedBranch) {
  11904. if (this.hasDeoptimizedCache) {
  11905. return UnknownValue;
  11906. }
  11907. const consequentValue = this.consequent.getLiteralValueAtPath(path, recursionTracker, origin);
  11908. const castedConsequentValue = tryCastLiteralValueToBoolean(consequentValue);
  11909. if (castedConsequentValue === UnknownValue)
  11910. return UnknownValue;
  11911. const alternateValue = this.alternate.getLiteralValueAtPath(path, recursionTracker, origin);
  11912. const castedAlternateValue = tryCastLiteralValueToBoolean(alternateValue);
  11913. if (castedConsequentValue !== castedAlternateValue)
  11914. return UnknownValue;
  11915. this.expressionsToBeDeoptimized.push(origin);
  11916. if (consequentValue !== alternateValue)
  11917. return castedConsequentValue ? UnknownTruthyValue : UnknownFalsyValue;
  11918. return consequentValue;
  11919. }
  11920. this.expressionsToBeDeoptimized.push(origin);
  11921. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  11922. }
  11923. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  11924. const usedBranch = this.getUsedBranch();
  11925. if (!usedBranch)
  11926. return [
  11927. new MultiExpression([
  11928. this.consequent.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0],
  11929. this.alternate.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0]
  11930. ]),
  11931. false
  11932. ];
  11933. this.expressionsToBeDeoptimized.push(origin);
  11934. return usedBranch.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  11935. }
  11936. hasEffects(context) {
  11937. if (this.test.hasEffects(context))
  11938. return true;
  11939. const usedBranch = this.getUsedBranch();
  11940. if (!usedBranch) {
  11941. return this.consequent.hasEffects(context) || this.alternate.hasEffects(context);
  11942. }
  11943. return usedBranch.hasEffects(context);
  11944. }
  11945. hasEffectsOnInteractionAtPath(path, interaction, context) {
  11946. const usedBranch = this.getUsedBranch();
  11947. if (!usedBranch) {
  11948. return (this.consequent.hasEffectsOnInteractionAtPath(path, interaction, context) ||
  11949. this.alternate.hasEffectsOnInteractionAtPath(path, interaction, context));
  11950. }
  11951. return usedBranch.hasEffectsOnInteractionAtPath(path, interaction, context);
  11952. }
  11953. include(context, includeChildrenRecursively) {
  11954. this.included = true;
  11955. const usedBranch = this.getUsedBranch();
  11956. if (usedBranch === null || includeChildrenRecursively || this.test.shouldBeIncluded(context)) {
  11957. this.test.include(context, includeChildrenRecursively);
  11958. this.consequent.include(context, includeChildrenRecursively);
  11959. this.alternate.include(context, includeChildrenRecursively);
  11960. }
  11961. else {
  11962. usedBranch.include(context, includeChildrenRecursively);
  11963. }
  11964. }
  11965. includePath(path, context) {
  11966. this.included = true;
  11967. const usedBranch = this.getUsedBranch();
  11968. if (usedBranch === null || this.test.shouldBeIncluded(context)) {
  11969. this.consequent.includePath(path, context);
  11970. this.alternate.includePath(path, context);
  11971. }
  11972. else {
  11973. usedBranch.includePath(path, context);
  11974. }
  11975. }
  11976. includeCallArguments(interaction, context) {
  11977. const usedBranch = this.getUsedBranch();
  11978. if (usedBranch) {
  11979. usedBranch.includeCallArguments(interaction, context);
  11980. }
  11981. else {
  11982. this.consequent.includeCallArguments(interaction, context);
  11983. this.alternate.includeCallArguments(interaction, context);
  11984. }
  11985. }
  11986. removeAnnotations(code) {
  11987. this.test.removeAnnotations(code);
  11988. }
  11989. render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  11990. if (this.test.included) {
  11991. this.test.render(code, options, { renderedSurroundingElement });
  11992. this.consequent.render(code, options);
  11993. this.alternate.render(code, options);
  11994. }
  11995. else {
  11996. const usedBranch = this.getUsedBranch();
  11997. const colonPos = findFirstOccurrenceOutsideComment(code.original, ':', this.consequent.end);
  11998. const inclusionStart = findNonWhiteSpace(code.original, (this.consequent.included
  11999. ? findFirstOccurrenceOutsideComment(code.original, '?', this.test.end)
  12000. : colonPos) + 1);
  12001. if (preventASI) {
  12002. removeLineBreaks(code, inclusionStart, usedBranch.start);
  12003. }
  12004. code.remove(this.start, inclusionStart);
  12005. if (this.consequent.included) {
  12006. code.remove(colonPos, this.end);
  12007. }
  12008. this.test.removeAnnotations(code);
  12009. usedBranch.render(code, options, {
  12010. isCalleeOfRenderedParent,
  12011. preventASI: true,
  12012. renderedParentType: renderedParentType || this.parent.type,
  12013. renderedSurroundingElement: renderedSurroundingElement || this.parent.type
  12014. });
  12015. }
  12016. }
  12017. getUsedBranch() {
  12018. if (this.isBranchResolutionAnalysed) {
  12019. return this.usedBranch;
  12020. }
  12021. this.isBranchResolutionAnalysed = true;
  12022. const testValue = tryCastLiteralValueToBoolean(this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this));
  12023. return typeof testValue === 'symbol'
  12024. ? null
  12025. : (this.usedBranch = testValue ? this.consequent : this.alternate);
  12026. }
  12027. }
  12028. ConditionalExpression.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  12029. ConditionalExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  12030. class ContinueStatement extends NodeBase {
  12031. hasEffects(context) {
  12032. if (this.label) {
  12033. if (!context.ignore.labels.has(this.label.name))
  12034. return true;
  12035. context.includedLabels.add(this.label.name);
  12036. }
  12037. else {
  12038. if (!context.ignore.continues)
  12039. return true;
  12040. context.hasContinue = true;
  12041. }
  12042. context.brokenFlow = true;
  12043. return false;
  12044. }
  12045. include(context, includeChildrenRecursively) {
  12046. this.included = true;
  12047. if (this.label) {
  12048. this.label.include(context, includeChildrenRecursively);
  12049. context.includedLabels.add(this.label.name);
  12050. }
  12051. else {
  12052. context.hasContinue = true;
  12053. }
  12054. context.brokenFlow = true;
  12055. }
  12056. }
  12057. ContinueStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  12058. ContinueStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  12059. class DebuggerStatement extends NodeBase {
  12060. hasEffects() {
  12061. return true;
  12062. }
  12063. }
  12064. DebuggerStatement.prototype.includeNode = onlyIncludeSelf;
  12065. class Decorator extends NodeBase {
  12066. hasEffects(context) {
  12067. return (this.expression.hasEffects(context) ||
  12068. this.expression.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_CALL, context));
  12069. }
  12070. }
  12071. Decorator.prototype.includeNode = onlyIncludeSelf;
  12072. function hasLoopBodyEffects(context, body) {
  12073. const { brokenFlow, hasBreak, hasContinue, ignore } = context;
  12074. const { breaks, continues } = ignore;
  12075. ignore.breaks = true;
  12076. ignore.continues = true;
  12077. context.hasBreak = false;
  12078. context.hasContinue = false;
  12079. if (body.hasEffects(context))
  12080. return true;
  12081. ignore.breaks = breaks;
  12082. ignore.continues = continues;
  12083. context.hasBreak = hasBreak;
  12084. context.hasContinue = hasContinue;
  12085. context.brokenFlow = brokenFlow;
  12086. return false;
  12087. }
  12088. function includeLoopBody(context, body, includeChildrenRecursively) {
  12089. const { brokenFlow, hasBreak, hasContinue } = context;
  12090. context.hasBreak = false;
  12091. context.hasContinue = false;
  12092. body.include(context, includeChildrenRecursively, { asSingleStatement: true });
  12093. context.hasBreak = hasBreak;
  12094. context.hasContinue = hasContinue;
  12095. context.brokenFlow = brokenFlow;
  12096. }
  12097. class DoWhileStatement extends NodeBase {
  12098. hasEffects(context) {
  12099. if (this.test.hasEffects(context))
  12100. return true;
  12101. return hasLoopBodyEffects(context, this.body);
  12102. }
  12103. include(context, includeChildrenRecursively) {
  12104. this.included = true;
  12105. this.test.include(context, includeChildrenRecursively);
  12106. includeLoopBody(context, this.body, includeChildrenRecursively);
  12107. }
  12108. }
  12109. DoWhileStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  12110. DoWhileStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  12111. class EmptyStatement extends NodeBase {
  12112. hasEffects() {
  12113. return false;
  12114. }
  12115. }
  12116. EmptyStatement.prototype.includeNode = onlyIncludeSelf;
  12117. class ExportAllDeclaration extends NodeBase {
  12118. hasEffects() {
  12119. return false;
  12120. }
  12121. initialise() {
  12122. super.initialise();
  12123. this.scope.context.addExport(this);
  12124. }
  12125. render(code, _options, nodeRenderOptions) {
  12126. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  12127. }
  12128. }
  12129. ExportAllDeclaration.prototype.needsBoundaries = true;
  12130. ExportAllDeclaration.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  12131. ExportAllDeclaration.prototype.applyDeoptimizations = doNotDeoptimize;
  12132. class ExportNamedDeclaration extends NodeBase {
  12133. bind() {
  12134. // Do not bind specifiers
  12135. this.declaration?.bind();
  12136. }
  12137. hasEffects(context) {
  12138. return !!this.declaration?.hasEffects(context);
  12139. }
  12140. initialise() {
  12141. super.initialise();
  12142. this.scope.context.addExport(this);
  12143. }
  12144. removeAnnotations(code) {
  12145. this.declaration?.removeAnnotations(code);
  12146. }
  12147. render(code, options, nodeRenderOptions) {
  12148. const { start, end } = nodeRenderOptions;
  12149. if (this.declaration === null) {
  12150. code.remove(start, end);
  12151. }
  12152. else {
  12153. let endBoundary = this.declaration.start;
  12154. // the start of the decorator may be before the start of the class declaration
  12155. if (this.declaration instanceof ClassDeclaration) {
  12156. const decorators = this.declaration.decorators;
  12157. for (const decorator of decorators) {
  12158. endBoundary = Math.min(endBoundary, decorator.start);
  12159. }
  12160. if (endBoundary <= this.start) {
  12161. endBoundary = this.declaration.start;
  12162. }
  12163. }
  12164. code.remove(this.start, endBoundary);
  12165. this.declaration.render(code, options, { end, start });
  12166. }
  12167. }
  12168. }
  12169. ExportNamedDeclaration.prototype.needsBoundaries = true;
  12170. ExportNamedDeclaration.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  12171. ExportNamedDeclaration.prototype.applyDeoptimizations = doNotDeoptimize;
  12172. class ExportSpecifier extends NodeBase {
  12173. }
  12174. ExportSpecifier.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  12175. ExportSpecifier.prototype.applyDeoptimizations = doNotDeoptimize;
  12176. class ForInStatement extends NodeBase {
  12177. createScope(parentScope) {
  12178. this.scope = new BlockScope(parentScope);
  12179. }
  12180. hasEffects(context) {
  12181. const { body, deoptimized, left, right } = this;
  12182. if (!deoptimized)
  12183. this.applyDeoptimizations();
  12184. if (left.hasEffectsAsAssignmentTarget(context, false) || right.hasEffects(context))
  12185. return true;
  12186. return hasLoopBodyEffects(context, body);
  12187. }
  12188. include(context, includeChildrenRecursively) {
  12189. const { body, deoptimized, left, right } = this;
  12190. if (!deoptimized)
  12191. this.applyDeoptimizations();
  12192. if (!this.included)
  12193. this.includeNode(context);
  12194. left.includeAsAssignmentTarget(context, includeChildrenRecursively || true, false);
  12195. right.include(context, includeChildrenRecursively);
  12196. includeLoopBody(context, body, includeChildrenRecursively);
  12197. }
  12198. includeNode(context) {
  12199. this.included = true;
  12200. if (!this.deoptimized)
  12201. this.applyDeoptimizations();
  12202. this.right.includePath(UNKNOWN_PATH, context);
  12203. }
  12204. initialise() {
  12205. super.initialise();
  12206. this.left.setAssignedValue(UNKNOWN_EXPRESSION);
  12207. }
  12208. render(code, options) {
  12209. this.left.render(code, options, NO_SEMICOLON);
  12210. this.right.render(code, options, NO_SEMICOLON);
  12211. // handle no space between "in" and the right side
  12212. if (code.original.charCodeAt(this.right.start - 1) === 110 /* n */) {
  12213. code.prependLeft(this.right.start, ' ');
  12214. }
  12215. this.body.render(code, options);
  12216. }
  12217. applyDeoptimizations() {
  12218. this.deoptimized = true;
  12219. this.left.deoptimizePath(EMPTY_PATH);
  12220. this.scope.context.requestTreeshakingPass();
  12221. }
  12222. }
  12223. class ForOfStatement extends NodeBase {
  12224. get await() {
  12225. return isFlagSet(this.flags, 131072 /* Flag.await */);
  12226. }
  12227. set await(value) {
  12228. this.flags = setFlag(this.flags, 131072 /* Flag.await */, value);
  12229. }
  12230. createScope(parentScope) {
  12231. this.scope = new BlockScope(parentScope);
  12232. }
  12233. hasEffects() {
  12234. if (!this.deoptimized)
  12235. this.applyDeoptimizations();
  12236. // Placeholder until proper Symbol.Iterator support
  12237. return true;
  12238. }
  12239. include(context, includeChildrenRecursively) {
  12240. const { body, deoptimized, left, right } = this;
  12241. if (!deoptimized)
  12242. this.applyDeoptimizations();
  12243. if (!this.included)
  12244. this.includeNode(context);
  12245. left.includeAsAssignmentTarget(context, includeChildrenRecursively || true, false);
  12246. right.include(context, includeChildrenRecursively);
  12247. includeLoopBody(context, body, includeChildrenRecursively);
  12248. }
  12249. includeNode(context) {
  12250. this.included = true;
  12251. if (!this.deoptimized)
  12252. this.applyDeoptimizations();
  12253. this.right.includePath(UNKNOWN_PATH, context);
  12254. }
  12255. initialise() {
  12256. super.initialise();
  12257. this.left.setAssignedValue(UNKNOWN_EXPRESSION);
  12258. }
  12259. render(code, options) {
  12260. this.left.render(code, options, NO_SEMICOLON);
  12261. this.right.render(code, options, NO_SEMICOLON);
  12262. // handle no space between "of" and the right side
  12263. if (code.original.charCodeAt(this.right.start - 1) === 102 /* f */) {
  12264. code.prependLeft(this.right.start, ' ');
  12265. }
  12266. this.body.render(code, options);
  12267. }
  12268. applyDeoptimizations() {
  12269. this.deoptimized = true;
  12270. this.left.deoptimizePath(EMPTY_PATH);
  12271. this.right.deoptimizePath(UNKNOWN_PATH);
  12272. this.scope.context.requestTreeshakingPass();
  12273. }
  12274. }
  12275. class ForStatement extends NodeBase {
  12276. createScope(parentScope) {
  12277. this.scope = new BlockScope(parentScope);
  12278. }
  12279. hasEffects(context) {
  12280. if (this.init?.hasEffects(context) ||
  12281. this.test?.hasEffects(context) ||
  12282. this.update?.hasEffects(context)) {
  12283. return true;
  12284. }
  12285. return hasLoopBodyEffects(context, this.body);
  12286. }
  12287. include(context, includeChildrenRecursively) {
  12288. this.included = true;
  12289. this.init?.include(context, includeChildrenRecursively, {
  12290. asSingleStatement: true
  12291. });
  12292. this.test?.include(context, includeChildrenRecursively);
  12293. this.update?.include(context, includeChildrenRecursively);
  12294. includeLoopBody(context, this.body, includeChildrenRecursively);
  12295. }
  12296. render(code, options) {
  12297. this.init?.render(code, options, NO_SEMICOLON);
  12298. this.test?.render(code, options, NO_SEMICOLON);
  12299. this.update?.render(code, options, NO_SEMICOLON);
  12300. this.body.render(code, options);
  12301. }
  12302. }
  12303. ForStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  12304. ForStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  12305. class FunctionExpression extends FunctionNode {
  12306. createScope(parentScope) {
  12307. super.createScope((this.idScope = new ChildScope(parentScope, parentScope.context)));
  12308. }
  12309. parseNode(esTreeNode) {
  12310. if (esTreeNode.id !== null) {
  12311. this.id = new Identifier(this, this.idScope).parseNode(esTreeNode.id);
  12312. }
  12313. return super.parseNode(esTreeNode);
  12314. }
  12315. onlyFunctionCallUsed() {
  12316. const isIIFE = this.parent.type === CallExpression$1 &&
  12317. this.parent.callee === this &&
  12318. (this.id === null || this.id.variable.getOnlyFunctionCallUsed());
  12319. return isIIFE || super.onlyFunctionCallUsed();
  12320. }
  12321. render(code, options, { renderedSurroundingElement } = BLANK) {
  12322. super.render(code, options);
  12323. if (renderedSurroundingElement === ExpressionStatement$1) {
  12324. code.appendRight(this.start, '(');
  12325. code.prependLeft(this.end, ')');
  12326. }
  12327. }
  12328. }
  12329. class TrackingScope extends BlockScope {
  12330. constructor() {
  12331. super(...arguments);
  12332. this.hoistedDeclarations = [];
  12333. }
  12334. addDeclaration(identifier, context, init, destructuredInitPath, kind) {
  12335. this.hoistedDeclarations.push(identifier);
  12336. return super.addDeclaration(identifier, context, init, destructuredInitPath, kind);
  12337. }
  12338. }
  12339. const unset = Symbol('unset');
  12340. class IfStatement extends NodeBase {
  12341. constructor() {
  12342. super(...arguments);
  12343. this.testValue = unset;
  12344. }
  12345. deoptimizeCache() {
  12346. this.testValue = UnknownValue;
  12347. }
  12348. hasEffects(context) {
  12349. if (this.test.hasEffects(context)) {
  12350. return true;
  12351. }
  12352. const testValue = this.getTestValue();
  12353. if (typeof testValue === 'symbol') {
  12354. const { brokenFlow } = context;
  12355. if (this.consequent.hasEffects(context))
  12356. return true;
  12357. const consequentBrokenFlow = context.brokenFlow;
  12358. context.brokenFlow = brokenFlow;
  12359. if (this.alternate === null)
  12360. return false;
  12361. if (this.alternate.hasEffects(context))
  12362. return true;
  12363. context.brokenFlow = context.brokenFlow && consequentBrokenFlow;
  12364. return false;
  12365. }
  12366. return testValue ? this.consequent.hasEffects(context) : !!this.alternate?.hasEffects(context);
  12367. }
  12368. include(context, includeChildrenRecursively) {
  12369. this.included = true;
  12370. if (includeChildrenRecursively) {
  12371. this.includeRecursively(includeChildrenRecursively, context);
  12372. }
  12373. else {
  12374. const testValue = this.getTestValue();
  12375. if (typeof testValue === 'symbol') {
  12376. this.includeUnknownTest(context);
  12377. }
  12378. else {
  12379. this.includeKnownTest(context, testValue);
  12380. }
  12381. }
  12382. }
  12383. parseNode(esTreeNode) {
  12384. this.consequent = new (this.scope.context.getNodeConstructor(esTreeNode.consequent.type))(this, (this.consequentScope = new TrackingScope(this.scope))).parseNode(esTreeNode.consequent);
  12385. if (esTreeNode.alternate) {
  12386. this.alternate = new (this.scope.context.getNodeConstructor(esTreeNode.alternate.type))(this, (this.alternateScope = new TrackingScope(this.scope))).parseNode(esTreeNode.alternate);
  12387. }
  12388. return super.parseNode(esTreeNode);
  12389. }
  12390. render(code, options) {
  12391. const { snippets: { getPropertyAccess } } = options;
  12392. // Note that unknown test values are always included
  12393. const testValue = this.getTestValue();
  12394. const hoistedDeclarations = [];
  12395. const includesIfElse = this.test.included;
  12396. const noTreeshake = !this.scope.context.options.treeshake;
  12397. if (includesIfElse) {
  12398. this.test.render(code, options);
  12399. }
  12400. else {
  12401. code.remove(this.start, this.consequent.start);
  12402. }
  12403. if (this.consequent.included && (noTreeshake || typeof testValue === 'symbol' || testValue)) {
  12404. this.consequent.render(code, options);
  12405. }
  12406. else {
  12407. code.overwrite(this.consequent.start, this.consequent.end, includesIfElse ? ';' : '');
  12408. hoistedDeclarations.push(...this.consequentScope.hoistedDeclarations);
  12409. }
  12410. if (this.alternate) {
  12411. if (this.alternate.included && (noTreeshake || typeof testValue === 'symbol' || !testValue)) {
  12412. if (includesIfElse) {
  12413. if (code.original.charCodeAt(this.alternate.start - 1) === 101) {
  12414. code.prependLeft(this.alternate.start, ' ');
  12415. }
  12416. }
  12417. else {
  12418. code.remove(this.consequent.end, this.alternate.start);
  12419. }
  12420. this.alternate.render(code, options);
  12421. }
  12422. else {
  12423. if (includesIfElse && this.shouldKeepAlternateBranch()) {
  12424. code.overwrite(this.alternate.start, this.end, ';');
  12425. }
  12426. else {
  12427. code.remove(this.consequent.end, this.end);
  12428. }
  12429. hoistedDeclarations.push(...this.alternateScope.hoistedDeclarations);
  12430. }
  12431. }
  12432. this.renderHoistedDeclarations(hoistedDeclarations, code, getPropertyAccess);
  12433. }
  12434. getTestValue() {
  12435. if (this.testValue === unset) {
  12436. return (this.testValue = tryCastLiteralValueToBoolean(this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this)));
  12437. }
  12438. return this.testValue;
  12439. }
  12440. includeKnownTest(context, testValue) {
  12441. if (this.test.shouldBeIncluded(context)) {
  12442. this.test.include(context, false);
  12443. }
  12444. if (testValue && this.consequent.shouldBeIncluded(context)) {
  12445. this.consequent.include(context, false, { asSingleStatement: true });
  12446. }
  12447. if (!testValue && this.alternate?.shouldBeIncluded(context)) {
  12448. this.alternate.include(context, false, { asSingleStatement: true });
  12449. }
  12450. }
  12451. includeRecursively(includeChildrenRecursively, context) {
  12452. this.test.include(context, includeChildrenRecursively);
  12453. this.consequent.include(context, includeChildrenRecursively);
  12454. this.alternate?.include(context, includeChildrenRecursively);
  12455. }
  12456. includeUnknownTest(context) {
  12457. this.test.include(context, false);
  12458. const { brokenFlow } = context;
  12459. let consequentBrokenFlow = false;
  12460. if (this.consequent.shouldBeIncluded(context)) {
  12461. this.consequent.include(context, false, { asSingleStatement: true });
  12462. consequentBrokenFlow = context.brokenFlow;
  12463. context.brokenFlow = brokenFlow;
  12464. }
  12465. if (this.alternate?.shouldBeIncluded(context)) {
  12466. this.alternate.include(context, false, { asSingleStatement: true });
  12467. context.brokenFlow = context.brokenFlow && consequentBrokenFlow;
  12468. }
  12469. }
  12470. renderHoistedDeclarations(hoistedDeclarations, code, getPropertyAccess) {
  12471. const hoistedVariables = [
  12472. ...new Set(hoistedDeclarations.map(identifier => {
  12473. const variable = identifier.variable;
  12474. return variable.included ? variable.getName(getPropertyAccess) : '';
  12475. }))
  12476. ]
  12477. .filter(Boolean)
  12478. .join(', ');
  12479. if (hoistedVariables) {
  12480. const parentType = this.parent.type;
  12481. const needsBraces = parentType !== Program$1 && parentType !== BlockStatement$1;
  12482. code.prependRight(this.start, `${needsBraces ? '{ ' : ''}var ${hoistedVariables}; `);
  12483. if (needsBraces) {
  12484. code.appendLeft(this.end, ` }`);
  12485. }
  12486. }
  12487. }
  12488. shouldKeepAlternateBranch() {
  12489. let currentParent = this.parent;
  12490. do {
  12491. if (currentParent instanceof IfStatement && currentParent.alternate) {
  12492. return true;
  12493. }
  12494. if (currentParent instanceof BlockStatement) {
  12495. return false;
  12496. }
  12497. currentParent = currentParent.parent;
  12498. } while (currentParent);
  12499. return false;
  12500. }
  12501. }
  12502. IfStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  12503. IfStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  12504. class ImportAttribute extends NodeBase {
  12505. }
  12506. class ImportDeclaration extends NodeBase {
  12507. // Do not bind specifiers or attributes
  12508. bind() { }
  12509. hasEffects() {
  12510. return false;
  12511. }
  12512. initialise() {
  12513. super.initialise();
  12514. this.scope.context.addImport(this);
  12515. }
  12516. render(code, _options, nodeRenderOptions) {
  12517. code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
  12518. }
  12519. }
  12520. ImportDeclaration.prototype.needsBoundaries = true;
  12521. ImportDeclaration.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  12522. ImportDeclaration.prototype.applyDeoptimizations = doNotDeoptimize;
  12523. class ImportDefaultSpecifier extends NodeBase {
  12524. }
  12525. ImportDefaultSpecifier.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  12526. ImportDefaultSpecifier.prototype.applyDeoptimizations = doNotDeoptimize;
  12527. class ObjectPromiseHandler {
  12528. constructor(resolvedVariable) {
  12529. this.interaction = {
  12530. args: [null, resolvedVariable],
  12531. type: INTERACTION_CALLED,
  12532. withNew: false
  12533. };
  12534. }
  12535. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  12536. deoptimizeInteraction(interaction);
  12537. if (interaction.type === INTERACTION_CALLED &&
  12538. path.length === 0 &&
  12539. (isFunctionExpressionNode(interaction.args[1]) ||
  12540. isArrowFunctionExpressionNode(interaction.args[1]))) {
  12541. interaction.args[1].deoptimizeArgumentsOnInteractionAtPath(this.interaction, [], recursionTracker);
  12542. }
  12543. }
  12544. includeCallArguments(interaction, context) {
  12545. // This includes the function call itself
  12546. includeInteractionWithoutThis(interaction, context);
  12547. if (interaction.type === INTERACTION_CALLED &&
  12548. (isFunctionExpressionNode(interaction.args[1]) ||
  12549. isArrowFunctionExpressionNode(interaction.args[1]))) {
  12550. interaction.args[1].includeCallArguments(this.interaction, context);
  12551. }
  12552. }
  12553. }
  12554. class EmptyPromiseHandler {
  12555. deoptimizeArgumentsOnInteractionAtPath(interaction) {
  12556. deoptimizeInteraction(interaction);
  12557. }
  12558. includeCallArguments(interaction, context) {
  12559. includeInteractionWithoutThis(interaction, context);
  12560. }
  12561. }
  12562. function getChunkInfoWithPath(chunk) {
  12563. return { fileName: chunk.getFileName(), ...chunk.getPreRenderedChunkInfo() };
  12564. }
  12565. class ImportExpression extends NodeBase {
  12566. constructor() {
  12567. super(...arguments);
  12568. this.inlineNamespace = null;
  12569. this.resolution = null;
  12570. this.attributes = null;
  12571. this.mechanism = null;
  12572. this.namespaceExportName = undefined;
  12573. this.localResolution = null;
  12574. this.resolutionString = null;
  12575. }
  12576. get shouldIncludeDynamicAttributes() {
  12577. return isFlagSet(this.flags, 268435456 /* Flag.shouldIncludeDynamicAttributes */);
  12578. }
  12579. set shouldIncludeDynamicAttributes(value) {
  12580. this.flags = setFlag(this.flags, 268435456 /* Flag.shouldIncludeDynamicAttributes */, value);
  12581. }
  12582. bind() {
  12583. const { options, parent, resolution, source } = this;
  12584. source.bind();
  12585. options?.bind();
  12586. // Check if we resolved to a Module without using instanceof
  12587. if (typeof resolution !== 'object' || !resolution || !('namespace' in resolution)) {
  12588. return;
  12589. }
  12590. // In these cases, we can track exactly what is included or deoptimized:
  12591. // * import('foo'); // as statement
  12592. // * await import('foo') // use as awaited expression in any way
  12593. // * import('foo').then(n => {...}) // only if .then is called directly on the import()
  12594. if (isExpressionStatementNode(parent) || isAwaitExpressionNode(parent)) {
  12595. this.localResolution = { resolution, tracked: true };
  12596. return;
  12597. }
  12598. if (!isMemberExpressionNode(parent)) {
  12599. this.localResolution = { resolution, tracked: false };
  12600. return;
  12601. }
  12602. let currentParent = parent;
  12603. // eslint-disable-next-line @typescript-eslint/no-this-alias
  12604. let callExpression = this;
  12605. while (true) {
  12606. if (currentParent.computed ||
  12607. currentParent.object !== callExpression ||
  12608. !isIdentifierNode(currentParent.property) ||
  12609. !isCallExpressionNode(currentParent.parent)) {
  12610. break;
  12611. }
  12612. const propertyName = currentParent.property.name;
  12613. callExpression = currentParent.parent;
  12614. if (propertyName === 'then') {
  12615. const firstArgument = callExpression.arguments[0];
  12616. if (firstArgument === undefined ||
  12617. isFunctionExpressionNode(firstArgument) ||
  12618. isArrowFunctionExpressionNode(firstArgument)) {
  12619. currentParent.promiseHandler = new ObjectPromiseHandler(getDynamicNamespaceVariable(resolution.namespace));
  12620. this.localResolution = { resolution, tracked: true };
  12621. return;
  12622. }
  12623. }
  12624. else if (propertyName === 'catch' || propertyName === 'finally') {
  12625. if (isMemberExpressionNode(callExpression.parent)) {
  12626. currentParent.promiseHandler = new EmptyPromiseHandler();
  12627. currentParent = callExpression.parent;
  12628. continue;
  12629. }
  12630. if (isExpressionStatementNode(callExpression.parent)) {
  12631. currentParent.promiseHandler = new EmptyPromiseHandler();
  12632. this.localResolution = { resolution, tracked: true };
  12633. return;
  12634. }
  12635. }
  12636. break;
  12637. }
  12638. this.localResolution = { resolution, tracked: false };
  12639. }
  12640. deoptimizePath(path) {
  12641. this.localResolution?.resolution?.namespace.deoptimizePath(path);
  12642. }
  12643. hasEffects() {
  12644. return true;
  12645. }
  12646. include(context, includeChildrenRecursively) {
  12647. if (!this.included)
  12648. this.includeNode(context);
  12649. this.source.include(context, includeChildrenRecursively);
  12650. if (this.shouldIncludeDynamicAttributes) {
  12651. this.options?.include(context, includeChildrenRecursively);
  12652. }
  12653. if (includeChildrenRecursively) {
  12654. this.localResolution?.resolution.includeAllExports();
  12655. }
  12656. }
  12657. includeNode(context) {
  12658. this.included = true;
  12659. const { localResolution, scope, shouldIncludeDynamicAttributes } = this;
  12660. if (shouldIncludeDynamicAttributes) {
  12661. this.options?.includePath(UNKNOWN_PATH, context);
  12662. }
  12663. scope.context.includeDynamicImport(this);
  12664. scope.addAccessedDynamicImport(this);
  12665. if (localResolution) {
  12666. if (localResolution.tracked) {
  12667. localResolution.resolution.includeModuleInExecution();
  12668. }
  12669. else {
  12670. localResolution.resolution.includeAllExports();
  12671. }
  12672. }
  12673. }
  12674. includePath(path, context) {
  12675. if (!this.included)
  12676. this.includeNode(context);
  12677. this.localResolution?.resolution?.namespace.includeMemberPath(path, context);
  12678. }
  12679. initialise() {
  12680. super.initialise();
  12681. this.scope.context.addDynamicImport(this);
  12682. }
  12683. parseNode(esTreeNode) {
  12684. this.sourceAstNode = esTreeNode.source;
  12685. return super.parseNode(esTreeNode);
  12686. }
  12687. render(code, options) {
  12688. const { snippets: { _, getDirectReturnFunction, getObject, getPropertyAccess }, importAttributesKey } = options;
  12689. if (this.inlineNamespace) {
  12690. const [left, right] = getDirectReturnFunction([], {
  12691. functionReturn: true,
  12692. lineBreakIndent: null,
  12693. name: null
  12694. });
  12695. code.overwrite(this.start, this.end, `Promise.resolve().then(${left}${this.inlineNamespace.getName(getPropertyAccess)}${right})`);
  12696. return;
  12697. }
  12698. if (this.mechanism) {
  12699. code.overwrite(this.start, findFirstOccurrenceOutsideComment(code.original, '(', this.start + 6) + 1, this.mechanism.left);
  12700. code.overwrite(this.end - 1, this.end, this.mechanism.right);
  12701. }
  12702. if (this.resolutionString) {
  12703. code.overwrite(this.source.start, this.source.end, this.resolutionString);
  12704. if (this.namespaceExportName) {
  12705. const [left, right] = getDirectReturnFunction(['n'], {
  12706. functionReturn: true,
  12707. lineBreakIndent: null,
  12708. name: null
  12709. });
  12710. code.prependLeft(this.end, `.then(${left}n.${this.namespaceExportName}${right})`);
  12711. }
  12712. }
  12713. else {
  12714. this.source.render(code, options);
  12715. }
  12716. if (this.attributes !== true) {
  12717. if (this.options) {
  12718. code.overwrite(this.source.end, this.end - 1, '', { contentOnly: true });
  12719. }
  12720. if (this.attributes) {
  12721. code.appendLeft(this.end - 1, `,${_}${getObject([[importAttributesKey, this.attributes]], {
  12722. lineBreakIndent: null
  12723. })}`);
  12724. }
  12725. }
  12726. }
  12727. setExternalResolution(exportMode, options, snippets, pluginDriver, accessedGlobalsByScope, resolutionString, namespaceExportName, attributes, ownChunk, targetChunk) {
  12728. const { format } = options;
  12729. this.inlineNamespace = null;
  12730. this.resolutionString = resolutionString;
  12731. this.namespaceExportName = namespaceExportName;
  12732. this.attributes = attributes;
  12733. const accessedGlobals = [...(accessedImportGlobals[format] || [])];
  12734. let helper;
  12735. ({ helper, mechanism: this.mechanism } = this.getDynamicImportMechanismAndHelper(exportMode, options, snippets, pluginDriver, ownChunk, targetChunk));
  12736. if (helper) {
  12737. accessedGlobals.push(helper);
  12738. }
  12739. if (accessedGlobals.length > 0) {
  12740. this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
  12741. }
  12742. }
  12743. setInternalResolution(inlineNamespace) {
  12744. this.inlineNamespace = inlineNamespace;
  12745. }
  12746. getDynamicImportMechanismAndHelper(exportMode, { compact, dynamicImportInCjs, format, generatedCode: { arrowFunctions }, interop }, { _, getDirectReturnFunction, getDirectReturnIifeLeft }, pluginDriver, ownChunk, targetChunk) {
  12747. const { resolution, scope } = this;
  12748. const mechanism = pluginDriver.hookFirstSync('renderDynamicImport', [
  12749. {
  12750. chunk: getChunkInfoWithPath(ownChunk),
  12751. customResolution: typeof resolution === 'string' ? resolution : null,
  12752. format,
  12753. getTargetChunkImports() {
  12754. if (targetChunk === null)
  12755. return null;
  12756. const chunkInfos = [];
  12757. const importerPath = ownChunk.getFileName();
  12758. for (const dep of targetChunk.dependencies) {
  12759. const resolvedImportPath = `'${dep.getImportPath(importerPath)}'`;
  12760. if (dep instanceof ExternalChunk) {
  12761. chunkInfos.push({
  12762. fileName: dep.getFileName(),
  12763. resolvedImportPath,
  12764. type: 'external'
  12765. });
  12766. }
  12767. else {
  12768. chunkInfos.push({
  12769. chunk: dep.getPreRenderedChunkInfo(),
  12770. fileName: dep.getFileName(),
  12771. resolvedImportPath,
  12772. type: 'internal'
  12773. });
  12774. }
  12775. }
  12776. return chunkInfos;
  12777. },
  12778. moduleId: scope.context.module.id,
  12779. targetChunk: targetChunk ? getChunkInfoWithPath(targetChunk) : null,
  12780. targetModuleAttributes: resolution && typeof resolution !== 'string' ? resolution.info.attributes : {},
  12781. targetModuleId: resolution && typeof resolution !== 'string' ? resolution.id : null
  12782. }
  12783. ]);
  12784. if (mechanism) {
  12785. return { helper: null, mechanism };
  12786. }
  12787. const hasDynamicTarget = !resolution || typeof resolution === 'string';
  12788. switch (format) {
  12789. case 'cjs': {
  12790. if (dynamicImportInCjs &&
  12791. (!resolution || typeof resolution === 'string' || resolution instanceof ExternalModule)) {
  12792. return { helper: null, mechanism: null };
  12793. }
  12794. const helper = getInteropHelper(resolution, exportMode, interop);
  12795. let left = `require(`;
  12796. let right = `)`;
  12797. if (helper) {
  12798. left = `/*#__PURE__*/${helper}(${left}`;
  12799. right += ')';
  12800. }
  12801. const [functionLeft, functionRight] = getDirectReturnFunction([], {
  12802. functionReturn: true,
  12803. lineBreakIndent: null,
  12804. name: null
  12805. });
  12806. left = `Promise.resolve().then(${functionLeft}${left}`;
  12807. right += `${functionRight})`;
  12808. if (!arrowFunctions && hasDynamicTarget) {
  12809. left = getDirectReturnIifeLeft(['t'], `${left}t${right}`, {
  12810. needsArrowReturnParens: false,
  12811. needsWrappedFunction: true
  12812. });
  12813. right = ')';
  12814. }
  12815. return {
  12816. helper,
  12817. mechanism: { left, right }
  12818. };
  12819. }
  12820. case 'amd': {
  12821. const resolve = compact ? 'c' : 'resolve';
  12822. const reject = compact ? 'e' : 'reject';
  12823. const helper = getInteropHelper(resolution, exportMode, interop);
  12824. const [resolveLeft, resolveRight] = getDirectReturnFunction(['m'], {
  12825. functionReturn: false,
  12826. lineBreakIndent: null,
  12827. name: null
  12828. });
  12829. const resolveNamespace = helper
  12830. ? `${resolveLeft}${resolve}(/*#__PURE__*/${helper}(m))${resolveRight}`
  12831. : resolve;
  12832. const [handlerLeft, handlerRight] = getDirectReturnFunction([resolve, reject], {
  12833. functionReturn: false,
  12834. lineBreakIndent: null,
  12835. name: null
  12836. });
  12837. let left = `new Promise(${handlerLeft}require([`;
  12838. let right = `],${_}${resolveNamespace},${_}${reject})${handlerRight})`;
  12839. if (!arrowFunctions && hasDynamicTarget) {
  12840. left = getDirectReturnIifeLeft(['t'], `${left}t${right}`, {
  12841. needsArrowReturnParens: false,
  12842. needsWrappedFunction: true
  12843. });
  12844. right = ')';
  12845. }
  12846. return {
  12847. helper,
  12848. mechanism: { left, right }
  12849. };
  12850. }
  12851. case 'system': {
  12852. return {
  12853. helper: null,
  12854. mechanism: {
  12855. left: 'module.import(',
  12856. right: ')'
  12857. }
  12858. };
  12859. }
  12860. }
  12861. return { helper: null, mechanism: null };
  12862. }
  12863. }
  12864. ImportExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  12865. function getInteropHelper(resolution, exportMode, interop) {
  12866. return exportMode === 'external'
  12867. ? namespaceInteropHelpersByInteropType[interop(resolution instanceof ExternalModule ? resolution.id : null)]
  12868. : exportMode === 'default'
  12869. ? INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE
  12870. : null;
  12871. }
  12872. const accessedImportGlobals = {
  12873. amd: ['require'],
  12874. cjs: ['require'],
  12875. system: ['module']
  12876. };
  12877. class ImportNamespaceSpecifier extends NodeBase {
  12878. }
  12879. ImportNamespaceSpecifier.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  12880. ImportNamespaceSpecifier.prototype.applyDeoptimizations = doNotDeoptimize;
  12881. class ImportSpecifier extends NodeBase {
  12882. }
  12883. ImportSpecifier.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  12884. ImportSpecifier.prototype.applyDeoptimizations = doNotDeoptimize;
  12885. class JSXIdentifier extends IdentifierBase {
  12886. constructor() {
  12887. super(...arguments);
  12888. this.isNativeElement = false;
  12889. }
  12890. bind() {
  12891. const type = this.getType();
  12892. if (type === 0 /* IdentifierType.Reference */) {
  12893. this.variable = this.scope.findVariable(this.name);
  12894. this.variable.addReference(this);
  12895. }
  12896. else if (type === 1 /* IdentifierType.NativeElementName */) {
  12897. this.isNativeElement = true;
  12898. }
  12899. }
  12900. include(context) {
  12901. if (!this.included)
  12902. this.includeNode(context);
  12903. }
  12904. includeNode(context) {
  12905. this.included = true;
  12906. if (!this.deoptimized)
  12907. this.applyDeoptimizations();
  12908. if (this.variable !== null) {
  12909. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  12910. }
  12911. }
  12912. includePath(path, context) {
  12913. if (!this.included) {
  12914. this.included = true;
  12915. if (this.variable !== null) {
  12916. this.scope.context.includeVariableInModule(this.variable, path, context);
  12917. }
  12918. }
  12919. else if (path.length > 0) {
  12920. this.variable?.includePath(path, context);
  12921. }
  12922. }
  12923. render(code, { snippets: { getPropertyAccess }, useOriginalName }) {
  12924. if (this.variable) {
  12925. const name = this.variable.getName(getPropertyAccess, useOriginalName);
  12926. if (name !== this.name) {
  12927. code.overwrite(this.start, this.end, name, {
  12928. contentOnly: true,
  12929. storeName: true
  12930. });
  12931. }
  12932. }
  12933. else if (this.isNativeElement &&
  12934. this.scope.context.options.jsx.mode !== 'preserve') {
  12935. code.update(this.start, this.end, JSON.stringify(this.name));
  12936. }
  12937. }
  12938. getType() {
  12939. switch (this.parent.type) {
  12940. case 'JSXOpeningElement':
  12941. case 'JSXClosingElement': {
  12942. return this.name.startsWith(this.name.charAt(0).toUpperCase())
  12943. ? 0 /* IdentifierType.Reference */
  12944. : 1 /* IdentifierType.NativeElementName */;
  12945. }
  12946. case 'JSXMemberExpression': {
  12947. return this.parent.object === this
  12948. ? 0 /* IdentifierType.Reference */
  12949. : 2 /* IdentifierType.Other */;
  12950. }
  12951. case 'JSXAttribute':
  12952. case 'JSXNamespacedName': {
  12953. return 2 /* IdentifierType.Other */;
  12954. }
  12955. default: {
  12956. /* istanbul ignore next */
  12957. throw new Error(`Unexpected parent node type for JSXIdentifier: ${this.parent.type}`);
  12958. }
  12959. }
  12960. }
  12961. }
  12962. class JSXAttribute extends NodeBase {
  12963. render(code, options, { jsxMode } = BLANK) {
  12964. super.render(code, options);
  12965. if (['classic', 'automatic'].includes(jsxMode)) {
  12966. const { name, value } = this;
  12967. const key = name instanceof JSXIdentifier ? name.name : `${name.namespace.name}:${name.name.name}`;
  12968. if (!(jsxMode === 'automatic' && key === 'key')) {
  12969. const safeKey = stringifyObjectKeyIfNeeded(key);
  12970. if (key !== safeKey) {
  12971. code.overwrite(name.start, name.end, safeKey, { contentOnly: true });
  12972. }
  12973. if (value) {
  12974. code.overwrite(name.end, value.start, ': ', { contentOnly: true });
  12975. // foo="aa \n aa"
  12976. if (value instanceof Literal &&
  12977. typeof value.value === 'string' &&
  12978. value.value.includes('\n')) {
  12979. code.overwrite(value.start, value.end, JSON.stringify(value.value), {
  12980. contentOnly: true
  12981. });
  12982. }
  12983. }
  12984. else {
  12985. code.appendLeft(name.end, ': true');
  12986. }
  12987. }
  12988. }
  12989. }
  12990. }
  12991. JSXAttribute.prototype.includeNode = onlyIncludeSelf;
  12992. class JSXClosingBase extends NodeBase {
  12993. render(code, options) {
  12994. const { mode } = this.scope.context.options.jsx;
  12995. if (mode !== 'preserve') {
  12996. code.overwrite(this.start, this.end, ')', { contentOnly: true });
  12997. }
  12998. else {
  12999. super.render(code, options);
  13000. }
  13001. }
  13002. }
  13003. JSXClosingBase.prototype.includeNode = onlyIncludeSelf;
  13004. class JSXClosingElement extends JSXClosingBase {
  13005. }
  13006. class JSXClosingFragment extends JSXClosingBase {
  13007. }
  13008. class JSXSpreadAttribute extends NodeBase {
  13009. render(code, options) {
  13010. this.argument.render(code, options);
  13011. const { mode } = this.scope.context.options.jsx;
  13012. if (mode !== 'preserve') {
  13013. code.overwrite(this.start, this.argument.start, '', { contentOnly: true });
  13014. code.overwrite(this.argument.end, this.end, '', { contentOnly: true });
  13015. }
  13016. }
  13017. }
  13018. class JSXEmptyExpression extends NodeBase {
  13019. }
  13020. JSXEmptyExpression.prototype.includeNode = onlyIncludeSelf;
  13021. class JSXExpressionContainer extends NodeBase {
  13022. includeNode(context) {
  13023. this.included = true;
  13024. if (!this.deoptimized)
  13025. this.applyDeoptimizations();
  13026. this.expression.includePath(UNKNOWN_PATH, context);
  13027. }
  13028. render(code, options) {
  13029. const { mode } = this.scope.context.options.jsx;
  13030. if (mode !== 'preserve') {
  13031. code.remove(this.start, this.expression.start);
  13032. code.remove(this.expression.end, this.end);
  13033. }
  13034. this.expression.render(code, options);
  13035. }
  13036. }
  13037. const RE_WHITESPACE_TRIM = /^[ \t]*\r?\n[ \t\r\n]*|[ \t]*\r?\n[ \t\r\n]*$/g;
  13038. const RE_WHITESPACE_MERGE = /[ \t]*\r?\n[ \t\r\n]*/g;
  13039. class JSXText extends NodeBase {
  13040. shouldRender() {
  13041. return !!this.getRenderedText();
  13042. }
  13043. render(code) {
  13044. const { mode } = this.scope.context.options.jsx;
  13045. if (mode !== 'preserve') {
  13046. code.overwrite(this.start, this.end, JSON.stringify(this.getRenderedText()), {
  13047. contentOnly: true
  13048. });
  13049. }
  13050. }
  13051. getRenderedText() {
  13052. if (this.renderedText === undefined)
  13053. this.renderedText = this.value
  13054. .replace(RE_WHITESPACE_TRIM, '')
  13055. .replace(RE_WHITESPACE_MERGE, ' ');
  13056. return this.renderedText;
  13057. }
  13058. }
  13059. JSXText.prototype.includeNode = onlyIncludeSelf;
  13060. function getRenderedJsxChildren(children) {
  13061. let renderedChildren = 0;
  13062. for (const child of children) {
  13063. if (!(child instanceof JSXExpressionContainer && child.expression instanceof JSXEmptyExpression) &&
  13064. (!(child instanceof JSXText) || child.shouldRender())) {
  13065. renderedChildren++;
  13066. }
  13067. }
  13068. return renderedChildren;
  13069. }
  13070. function getAndIncludeFactoryVariable(factory, preserve, importSource, node, context) {
  13071. const [baseName, nestedName] = factory.split('.');
  13072. let factoryVariable;
  13073. if (importSource) {
  13074. factoryVariable = node.scope.context.getImportedJsxFactoryVariable(nestedName ? 'default' : baseName, node.start, importSource);
  13075. if (preserve) {
  13076. // This pretends we are accessing an included global variable of the same name
  13077. const globalVariable = node.scope.findGlobal(baseName);
  13078. globalVariable.includePath(UNKNOWN_PATH, context);
  13079. // This excludes this variable from renaming
  13080. factoryVariable.globalName = baseName;
  13081. }
  13082. }
  13083. else {
  13084. factoryVariable = node.scope.findGlobal(baseName);
  13085. }
  13086. node.scope.context.includeVariableInModule(factoryVariable, UNKNOWN_PATH, context);
  13087. if (factoryVariable instanceof LocalVariable) {
  13088. factoryVariable.consolidateInitializers();
  13089. factoryVariable.addUsedPlace(node);
  13090. node.scope.context.requestTreeshakingPass();
  13091. }
  13092. return factoryVariable;
  13093. }
  13094. class JSXElementBase extends NodeBase {
  13095. constructor() {
  13096. super(...arguments);
  13097. this.factoryVariable = null;
  13098. this.factory = null;
  13099. }
  13100. initialise() {
  13101. super.initialise();
  13102. const { importSource } = (this.jsxMode = this.getRenderingMode());
  13103. if (importSource) {
  13104. this.scope.context.addImportSource(importSource);
  13105. }
  13106. }
  13107. include(context, includeChildrenRecursively) {
  13108. if (!this.included)
  13109. this.includeNode(context);
  13110. for (const child of this.children) {
  13111. child.include(context, includeChildrenRecursively);
  13112. }
  13113. }
  13114. includeNode(context) {
  13115. this.included = true;
  13116. const { factory, importSource, mode } = this.jsxMode;
  13117. if (factory) {
  13118. this.factory = factory;
  13119. this.factoryVariable = getAndIncludeFactoryVariable(factory, mode === 'preserve', importSource, this, context);
  13120. }
  13121. }
  13122. getRenderingMode() {
  13123. const jsx = this.scope.context.options.jsx;
  13124. const { mode, factory, importSource } = jsx;
  13125. if (mode === 'automatic') {
  13126. return {
  13127. factory: getRenderedJsxChildren(this.children) > 1 ? 'jsxs' : 'jsx',
  13128. importSource: jsx.jsxImportSource,
  13129. mode
  13130. };
  13131. }
  13132. return { factory, importSource, mode };
  13133. }
  13134. renderChildren(code, options, openingEnd) {
  13135. const { children } = this;
  13136. let hasMultipleChildren = false;
  13137. let childrenEnd = openingEnd;
  13138. let firstChild = null;
  13139. for (const child of children) {
  13140. if ((child instanceof JSXExpressionContainer &&
  13141. child.expression instanceof JSXEmptyExpression) ||
  13142. (child instanceof JSXText && !child.shouldRender())) {
  13143. code.remove(childrenEnd, child.end);
  13144. }
  13145. else {
  13146. code.appendLeft(childrenEnd, ', ');
  13147. child.render(code, options);
  13148. if (firstChild) {
  13149. hasMultipleChildren = true;
  13150. }
  13151. else {
  13152. firstChild = child;
  13153. }
  13154. }
  13155. childrenEnd = child.end;
  13156. }
  13157. return { childrenEnd, firstChild, hasMultipleChildren };
  13158. }
  13159. }
  13160. JSXElementBase.prototype.applyDeoptimizations = doNotDeoptimize;
  13161. class JSXElement extends JSXElementBase {
  13162. include(context, includeChildrenRecursively) {
  13163. super.include(context, includeChildrenRecursively);
  13164. this.openingElement.include(context, includeChildrenRecursively);
  13165. this.closingElement?.include(context, includeChildrenRecursively);
  13166. }
  13167. render(code, options) {
  13168. switch (this.jsxMode.mode) {
  13169. case 'classic': {
  13170. this.renderClassicMode(code, options);
  13171. break;
  13172. }
  13173. case 'automatic': {
  13174. this.renderAutomaticMode(code, options);
  13175. break;
  13176. }
  13177. default: {
  13178. super.render(code, options);
  13179. }
  13180. }
  13181. }
  13182. getRenderingMode() {
  13183. const jsx = this.scope.context.options.jsx;
  13184. const { mode, factory, importSource } = jsx;
  13185. if (mode === 'automatic') {
  13186. // In the case there is a key after a spread attribute, we fall back to
  13187. // classic mode, see https://github.com/facebook/react/issues/20031#issuecomment-710346866
  13188. // for reasoning.
  13189. let hasSpread = false;
  13190. for (const attribute of this.openingElement.attributes) {
  13191. if (attribute instanceof JSXSpreadAttribute) {
  13192. hasSpread = true;
  13193. }
  13194. else if (hasSpread && attribute.name.name === 'key') {
  13195. return { factory, importSource, mode: 'classic' };
  13196. }
  13197. }
  13198. }
  13199. return super.getRenderingMode();
  13200. }
  13201. renderClassicMode(code, options) {
  13202. const { snippets: { getPropertyAccess }, useOriginalName } = options;
  13203. const { closingElement, end, factory, factoryVariable, openingElement: { end: openingEnd, selfClosing } } = this;
  13204. const [, ...nestedName] = factory.split('.');
  13205. const { firstAttribute, hasAttributes, hasSpread, inObject, previousEnd } = this.renderAttributes(code, options, [factoryVariable.getName(getPropertyAccess, useOriginalName), ...nestedName].join('.'), false);
  13206. this.wrapAttributes(code, inObject, hasAttributes, hasSpread, firstAttribute, 'null', previousEnd);
  13207. this.renderChildren(code, options, openingEnd);
  13208. if (selfClosing) {
  13209. code.appendLeft(end, ')');
  13210. }
  13211. else {
  13212. closingElement.render(code, options);
  13213. }
  13214. }
  13215. renderAutomaticMode(code, options) {
  13216. const { snippets: { getPropertyAccess }, useOriginalName } = options;
  13217. const { closingElement, end, factoryVariable, openingElement: { end: openingEnd, selfClosing } } = this;
  13218. let { firstAttribute, hasAttributes, hasSpread, inObject, keyAttribute, previousEnd } = this.renderAttributes(code, options, factoryVariable.getName(getPropertyAccess, useOriginalName), true);
  13219. const { firstChild, hasMultipleChildren, childrenEnd } = this.renderChildren(code, options, openingEnd);
  13220. if (firstChild) {
  13221. code.prependRight(firstChild.start, `children: ${hasMultipleChildren ? '[' : ''}`);
  13222. if (!inObject) {
  13223. code.prependRight(firstChild.start, '{ ');
  13224. inObject = true;
  13225. }
  13226. previousEnd = closingElement.start;
  13227. if (hasMultipleChildren) {
  13228. code.appendLeft(previousEnd, ']');
  13229. }
  13230. }
  13231. // This ensures that attributesEnd never corresponds to this.end. This is
  13232. // important because we must never use code.move with this.end as target.
  13233. // Otherwise, this would interfere with parent elements that try to append
  13234. // code to this.end, which would appear BEFORE the moved code.
  13235. const attributesEnd = firstChild ? childrenEnd : previousEnd;
  13236. this.wrapAttributes(code, inObject, hasAttributes || !!firstChild, hasSpread, firstAttribute || firstChild, '{}', attributesEnd);
  13237. if (keyAttribute) {
  13238. const { value } = keyAttribute;
  13239. // This will appear to the left of the moved code...
  13240. code.appendLeft(attributesEnd, ', ');
  13241. if (value) {
  13242. code.move(value.start, value.end, attributesEnd);
  13243. }
  13244. else {
  13245. code.appendLeft(attributesEnd, 'true');
  13246. }
  13247. }
  13248. if (selfClosing) {
  13249. // Moving the key attribute will also move the parenthesis to the right position
  13250. code.appendLeft(keyAttribute?.value?.end || end, ')');
  13251. }
  13252. else {
  13253. closingElement.render(code, options);
  13254. }
  13255. }
  13256. renderAttributes(code, options, factoryName, extractKeyAttribute) {
  13257. const { jsxMode: { mode }, openingElement } = this;
  13258. const { attributes, end: openingEnd, start: openingStart, name: { start: nameStart, end: nameEnd } } = openingElement;
  13259. code.update(openingStart, nameStart, `/*#__PURE__*/${factoryName}(`);
  13260. openingElement.render(code, options, { jsxMode: mode });
  13261. let keyAttribute = null;
  13262. let hasSpread = false;
  13263. let inObject = false;
  13264. let previousEnd = nameEnd;
  13265. let hasAttributes = false;
  13266. let firstAttribute = null;
  13267. for (const attribute of attributes) {
  13268. if (attribute instanceof JSXAttribute) {
  13269. if (extractKeyAttribute && attribute.name.name === 'key') {
  13270. keyAttribute = attribute;
  13271. code.remove(previousEnd, attribute.value?.start || attribute.end);
  13272. continue;
  13273. }
  13274. code.appendLeft(previousEnd, ',');
  13275. if (!inObject) {
  13276. code.prependRight(attribute.start, '{ ');
  13277. inObject = true;
  13278. }
  13279. hasAttributes = true;
  13280. }
  13281. else {
  13282. if (inObject) {
  13283. if (hasAttributes) {
  13284. code.appendLeft(previousEnd, ' ');
  13285. }
  13286. code.appendLeft(previousEnd, '},');
  13287. inObject = false;
  13288. }
  13289. else {
  13290. code.appendLeft(previousEnd, ',');
  13291. }
  13292. hasSpread = true;
  13293. }
  13294. previousEnd = attribute.end;
  13295. firstAttribute ??= attribute;
  13296. }
  13297. code.remove(attributes.at(-1)?.end || previousEnd, openingEnd);
  13298. return { firstAttribute, hasAttributes, hasSpread, inObject, keyAttribute, previousEnd };
  13299. }
  13300. wrapAttributes(code, inObject, hasAttributes, hasSpread, firstAttribute, missingAttributesFallback, attributesEnd) {
  13301. if (inObject) {
  13302. code.appendLeft(attributesEnd, ' }');
  13303. }
  13304. if (hasSpread) {
  13305. if (hasAttributes) {
  13306. const { start } = firstAttribute;
  13307. if (firstAttribute instanceof JSXSpreadAttribute) {
  13308. code.prependRight(start, '{}, ');
  13309. }
  13310. code.prependRight(start, 'Object.assign(');
  13311. code.appendLeft(attributesEnd, ')');
  13312. }
  13313. }
  13314. else if (!hasAttributes) {
  13315. code.appendLeft(attributesEnd, `, ${missingAttributesFallback}`);
  13316. }
  13317. }
  13318. }
  13319. class JSXFragment extends JSXElementBase {
  13320. include(context, includeChildrenRecursively) {
  13321. super.include(context, includeChildrenRecursively);
  13322. this.openingFragment.include(context, includeChildrenRecursively);
  13323. this.closingFragment.include(context, includeChildrenRecursively);
  13324. }
  13325. render(code, options) {
  13326. switch (this.jsxMode.mode) {
  13327. case 'classic': {
  13328. this.renderClassicMode(code, options);
  13329. break;
  13330. }
  13331. case 'automatic': {
  13332. this.renderAutomaticMode(code, options);
  13333. break;
  13334. }
  13335. default: {
  13336. super.render(code, options);
  13337. }
  13338. }
  13339. }
  13340. renderClassicMode(code, options) {
  13341. const { snippets: { getPropertyAccess }, useOriginalName } = options;
  13342. const { closingFragment, factory, factoryVariable, openingFragment, start } = this;
  13343. const [, ...nestedName] = factory.split('.');
  13344. openingFragment.render(code, options);
  13345. code.prependRight(start, `/*#__PURE__*/${[
  13346. factoryVariable.getName(getPropertyAccess, useOriginalName),
  13347. ...nestedName
  13348. ].join('.')}(`);
  13349. code.appendLeft(openingFragment.end, ', null');
  13350. this.renderChildren(code, options, openingFragment.end);
  13351. closingFragment.render(code, options);
  13352. }
  13353. renderAutomaticMode(code, options) {
  13354. const { snippets: { getPropertyAccess }, useOriginalName } = options;
  13355. const { closingFragment, factoryVariable, openingFragment, start } = this;
  13356. openingFragment.render(code, options);
  13357. code.prependRight(start, `/*#__PURE__*/${factoryVariable.getName(getPropertyAccess, useOriginalName)}(`);
  13358. const { firstChild, hasMultipleChildren, childrenEnd } = this.renderChildren(code, options, openingFragment.end);
  13359. if (firstChild) {
  13360. code.prependRight(firstChild.start, `{ children: ${hasMultipleChildren ? '[' : ''}`);
  13361. if (hasMultipleChildren) {
  13362. code.appendLeft(closingFragment.start, ']');
  13363. }
  13364. code.appendLeft(childrenEnd, ' }');
  13365. }
  13366. else {
  13367. code.appendLeft(openingFragment.end, ', {}');
  13368. }
  13369. closingFragment.render(code, options);
  13370. }
  13371. }
  13372. class JSXMemberExpression extends NodeBase {
  13373. includeNode(context) {
  13374. this.included = true;
  13375. if (!this.deoptimized)
  13376. this.applyDeoptimizations();
  13377. this.object.includePath([this.property.name], context);
  13378. }
  13379. includePath(path, context) {
  13380. if (!this.included)
  13381. this.includeNode(context);
  13382. this.object.includePath([this.property.name, ...path], context);
  13383. }
  13384. }
  13385. class JSXNamespacedName extends NodeBase {
  13386. }
  13387. JSXNamespacedName.prototype.includeNode = onlyIncludeSelf;
  13388. class JSXOpeningElement extends NodeBase {
  13389. render(code, options, { jsxMode = this.scope.context.options.jsx.mode } = {}) {
  13390. this.name.render(code, options);
  13391. for (const attribute of this.attributes) {
  13392. attribute.render(code, options, { jsxMode });
  13393. }
  13394. }
  13395. }
  13396. JSXOpeningElement.prototype.includeNode = onlyIncludeSelf;
  13397. class JSXOpeningFragment extends NodeBase {
  13398. constructor() {
  13399. super(...arguments);
  13400. this.fragment = null;
  13401. this.fragmentVariable = null;
  13402. }
  13403. includeNode(context) {
  13404. this.included = true;
  13405. if (!this.deoptimized)
  13406. this.applyDeoptimizations();
  13407. const jsx = this.scope.context.options.jsx;
  13408. if (jsx.mode === 'automatic') {
  13409. this.fragment = 'Fragment';
  13410. this.fragmentVariable = getAndIncludeFactoryVariable('Fragment', false, jsx.jsxImportSource, this, context);
  13411. }
  13412. else {
  13413. const { fragment, importSource, mode } = jsx;
  13414. if (fragment != null) {
  13415. this.fragment = fragment;
  13416. this.fragmentVariable = getAndIncludeFactoryVariable(fragment, mode === 'preserve', importSource, this, context);
  13417. }
  13418. }
  13419. }
  13420. render(code, options) {
  13421. const { mode } = this.scope.context.options.jsx;
  13422. if (mode !== 'preserve') {
  13423. const { snippets: { getPropertyAccess }, useOriginalName } = options;
  13424. const [, ...nestedFragment] = this.fragment.split('.');
  13425. const fragment = [
  13426. this.fragmentVariable.getName(getPropertyAccess, useOriginalName),
  13427. ...nestedFragment
  13428. ].join('.');
  13429. code.update(this.start, this.end, fragment);
  13430. }
  13431. }
  13432. }
  13433. class JSXSpreadChild extends NodeBase {
  13434. render(code, options) {
  13435. super.render(code, options);
  13436. const { mode } = this.scope.context.options.jsx;
  13437. if (mode !== 'preserve') {
  13438. code.overwrite(this.start, this.expression.start, '...', { contentOnly: true });
  13439. code.overwrite(this.expression.end, this.end, '', { contentOnly: true });
  13440. }
  13441. }
  13442. }
  13443. class LabeledStatement extends NodeBase {
  13444. hasEffects(context) {
  13445. const { brokenFlow, includedLabels } = context;
  13446. context.ignore.labels.add(this.label.name);
  13447. context.includedLabels = new Set();
  13448. let bodyHasEffects = false;
  13449. if (this.body.hasEffects(context)) {
  13450. bodyHasEffects = true;
  13451. }
  13452. else {
  13453. context.ignore.labels.delete(this.label.name);
  13454. if (context.includedLabels.has(this.label.name)) {
  13455. context.includedLabels.delete(this.label.name);
  13456. context.brokenFlow = brokenFlow;
  13457. }
  13458. }
  13459. context.includedLabels = new Set([...includedLabels, ...context.includedLabels]);
  13460. return bodyHasEffects;
  13461. }
  13462. include(context, includeChildrenRecursively) {
  13463. if (!this.included)
  13464. this.includeNode(context);
  13465. const { brokenFlow, includedLabels } = context;
  13466. context.includedLabels = new Set();
  13467. this.body.include(context, includeChildrenRecursively);
  13468. if (includeChildrenRecursively || context.includedLabels.has(this.label.name)) {
  13469. this.label.include(context, includeChildrenRecursively);
  13470. context.includedLabels.delete(this.label.name);
  13471. context.brokenFlow = brokenFlow;
  13472. }
  13473. context.includedLabels = new Set([...includedLabels, ...context.includedLabels]);
  13474. }
  13475. includeNode(context) {
  13476. this.included = true;
  13477. this.body.includePath(UNKNOWN_PATH, context);
  13478. }
  13479. render(code, options) {
  13480. if (this.label.included) {
  13481. this.label.render(code, options);
  13482. }
  13483. else {
  13484. code.remove(this.start, findNonWhiteSpace(code.original, findFirstOccurrenceOutsideComment(code.original, ':', this.label.end) + 1));
  13485. }
  13486. this.body.render(code, options);
  13487. }
  13488. }
  13489. LabeledStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  13490. class LogicalExpression extends NodeBase {
  13491. constructor() {
  13492. super(...arguments);
  13493. // We collect deoptimization information if usedBranch !== null
  13494. this.expressionsToBeDeoptimized = [];
  13495. this.usedBranch = null;
  13496. }
  13497. //private isBranchResolutionAnalysed = false;
  13498. get isBranchResolutionAnalysed() {
  13499. return isFlagSet(this.flags, 65536 /* Flag.isBranchResolutionAnalysed */);
  13500. }
  13501. set isBranchResolutionAnalysed(value) {
  13502. this.flags = setFlag(this.flags, 65536 /* Flag.isBranchResolutionAnalysed */, value);
  13503. }
  13504. get hasDeoptimizedCache() {
  13505. return isFlagSet(this.flags, 33554432 /* Flag.hasDeoptimizedCache */);
  13506. }
  13507. set hasDeoptimizedCache(value) {
  13508. this.flags = setFlag(this.flags, 33554432 /* Flag.hasDeoptimizedCache */, value);
  13509. }
  13510. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  13511. this.left.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  13512. this.right.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  13513. }
  13514. deoptimizeCache() {
  13515. if (this.hasDeoptimizedCache)
  13516. return;
  13517. this.hasDeoptimizedCache = true;
  13518. if (this.usedBranch) {
  13519. const unusedBranch = this.usedBranch === this.left ? this.right : this.left;
  13520. this.usedBranch = null;
  13521. unusedBranch.deoptimizePath(UNKNOWN_PATH);
  13522. if (this.included) {
  13523. // As we are not tracking inclusions, we just include everything
  13524. unusedBranch.includePath(UNKNOWN_PATH, createInclusionContext());
  13525. }
  13526. }
  13527. const { scope: { context }, expressionsToBeDeoptimized } = this;
  13528. this.expressionsToBeDeoptimized = EMPTY_ARRAY;
  13529. for (const expression of expressionsToBeDeoptimized) {
  13530. expression.deoptimizeCache();
  13531. }
  13532. // Request another pass because we need to ensure "include" runs again if
  13533. // it is rendered
  13534. context.requestTreeshakingPass();
  13535. }
  13536. deoptimizePath(path) {
  13537. const usedBranch = this.getUsedBranch();
  13538. if (usedBranch) {
  13539. usedBranch.deoptimizePath(path);
  13540. }
  13541. else {
  13542. this.left.deoptimizePath(path);
  13543. this.right.deoptimizePath(path);
  13544. }
  13545. }
  13546. getLiteralValueAtPath(path, recursionTracker, origin) {
  13547. if (origin === this)
  13548. return UnknownValue;
  13549. const usedBranch = this.getUsedBranch();
  13550. if (usedBranch) {
  13551. this.expressionsToBeDeoptimized.push(origin);
  13552. return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
  13553. }
  13554. else if (!this.hasDeoptimizedCache && !path.length) {
  13555. const rightValue = this.right.getLiteralValueAtPath(path, recursionTracker, origin);
  13556. const booleanOrUnknown = tryCastLiteralValueToBoolean(rightValue);
  13557. if (typeof booleanOrUnknown !== 'symbol') {
  13558. if (!booleanOrUnknown && this.operator === '&&') {
  13559. this.expressionsToBeDeoptimized.push(origin);
  13560. return UnknownFalsyValue;
  13561. }
  13562. if (booleanOrUnknown && this.operator === '||') {
  13563. this.expressionsToBeDeoptimized.push(origin);
  13564. return UnknownTruthyValue;
  13565. }
  13566. }
  13567. }
  13568. return UnknownValue;
  13569. }
  13570. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  13571. const usedBranch = this.getUsedBranch();
  13572. if (usedBranch) {
  13573. this.expressionsToBeDeoptimized.push(origin);
  13574. return usedBranch.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  13575. }
  13576. return [
  13577. new MultiExpression([
  13578. this.left.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0],
  13579. this.right.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)[0]
  13580. ]),
  13581. false
  13582. ];
  13583. }
  13584. hasEffects(context) {
  13585. if (this.left.hasEffects(context)) {
  13586. return true;
  13587. }
  13588. if (this.getUsedBranch() !== this.left) {
  13589. return this.right.hasEffects(context);
  13590. }
  13591. return false;
  13592. }
  13593. hasEffectsOnInteractionAtPath(path, interaction, context) {
  13594. const usedBranch = this.getUsedBranch();
  13595. if (usedBranch) {
  13596. return usedBranch.hasEffectsOnInteractionAtPath(path, interaction, context);
  13597. }
  13598. return (this.left.hasEffectsOnInteractionAtPath(path, interaction, context) ||
  13599. this.right.hasEffectsOnInteractionAtPath(path, interaction, context));
  13600. }
  13601. include(context, includeChildrenRecursively) {
  13602. this.included = true;
  13603. const usedBranch = this.getUsedBranch();
  13604. if (includeChildrenRecursively ||
  13605. !usedBranch ||
  13606. (usedBranch === this.right && this.left.shouldBeIncluded(context))) {
  13607. this.left.include(context, includeChildrenRecursively);
  13608. this.right.include(context, includeChildrenRecursively);
  13609. }
  13610. else {
  13611. usedBranch.include(context, includeChildrenRecursively);
  13612. }
  13613. }
  13614. includePath(path, context) {
  13615. this.included = true;
  13616. const usedBranch = this.getUsedBranch();
  13617. if (!usedBranch || (usedBranch === this.right && this.left.shouldBeIncluded(context))) {
  13618. this.left.includePath(path, context);
  13619. this.right.includePath(path, context);
  13620. }
  13621. else {
  13622. usedBranch.includePath(path, context);
  13623. }
  13624. }
  13625. removeAnnotations(code) {
  13626. this.left.removeAnnotations(code);
  13627. }
  13628. render(code, options, { isCalleeOfRenderedParent, preventASI, renderedParentType, renderedSurroundingElement } = BLANK) {
  13629. if (!this.left.included || !this.right.included) {
  13630. const operatorPos = findFirstOccurrenceOutsideComment(code.original, this.operator, this.left.end);
  13631. if (this.right.included) {
  13632. const removePos = findNonWhiteSpace(code.original, operatorPos + 2);
  13633. code.remove(this.start, removePos);
  13634. if (preventASI) {
  13635. removeLineBreaks(code, removePos, this.right.start);
  13636. }
  13637. this.left.removeAnnotations(code);
  13638. }
  13639. else {
  13640. code.remove(findLastWhiteSpaceReverse(code.original, this.left.end, operatorPos), this.end);
  13641. }
  13642. this.getUsedBranch().render(code, options, {
  13643. isCalleeOfRenderedParent,
  13644. preventASI,
  13645. renderedParentType: renderedParentType || this.parent.type,
  13646. renderedSurroundingElement: renderedSurroundingElement || this.parent.type
  13647. });
  13648. }
  13649. else {
  13650. this.left.render(code, options, {
  13651. preventASI,
  13652. renderedSurroundingElement
  13653. });
  13654. this.right.render(code, options);
  13655. }
  13656. }
  13657. getUsedBranch() {
  13658. if (!this.isBranchResolutionAnalysed) {
  13659. this.isBranchResolutionAnalysed = true;
  13660. const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  13661. const booleanOrUnknown = tryCastLiteralValueToBoolean(leftValue);
  13662. if (typeof booleanOrUnknown === 'symbol' ||
  13663. (this.operator === '??' && typeof leftValue === 'symbol')) {
  13664. return null;
  13665. }
  13666. else {
  13667. this.usedBranch =
  13668. (this.operator === '||' && booleanOrUnknown) ||
  13669. (this.operator === '&&' && !booleanOrUnknown) ||
  13670. (this.operator === '??' && leftValue != null)
  13671. ? this.left
  13672. : this.right;
  13673. }
  13674. }
  13675. return this.usedBranch;
  13676. }
  13677. }
  13678. LogicalExpression.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13679. LogicalExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  13680. class NewExpression extends NodeBase {
  13681. hasEffects(context) {
  13682. if (!this.deoptimized)
  13683. this.applyDeoptimizations();
  13684. for (const argument of this.arguments) {
  13685. if (argument.hasEffects(context))
  13686. return true;
  13687. }
  13688. if (this.annotationPure) {
  13689. return false;
  13690. }
  13691. return (this.callee.hasEffects(context) ||
  13692. this.callee.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  13693. }
  13694. hasEffectsOnInteractionAtPath(path, { type }) {
  13695. return path.length > 0 || type !== INTERACTION_ACCESSED;
  13696. }
  13697. include(context, includeChildrenRecursively) {
  13698. if (!this.included)
  13699. this.includeNode(context);
  13700. if (includeChildrenRecursively) {
  13701. super.include(context, true);
  13702. }
  13703. else {
  13704. this.callee.include(context, false);
  13705. this.callee.includeCallArguments(this.interaction, context);
  13706. }
  13707. }
  13708. includeNode(context) {
  13709. this.included = true;
  13710. if (!this.deoptimized)
  13711. this.applyDeoptimizations();
  13712. this.callee.includePath(UNKNOWN_PATH, context);
  13713. }
  13714. initialise() {
  13715. super.initialise();
  13716. this.interaction = {
  13717. args: [null, ...this.arguments],
  13718. type: INTERACTION_CALLED,
  13719. withNew: true
  13720. };
  13721. if (this.annotations &&
  13722. this.scope.context.options.treeshake.annotations) {
  13723. this.annotationPure = this.annotations.some(comment => comment.type === 'pure');
  13724. }
  13725. }
  13726. render(code, options) {
  13727. this.callee.render(code, options);
  13728. renderCallArguments(code, options, this);
  13729. }
  13730. applyDeoptimizations() {
  13731. this.deoptimized = true;
  13732. this.callee.deoptimizeArgumentsOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  13733. this.scope.context.requestTreeshakingPass();
  13734. }
  13735. }
  13736. class ObjectExpression extends NodeBase {
  13737. constructor() {
  13738. super(...arguments);
  13739. this.objectEntity = null;
  13740. this.protoProp = null;
  13741. }
  13742. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  13743. this.getObjectEntity().deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  13744. }
  13745. deoptimizeCache() {
  13746. this.getObjectEntity().deoptimizeAllProperties();
  13747. }
  13748. deoptimizePath(path) {
  13749. this.getObjectEntity().deoptimizePath(path);
  13750. }
  13751. getLiteralValueAtPath(path, recursionTracker, origin) {
  13752. return this.getObjectEntity().getLiteralValueAtPath(path, recursionTracker, origin);
  13753. }
  13754. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  13755. return this.getObjectEntity().getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin);
  13756. }
  13757. hasEffectsOnInteractionAtPath(path, interaction, context) {
  13758. return this.getObjectEntity().hasEffectsOnInteractionAtPath(path, interaction, context);
  13759. }
  13760. include(context, includeChildrenRecursively) {
  13761. if (!this.included)
  13762. this.includeNode(context);
  13763. this.getObjectEntity().include(context, includeChildrenRecursively);
  13764. this.protoProp?.include(context, includeChildrenRecursively);
  13765. }
  13766. includeNode(context) {
  13767. this.included = true;
  13768. this.protoProp?.includePath(UNKNOWN_PATH, context);
  13769. }
  13770. includePath(path, context) {
  13771. if (!this.included)
  13772. this.includeNode(context);
  13773. this.getObjectEntity().includePath(path, context);
  13774. }
  13775. render(code, options, { renderedSurroundingElement } = BLANK) {
  13776. if (renderedSurroundingElement === ExpressionStatement$1 ||
  13777. renderedSurroundingElement === ArrowFunctionExpression$1) {
  13778. code.appendRight(this.start, '(');
  13779. code.prependLeft(this.end, ')');
  13780. }
  13781. if (this.properties.length > 0) {
  13782. const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.properties, code, this.start + 1, this.end - 1);
  13783. let lastSeparatorPos = null;
  13784. for (const { node, separator, start, end } of separatedNodes) {
  13785. if (!node.included) {
  13786. treeshakeNode(node, code, start, end);
  13787. continue;
  13788. }
  13789. lastSeparatorPos = separator;
  13790. node.render(code, options);
  13791. }
  13792. if (lastSeparatorPos) {
  13793. code.remove(lastSeparatorPos, this.end - 1);
  13794. }
  13795. }
  13796. }
  13797. getObjectEntity() {
  13798. if (this.objectEntity !== null) {
  13799. return this.objectEntity;
  13800. }
  13801. let prototype = OBJECT_PROTOTYPE;
  13802. const properties = [];
  13803. for (const property of this.properties) {
  13804. if (property instanceof SpreadElement) {
  13805. properties.push({ key: UnknownKey, kind: 'init', property });
  13806. continue;
  13807. }
  13808. let key;
  13809. if (property.computed) {
  13810. const keyValue = property.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
  13811. if (typeof keyValue === 'symbol') {
  13812. properties.push({
  13813. key: isAnyWellKnown(keyValue) ? keyValue : UnknownKey,
  13814. kind: property.kind,
  13815. property
  13816. });
  13817. continue;
  13818. }
  13819. else {
  13820. key = String(keyValue);
  13821. }
  13822. }
  13823. else {
  13824. key =
  13825. property.key instanceof Identifier
  13826. ? property.key.name
  13827. : String(property.key.value);
  13828. if (key === '__proto__' && property.kind === 'init') {
  13829. this.protoProp = property;
  13830. prototype =
  13831. property.value instanceof Literal && property.value.value === null
  13832. ? null
  13833. : property.value;
  13834. continue;
  13835. }
  13836. }
  13837. properties.push({ key, kind: property.kind, property });
  13838. }
  13839. return (this.objectEntity = new ObjectEntity(properties, prototype));
  13840. }
  13841. }
  13842. ObjectExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  13843. class PanicError extends NodeBase {
  13844. initialise() {
  13845. const { id } = this.scope.context.module;
  13846. // This simulates the current nested error structure. We could also just
  13847. // replace it with a flat error.
  13848. const parseError = getRollupError(logParseError(this.message));
  13849. const moduleParseError = logModuleParseError(parseError, id);
  13850. return error(moduleParseError);
  13851. }
  13852. }
  13853. class ParseError extends NodeBase {
  13854. initialise() {
  13855. const pos = this.start;
  13856. const { id } = this.scope.context.module;
  13857. // This simulates the current nested error structure. We could also just
  13858. // replace it with a flat error.
  13859. const parseError = getRollupError(logParseError(this.message, pos));
  13860. const moduleParseError = logModuleParseError(parseError, id);
  13861. this.scope.context.error(moduleParseError, pos);
  13862. }
  13863. }
  13864. class PrivateIdentifier extends NodeBase {
  13865. }
  13866. PrivateIdentifier.prototype.includeNode = onlyIncludeSelf;
  13867. class Program extends NodeBase {
  13868. constructor() {
  13869. super(...arguments);
  13870. this.hasCachedEffect = null;
  13871. this.hasLoggedEffect = false;
  13872. }
  13873. hasCachedEffects() {
  13874. if (!this.included) {
  13875. return false;
  13876. }
  13877. return this.hasCachedEffect === null
  13878. ? (this.hasCachedEffect = this.hasEffects(createHasEffectsContext()))
  13879. : this.hasCachedEffect;
  13880. }
  13881. hasEffects(context) {
  13882. for (const node of this.body) {
  13883. if (node.hasEffects(context)) {
  13884. if (this.scope.context.options.experimentalLogSideEffects && !this.hasLoggedEffect) {
  13885. this.hasLoggedEffect = true;
  13886. const { code, log, module } = this.scope.context;
  13887. log(LOGLEVEL_INFO, logFirstSideEffect(code, module.id, locate(code, node.start, { offsetLine: 1 })), node.start);
  13888. }
  13889. return (this.hasCachedEffect = true);
  13890. }
  13891. }
  13892. return false;
  13893. }
  13894. include(context, includeChildrenRecursively) {
  13895. this.included = true;
  13896. for (const node of this.body) {
  13897. if (includeChildrenRecursively || node.shouldBeIncluded(context)) {
  13898. node.include(context, includeChildrenRecursively);
  13899. }
  13900. }
  13901. }
  13902. initialise() {
  13903. super.initialise();
  13904. if (this.invalidAnnotations)
  13905. for (const { start, end, type } of this.invalidAnnotations) {
  13906. this.scope.context.magicString.remove(start, end);
  13907. if (type === 'pure' || type === 'noSideEffects') {
  13908. this.scope.context.log(LOGLEVEL_WARN, logInvalidAnnotation(this.scope.context.code.slice(start, end), this.scope.context.module.id, type), start);
  13909. }
  13910. }
  13911. }
  13912. render(code, options) {
  13913. let start = this.start;
  13914. if (code.original.startsWith('#!')) {
  13915. start = Math.min(code.original.indexOf('\n') + 1, this.end);
  13916. code.remove(0, start);
  13917. }
  13918. if (this.body.length > 0) {
  13919. // Keep all consecutive lines that start with a comment
  13920. while (code.original[start] === '/' && /[*/]/.test(code.original[start + 1])) {
  13921. const firstLineBreak = findFirstLineBreakOutsideComment(code.original.slice(start, this.body[0].start));
  13922. if (firstLineBreak[0] === -1) {
  13923. break;
  13924. }
  13925. start += firstLineBreak[1];
  13926. }
  13927. renderStatementList(this.body, code, start, this.end, options);
  13928. }
  13929. else {
  13930. super.render(code, options);
  13931. }
  13932. }
  13933. }
  13934. Program.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  13935. Program.prototype.applyDeoptimizations = doNotDeoptimize;
  13936. class Property extends MethodBase {
  13937. //declare method: boolean;
  13938. get method() {
  13939. return isFlagSet(this.flags, 262144 /* Flag.method */);
  13940. }
  13941. set method(value) {
  13942. this.flags = setFlag(this.flags, 262144 /* Flag.method */, value);
  13943. }
  13944. //declare shorthand: boolean;
  13945. get shorthand() {
  13946. return isFlagSet(this.flags, 524288 /* Flag.shorthand */);
  13947. }
  13948. set shorthand(value) {
  13949. this.flags = setFlag(this.flags, 524288 /* Flag.shorthand */, value);
  13950. }
  13951. declare(kind, destructuredInitPath, init) {
  13952. return this.value.declare(kind, this.getPathInProperty(destructuredInitPath), init);
  13953. }
  13954. deoptimizeAssignment(destructuredInitPath, init) {
  13955. this.value.deoptimizeAssignment?.(this.getPathInProperty(destructuredInitPath), init);
  13956. }
  13957. hasEffects(context) {
  13958. return this.key.hasEffects(context) || this.value.hasEffects(context);
  13959. }
  13960. hasEffectsWhenDestructuring(context, destructuredInitPath, init) {
  13961. return this.value.hasEffectsWhenDestructuring?.(context, this.getPathInProperty(destructuredInitPath), init);
  13962. }
  13963. includeDestructuredIfNecessary(context, destructuredInitPath, init) {
  13964. const path = this.getPathInProperty(destructuredInitPath);
  13965. let included = this.value.includeDestructuredIfNecessary(context, path, init) ||
  13966. this.included;
  13967. if ((included ||= this.key.hasEffects(createHasEffectsContext()))) {
  13968. this.key.include(context, false);
  13969. if (!this.value.included) {
  13970. this.value.includeNode(context);
  13971. // Unfortunately, we need to include the value again now, so that any
  13972. // declared variables are properly included.
  13973. this.value.includeDestructuredIfNecessary(context, path, init);
  13974. }
  13975. }
  13976. if (!this.included && included) {
  13977. this.includeNode(context);
  13978. }
  13979. return this.included;
  13980. }
  13981. include(context, includeChildrenRecursively) {
  13982. this.included = true;
  13983. this.key.include(context, includeChildrenRecursively);
  13984. this.value.include(context, includeChildrenRecursively);
  13985. }
  13986. includePath(path, context) {
  13987. this.included = true;
  13988. this.value.includePath(path, context);
  13989. }
  13990. markDeclarationReached() {
  13991. this.value.markDeclarationReached();
  13992. }
  13993. render(code, options) {
  13994. if (!this.shorthand) {
  13995. this.key.render(code, options);
  13996. }
  13997. this.value.render(code, options, { isShorthandProperty: this.shorthand });
  13998. }
  13999. getPathInProperty(destructuredInitPath) {
  14000. return destructuredInitPath.at(-1) === UnknownKey
  14001. ? destructuredInitPath
  14002. : // For now, we only consider static paths as we do not know how to
  14003. // deoptimize the path in the dynamic case.
  14004. this.computed
  14005. ? [...destructuredInitPath, UnknownKey]
  14006. : this.key instanceof Identifier
  14007. ? [...destructuredInitPath, this.key.name]
  14008. : [...destructuredInitPath, String(this.key.value)];
  14009. }
  14010. }
  14011. Property.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  14012. Property.prototype.applyDeoptimizations = doNotDeoptimize;
  14013. class PropertyDefinition extends NodeBase {
  14014. get computed() {
  14015. return isFlagSet(this.flags, 1024 /* Flag.computed */);
  14016. }
  14017. set computed(value) {
  14018. this.flags = setFlag(this.flags, 1024 /* Flag.computed */, value);
  14019. }
  14020. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  14021. this.value?.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  14022. }
  14023. deoptimizePath(path) {
  14024. this.value?.deoptimizePath(path);
  14025. }
  14026. getLiteralValueAtPath(path, recursionTracker, origin) {
  14027. return this.value
  14028. ? this.value.getLiteralValueAtPath(path, recursionTracker, origin)
  14029. : UnknownValue;
  14030. }
  14031. getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin) {
  14032. return this.value
  14033. ? this.value.getReturnExpressionWhenCalledAtPath(path, interaction, recursionTracker, origin)
  14034. : UNKNOWN_RETURN_EXPRESSION;
  14035. }
  14036. hasEffects(context) {
  14037. return (this.key.hasEffects(context) ||
  14038. (this.static && !!this.value?.hasEffects(context)) ||
  14039. checkEffectForNodes(this.decorators, context));
  14040. }
  14041. hasEffectsOnInteractionAtPath(path, interaction, context) {
  14042. return !this.value || this.value.hasEffectsOnInteractionAtPath(path, interaction, context);
  14043. }
  14044. includeNode(context) {
  14045. this.included = true;
  14046. this.value?.includePath(UNKNOWN_PATH, context);
  14047. for (const decorator of this.decorators) {
  14048. decorator.includePath(UNKNOWN_PATH, context);
  14049. }
  14050. }
  14051. }
  14052. PropertyDefinition.prototype.applyDeoptimizations = doNotDeoptimize;
  14053. class ReturnStatement extends NodeBase {
  14054. hasEffects(context) {
  14055. if (!context.ignore.returnYield || this.argument?.hasEffects(context))
  14056. return true;
  14057. context.brokenFlow = true;
  14058. return false;
  14059. }
  14060. include(context, includeChildrenRecursively) {
  14061. if (!this.included)
  14062. this.includeNode(context);
  14063. this.argument?.include(context, includeChildrenRecursively);
  14064. context.brokenFlow = true;
  14065. }
  14066. includeNode(context) {
  14067. this.included = true;
  14068. this.argument?.includePath(UNKNOWN_PATH, context);
  14069. }
  14070. initialise() {
  14071. super.initialise();
  14072. this.scope.addReturnExpression(this.argument || UNKNOWN_EXPRESSION);
  14073. }
  14074. render(code, options) {
  14075. if (this.argument) {
  14076. this.argument.render(code, options, { preventASI: true });
  14077. if (this.argument.start === this.start + 6 /* 'return'.length */) {
  14078. code.prependLeft(this.start + 6, ' ');
  14079. }
  14080. }
  14081. }
  14082. }
  14083. ReturnStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  14084. class SequenceExpression extends NodeBase {
  14085. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  14086. this.expressions[this.expressions.length - 1].deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  14087. }
  14088. deoptimizePath(path) {
  14089. this.expressions[this.expressions.length - 1].deoptimizePath(path);
  14090. }
  14091. getLiteralValueAtPath(path, recursionTracker, origin) {
  14092. return this.expressions[this.expressions.length - 1].getLiteralValueAtPath(path, recursionTracker, origin);
  14093. }
  14094. hasEffects(context) {
  14095. for (const expression of this.expressions) {
  14096. if (expression.hasEffects(context))
  14097. return true;
  14098. }
  14099. return false;
  14100. }
  14101. hasEffectsOnInteractionAtPath(path, interaction, context) {
  14102. return this.expressions[this.expressions.length - 1].hasEffectsOnInteractionAtPath(path, interaction, context);
  14103. }
  14104. include(context, includeChildrenRecursively) {
  14105. this.included = true;
  14106. const lastExpression = this.expressions[this.expressions.length - 1];
  14107. for (const expression of this.expressions) {
  14108. if (includeChildrenRecursively ||
  14109. (expression === lastExpression && !(this.parent instanceof ExpressionStatement)) ||
  14110. expression.shouldBeIncluded(context)) {
  14111. expression.include(context, includeChildrenRecursively);
  14112. }
  14113. }
  14114. }
  14115. includePath(path, context) {
  14116. this.included = true;
  14117. this.expressions[this.expressions.length - 1].includePath(path, context);
  14118. }
  14119. removeAnnotations(code) {
  14120. this.expressions[0].removeAnnotations(code);
  14121. }
  14122. render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
  14123. let includedNodes = 0;
  14124. let lastSeparatorPos = null;
  14125. const lastNode = this.expressions[this.expressions.length - 1];
  14126. for (const { node, separator, start, end } of getCommaSeparatedNodesWithBoundaries(this.expressions, code, this.start, this.end)) {
  14127. if (!node.included) {
  14128. treeshakeNode(node, code, start, end);
  14129. continue;
  14130. }
  14131. includedNodes++;
  14132. lastSeparatorPos = separator;
  14133. if (includedNodes === 1 && preventASI) {
  14134. removeLineBreaks(code, start, node.start);
  14135. }
  14136. if (includedNodes === 1) {
  14137. const parentType = renderedParentType || this.parent.type;
  14138. node.render(code, options, {
  14139. isCalleeOfRenderedParent: isCalleeOfRenderedParent && node === lastNode,
  14140. renderedParentType: parentType,
  14141. renderedSurroundingElement: parentType
  14142. });
  14143. }
  14144. else {
  14145. node.render(code, options);
  14146. }
  14147. }
  14148. if (lastSeparatorPos) {
  14149. code.remove(lastSeparatorPos, this.end);
  14150. }
  14151. }
  14152. }
  14153. SequenceExpression.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  14154. SequenceExpression.prototype.applyDeoptimizations = doNotDeoptimize;
  14155. class Super extends NodeBase {
  14156. bind() {
  14157. this.variable = this.scope.findVariable('this');
  14158. }
  14159. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  14160. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  14161. }
  14162. deoptimizePath(path) {
  14163. this.variable.deoptimizePath(path);
  14164. }
  14165. include(context) {
  14166. if (!this.included)
  14167. this.includeNode(context);
  14168. }
  14169. includeNode(context) {
  14170. this.included = true;
  14171. if (!this.deoptimized)
  14172. this.applyDeoptimizations();
  14173. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  14174. }
  14175. }
  14176. class SwitchCase extends NodeBase {
  14177. hasEffects(context) {
  14178. if (this.test?.hasEffects(context))
  14179. return true;
  14180. for (const node of this.consequent) {
  14181. if (context.brokenFlow)
  14182. break;
  14183. if (node.hasEffects(context))
  14184. return true;
  14185. }
  14186. return false;
  14187. }
  14188. include(context, includeChildrenRecursively) {
  14189. this.included = true;
  14190. this.test?.include(context, includeChildrenRecursively);
  14191. for (const node of this.consequent) {
  14192. if (includeChildrenRecursively || node.shouldBeIncluded(context))
  14193. node.include(context, includeChildrenRecursively);
  14194. }
  14195. }
  14196. render(code, options, nodeRenderOptions) {
  14197. if (this.test) {
  14198. this.test.render(code, options);
  14199. if (this.test.start === this.start + 4) {
  14200. code.prependLeft(this.test.start, ' ');
  14201. }
  14202. }
  14203. if (this.consequent.length > 0) {
  14204. const testEnd = this.test
  14205. ? this.test.end
  14206. : findFirstOccurrenceOutsideComment(code.original, 'default', this.start) + 7;
  14207. const consequentStart = findFirstOccurrenceOutsideComment(code.original, ':', testEnd) + 1;
  14208. renderStatementList(this.consequent, code, consequentStart, nodeRenderOptions.end, options);
  14209. }
  14210. }
  14211. }
  14212. SwitchCase.prototype.needsBoundaries = true;
  14213. SwitchCase.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  14214. SwitchCase.prototype.applyDeoptimizations = doNotDeoptimize;
  14215. class SwitchStatement extends NodeBase {
  14216. createScope(parentScope) {
  14217. this.parentScope = parentScope;
  14218. this.scope = new BlockScope(parentScope);
  14219. }
  14220. hasEffects(context) {
  14221. if (this.discriminant.hasEffects(context))
  14222. return true;
  14223. const { brokenFlow, hasBreak, ignore } = context;
  14224. const { breaks } = ignore;
  14225. ignore.breaks = true;
  14226. context.hasBreak = false;
  14227. let onlyHasBrokenFlow = true;
  14228. for (const switchCase of this.cases) {
  14229. if (switchCase.hasEffects(context))
  14230. return true;
  14231. onlyHasBrokenFlow &&= context.brokenFlow && !context.hasBreak;
  14232. context.hasBreak = false;
  14233. context.brokenFlow = brokenFlow;
  14234. }
  14235. if (this.defaultCase !== null) {
  14236. context.brokenFlow = onlyHasBrokenFlow;
  14237. }
  14238. ignore.breaks = breaks;
  14239. context.hasBreak = hasBreak;
  14240. return false;
  14241. }
  14242. include(context, includeChildrenRecursively) {
  14243. this.included = true;
  14244. this.discriminant.include(context, includeChildrenRecursively);
  14245. const { brokenFlow, hasBreak } = context;
  14246. context.hasBreak = false;
  14247. let onlyHasBrokenFlow = true;
  14248. let isCaseIncluded = includeChildrenRecursively ||
  14249. (this.defaultCase !== null && this.defaultCase < this.cases.length - 1);
  14250. for (let caseIndex = this.cases.length - 1; caseIndex >= 0; caseIndex--) {
  14251. const switchCase = this.cases[caseIndex];
  14252. if (switchCase.included) {
  14253. isCaseIncluded = true;
  14254. }
  14255. if (!isCaseIncluded) {
  14256. const hasEffectsContext = createHasEffectsContext();
  14257. hasEffectsContext.ignore.breaks = true;
  14258. isCaseIncluded = switchCase.hasEffects(hasEffectsContext);
  14259. }
  14260. if (isCaseIncluded) {
  14261. switchCase.include(context, includeChildrenRecursively);
  14262. onlyHasBrokenFlow &&= context.brokenFlow && !context.hasBreak;
  14263. context.hasBreak = false;
  14264. context.brokenFlow = brokenFlow;
  14265. }
  14266. else {
  14267. onlyHasBrokenFlow = brokenFlow;
  14268. }
  14269. }
  14270. if (isCaseIncluded && this.defaultCase !== null) {
  14271. context.brokenFlow = onlyHasBrokenFlow;
  14272. }
  14273. context.hasBreak = hasBreak;
  14274. }
  14275. initialise() {
  14276. super.initialise();
  14277. for (let caseIndex = 0; caseIndex < this.cases.length; caseIndex++) {
  14278. if (this.cases[caseIndex].test === null) {
  14279. this.defaultCase = caseIndex;
  14280. return;
  14281. }
  14282. }
  14283. this.defaultCase = null;
  14284. }
  14285. parseNode(esTreeNode) {
  14286. this.discriminant = new (this.scope.context.getNodeConstructor(esTreeNode.discriminant.type))(this, this.parentScope).parseNode(esTreeNode.discriminant);
  14287. return super.parseNode(esTreeNode);
  14288. }
  14289. render(code, options) {
  14290. this.discriminant.render(code, options);
  14291. if (this.cases.length > 0) {
  14292. renderStatementList(this.cases, code, this.cases[0].start, this.end - 1, options);
  14293. }
  14294. }
  14295. }
  14296. SwitchStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  14297. SwitchStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  14298. class TaggedTemplateExpression extends CallExpressionBase {
  14299. get hasCheckedForWarnings() {
  14300. return isFlagSet(this.flags, 134217728 /* Flag.checkedForWarnings */);
  14301. }
  14302. set hasCheckedForWarnings(value) {
  14303. this.flags = setFlag(this.flags, 134217728 /* Flag.checkedForWarnings */, value);
  14304. }
  14305. hasEffects(context) {
  14306. if (!this.deoptimized)
  14307. this.applyDeoptimizations();
  14308. for (const argument of this.quasi.expressions) {
  14309. if (argument.hasEffects(context))
  14310. return true;
  14311. }
  14312. return (this.tag.hasEffects(context) ||
  14313. this.tag.hasEffectsOnInteractionAtPath(EMPTY_PATH, this.interaction, context));
  14314. }
  14315. include(context, includeChildrenRecursively) {
  14316. if (!this.included)
  14317. this.includeNode(context);
  14318. if (includeChildrenRecursively) {
  14319. super.include(context, true);
  14320. }
  14321. else {
  14322. this.quasi.include(context, false);
  14323. this.tag.include(context, false);
  14324. this.tag.includeCallArguments(this.interaction, context);
  14325. }
  14326. }
  14327. initialise() {
  14328. super.initialise();
  14329. this.args = [UNKNOWN_EXPRESSION, ...this.quasi.expressions];
  14330. this.interaction = {
  14331. args: [
  14332. this.tag instanceof MemberExpression && !this.tag.variable ? this.tag.object : null,
  14333. ...this.args
  14334. ],
  14335. type: INTERACTION_CALLED,
  14336. withNew: false
  14337. };
  14338. }
  14339. render(code, options) {
  14340. this.tag.render(code, options, { isCalleeOfRenderedParent: true });
  14341. this.quasi.render(code, options);
  14342. if (!this.hasCheckedForWarnings && this.tag.type === Identifier$1) {
  14343. this.hasCheckedForWarnings = true;
  14344. const name = this.tag.name;
  14345. const variable = this.scope.findVariable(name);
  14346. if (variable.isNamespace) {
  14347. this.scope.context.log(LOGLEVEL_WARN, logCannotCallNamespace(name), this.start);
  14348. }
  14349. }
  14350. }
  14351. applyDeoptimizations() {
  14352. this.deoptimized = true;
  14353. this.tag.deoptimizeArgumentsOnInteractionAtPath(this.interaction, EMPTY_PATH, SHARED_RECURSION_TRACKER);
  14354. this.scope.context.requestTreeshakingPass();
  14355. }
  14356. getReturnExpression(recursionTracker = SHARED_RECURSION_TRACKER) {
  14357. if (this.returnExpression === null) {
  14358. this.returnExpression = UNKNOWN_RETURN_EXPRESSION;
  14359. return (this.returnExpression = this.tag.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, this.interaction, recursionTracker, this));
  14360. }
  14361. return this.returnExpression;
  14362. }
  14363. }
  14364. TaggedTemplateExpression.prototype.includeNode = onlyIncludeSelf;
  14365. class TemplateElement extends NodeBase {
  14366. get tail() {
  14367. return isFlagSet(this.flags, 1048576 /* Flag.tail */);
  14368. }
  14369. set tail(value) {
  14370. this.flags = setFlag(this.flags, 1048576 /* Flag.tail */, value);
  14371. }
  14372. // Do not try to bind value
  14373. bind() { }
  14374. hasEffects() {
  14375. return false;
  14376. }
  14377. parseNode(esTreeNode) {
  14378. this.value = esTreeNode.value;
  14379. return super.parseNode(esTreeNode);
  14380. }
  14381. render() { }
  14382. }
  14383. TemplateElement.prototype.includeNode = onlyIncludeSelf;
  14384. class TemplateLiteral extends NodeBase {
  14385. deoptimizeArgumentsOnInteractionAtPath() { }
  14386. getLiteralValueAtPath(path) {
  14387. if (path.length > 0 || this.quasis.length !== 1) {
  14388. return UnknownValue;
  14389. }
  14390. return this.quasis[0].value.cooked;
  14391. }
  14392. getReturnExpressionWhenCalledAtPath(path) {
  14393. if (path.length !== 1) {
  14394. return UNKNOWN_RETURN_EXPRESSION;
  14395. }
  14396. return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
  14397. }
  14398. hasEffectsOnInteractionAtPath(path, interaction, context) {
  14399. if (interaction.type === INTERACTION_ACCESSED) {
  14400. return path.length > 1;
  14401. }
  14402. if (interaction.type === INTERACTION_CALLED && path.length === 1) {
  14403. return hasMemberEffectWhenCalled(literalStringMembers, path[0], interaction, context);
  14404. }
  14405. return true;
  14406. }
  14407. includeNode(context) {
  14408. this.included = true;
  14409. if (!this.deoptimized)
  14410. this.applyDeoptimizations();
  14411. for (const node of this.expressions) {
  14412. node.includePath(UNKNOWN_PATH, context);
  14413. }
  14414. }
  14415. render(code, options) {
  14416. code.indentExclusionRanges.push([this.start, this.end]);
  14417. super.render(code, options);
  14418. }
  14419. }
  14420. class ModuleScope extends ChildScope {
  14421. constructor(parent, context, importDescriptions) {
  14422. super(parent, context);
  14423. this.importDescriptions = importDescriptions;
  14424. this.variables.set('this', new LocalVariable('this', null, UNDEFINED_EXPRESSION, EMPTY_PATH, context, 'other'));
  14425. }
  14426. addDeclaration(identifier, context, init, destructuredInitPath, kind) {
  14427. if (this.importDescriptions.has(identifier.name)) {
  14428. context.error(logRedeclarationError(identifier.name), identifier.start);
  14429. }
  14430. return super.addDeclaration(identifier, context, init, destructuredInitPath, kind);
  14431. }
  14432. addExportDefaultDeclaration(exportDefaultDeclaration, context) {
  14433. const variable = new ExportDefaultVariable(exportDefaultDeclaration, context);
  14434. this.variables.set('default', variable);
  14435. return variable;
  14436. }
  14437. addNamespaceMemberAccess() { }
  14438. deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
  14439. // all module level variables are already deconflicted when deconflicting the chunk
  14440. for (const scope of this.children)
  14441. scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  14442. }
  14443. findLexicalBoundary() {
  14444. return this;
  14445. }
  14446. findVariable(name) {
  14447. const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
  14448. if (knownVariable) {
  14449. return knownVariable;
  14450. }
  14451. const variable = this.context.traceVariable(name) || this.parent.findVariable(name);
  14452. if (variable instanceof GlobalVariable) {
  14453. this.accessedOutsideVariables.set(name, variable);
  14454. }
  14455. return variable;
  14456. }
  14457. }
  14458. class ThisExpression extends NodeBase {
  14459. bind() {
  14460. this.variable = this.scope.findVariable('this');
  14461. }
  14462. deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker) {
  14463. this.variable.deoptimizeArgumentsOnInteractionAtPath(interaction, path, recursionTracker);
  14464. }
  14465. deoptimizePath(path) {
  14466. this.variable.deoptimizePath(path);
  14467. }
  14468. hasEffectsOnInteractionAtPath(path, interaction, context) {
  14469. if (path.length === 0) {
  14470. return interaction.type !== INTERACTION_ACCESSED;
  14471. }
  14472. return this.variable.hasEffectsOnInteractionAtPath(path, interaction, context);
  14473. }
  14474. include(context) {
  14475. if (!this.included)
  14476. this.includeNode(context);
  14477. }
  14478. includeNode(context) {
  14479. this.included = true;
  14480. if (!this.deoptimized)
  14481. this.applyDeoptimizations();
  14482. this.scope.context.includeVariableInModule(this.variable, EMPTY_PATH, context);
  14483. }
  14484. includePath(path, context) {
  14485. if (!this.included) {
  14486. this.included = true;
  14487. this.scope.context.includeVariableInModule(this.variable, path, context);
  14488. }
  14489. else if (path.length > 0) {
  14490. this.variable.includePath(path, context);
  14491. }
  14492. const functionScope = findFunctionScope(this.scope, this.variable);
  14493. if (functionScope &&
  14494. functionScope.functionNode.parent instanceof Property &&
  14495. functionScope.functionNode.parent.parent instanceof ObjectExpression) {
  14496. functionScope.functionNode.parent.parent.includePath(path, context);
  14497. }
  14498. }
  14499. initialise() {
  14500. super.initialise();
  14501. this.alias =
  14502. this.scope.findLexicalBoundary() instanceof ModuleScope
  14503. ? this.scope.context.moduleContext
  14504. : null;
  14505. if (this.alias === 'undefined') {
  14506. this.scope.context.log(LOGLEVEL_WARN, logThisIsUndefined(), this.start);
  14507. }
  14508. }
  14509. render(code) {
  14510. if (this.alias !== null) {
  14511. code.overwrite(this.start, this.end, this.alias, {
  14512. contentOnly: false,
  14513. storeName: true
  14514. });
  14515. }
  14516. }
  14517. }
  14518. function findFunctionScope(scope, thisVariable) {
  14519. while (!(scope instanceof FunctionScope && scope.thisVariable === thisVariable)) {
  14520. if (!(scope instanceof ChildScope)) {
  14521. return null;
  14522. }
  14523. scope = scope.parent;
  14524. }
  14525. return scope;
  14526. }
  14527. class ThrowStatement extends NodeBase {
  14528. hasEffects() {
  14529. return true;
  14530. }
  14531. include(context, includeChildrenRecursively) {
  14532. if (!this.included)
  14533. this.includeNode(context);
  14534. this.argument.include(context, includeChildrenRecursively);
  14535. context.brokenFlow = true;
  14536. }
  14537. includeNode(context) {
  14538. if (!this.included) {
  14539. this.included = true;
  14540. this.argument.includePath(UNKNOWN_PATH, context);
  14541. }
  14542. }
  14543. render(code, options) {
  14544. this.argument.render(code, options, { preventASI: true });
  14545. if (this.argument.start === this.start + 5 /* 'throw'.length */) {
  14546. code.prependLeft(this.start + 5, ' ');
  14547. }
  14548. }
  14549. }
  14550. class TryStatement extends NodeBase {
  14551. constructor() {
  14552. super(...arguments);
  14553. this.directlyIncluded = false;
  14554. this.includedLabelsAfterBlock = null;
  14555. }
  14556. hasEffects(context) {
  14557. return ((this.scope.context.options.treeshake.tryCatchDeoptimization
  14558. ? this.block.body.length > 0
  14559. : this.block.hasEffects(context)) || !!this.finalizer?.hasEffects(context));
  14560. }
  14561. include(context, includeChildrenRecursively) {
  14562. const tryCatchDeoptimization = this.scope.context.options.treeshake?.tryCatchDeoptimization;
  14563. const { brokenFlow, includedLabels } = context;
  14564. if (!this.directlyIncluded || !tryCatchDeoptimization) {
  14565. this.included = true;
  14566. this.directlyIncluded = true;
  14567. this.block.include(context, tryCatchDeoptimization ? INCLUDE_PARAMETERS : includeChildrenRecursively);
  14568. if (includedLabels.size > 0) {
  14569. this.includedLabelsAfterBlock = [...includedLabels];
  14570. }
  14571. context.brokenFlow = brokenFlow;
  14572. }
  14573. else if (this.includedLabelsAfterBlock) {
  14574. for (const label of this.includedLabelsAfterBlock) {
  14575. includedLabels.add(label);
  14576. }
  14577. }
  14578. if (this.handler !== null) {
  14579. this.handler.include(context, includeChildrenRecursively);
  14580. context.brokenFlow = brokenFlow;
  14581. }
  14582. this.finalizer?.include(context, includeChildrenRecursively);
  14583. }
  14584. }
  14585. TryStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  14586. TryStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  14587. const unaryOperators = {
  14588. '!': value => !value,
  14589. '+': value => +value,
  14590. '-': value => -value,
  14591. delete: () => UnknownValue,
  14592. typeof: value => typeof value,
  14593. void: () => undefined,
  14594. '~': value => ~value
  14595. };
  14596. const UNASSIGNED = Symbol('Unassigned');
  14597. class UnaryExpression extends NodeBase {
  14598. constructor() {
  14599. super(...arguments);
  14600. this.renderedLiteralValue = UNASSIGNED;
  14601. }
  14602. get prefix() {
  14603. return isFlagSet(this.flags, 2097152 /* Flag.prefix */);
  14604. }
  14605. set prefix(value) {
  14606. this.flags = setFlag(this.flags, 2097152 /* Flag.prefix */, value);
  14607. }
  14608. deoptimizeCache() {
  14609. this.renderedLiteralValue = UnknownValue;
  14610. }
  14611. getLiteralValueAtPath(path, recursionTracker, origin) {
  14612. if (path.length > 0)
  14613. return UnknownValue;
  14614. const argumentValue = this.argument.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
  14615. if (typeof argumentValue === 'symbol') {
  14616. if (this.operator === 'void')
  14617. return undefined;
  14618. if (this.operator === '!') {
  14619. if (argumentValue === UnknownFalsyValue)
  14620. return true;
  14621. if (argumentValue === UnknownTruthyValue)
  14622. return false;
  14623. }
  14624. return UnknownValue;
  14625. }
  14626. return unaryOperators[this.operator](argumentValue);
  14627. }
  14628. hasEffects(context) {
  14629. if (!this.deoptimized)
  14630. this.applyDeoptimizations();
  14631. if (this.operator === 'typeof' && this.argument instanceof Identifier)
  14632. return false;
  14633. return (this.argument.hasEffects(context) ||
  14634. (this.operator === 'delete' &&
  14635. this.argument.hasEffectsOnInteractionAtPath(EMPTY_PATH, NODE_INTERACTION_UNKNOWN_ASSIGNMENT, context)));
  14636. }
  14637. hasEffectsOnInteractionAtPath(path, { type }) {
  14638. return type !== INTERACTION_ACCESSED || path.length > (this.operator === 'void' ? 0 : 1);
  14639. }
  14640. applyDeoptimizations() {
  14641. this.deoptimized = true;
  14642. if (this.operator === 'delete') {
  14643. this.argument.deoptimizePath(EMPTY_PATH);
  14644. this.scope.context.requestTreeshakingPass();
  14645. }
  14646. }
  14647. getRenderedLiteralValue(includeChildrenRecursively) {
  14648. if (this.renderedLiteralValue !== UNASSIGNED)
  14649. return this.renderedLiteralValue;
  14650. return (this.renderedLiteralValue = includeChildrenRecursively
  14651. ? UnknownValue
  14652. : getRenderedLiteralValue(this.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this)));
  14653. }
  14654. include(context, includeChildrenRecursively, _options) {
  14655. if (!this.deoptimized)
  14656. this.applyDeoptimizations();
  14657. this.included = true;
  14658. // Check if the argument is an identifier that should be preserved as a reference for readability
  14659. const shouldPreserveArgument = this.argument instanceof Identifier && this.argument.variable?.included;
  14660. if (typeof this.getRenderedLiteralValue(includeChildrenRecursively) === 'symbol' ||
  14661. this.argument.shouldBeIncluded(context) ||
  14662. shouldPreserveArgument) {
  14663. this.argument.include(context, includeChildrenRecursively);
  14664. this.renderedLiteralValue = UnknownValue;
  14665. }
  14666. }
  14667. render(code, options) {
  14668. if (typeof this.renderedLiteralValue === 'symbol') {
  14669. super.render(code, options);
  14670. }
  14671. else {
  14672. let value = this.renderedLiteralValue;
  14673. if (!CHARACTERS_THAT_DO_NOT_REQUIRE_SPACE.test(code.original[this.start - 1])) {
  14674. value = ` ${value}`;
  14675. }
  14676. code.overwrite(this.start, this.end, value);
  14677. }
  14678. }
  14679. }
  14680. const CHARACTERS_THAT_DO_NOT_REQUIRE_SPACE = /[\s([=%&*+-/<>^|,?:;]/;
  14681. UnaryExpression.prototype.includeNode = onlyIncludeSelf;
  14682. class UpdateExpression extends NodeBase {
  14683. hasEffects(context) {
  14684. if (!this.deoptimized)
  14685. this.applyDeoptimizations();
  14686. return this.argument.hasEffectsAsAssignmentTarget(context, true);
  14687. }
  14688. hasEffectsOnInteractionAtPath(path, { type }) {
  14689. return path.length > 1 || type !== INTERACTION_ACCESSED;
  14690. }
  14691. include(context, includeChildrenRecursively) {
  14692. if (!this.included)
  14693. this.includeNode(context);
  14694. this.argument.includeAsAssignmentTarget(context, includeChildrenRecursively, true);
  14695. }
  14696. initialise() {
  14697. super.initialise();
  14698. this.argument.setAssignedValue(UNKNOWN_EXPRESSION);
  14699. }
  14700. render(code, options) {
  14701. const { exportNamesByVariable, format, snippets: { _ } } = options;
  14702. this.argument.render(code, options);
  14703. if (format === 'system') {
  14704. const variable = this.argument.variable;
  14705. const exportNames = exportNamesByVariable.get(variable);
  14706. if (exportNames) {
  14707. if (this.prefix) {
  14708. if (exportNames.length === 1) {
  14709. renderSystemExportExpression(variable, this.start, this.end, code, options);
  14710. }
  14711. else {
  14712. renderSystemExportSequenceAfterExpression(variable, this.start, this.end, this.parent.type !== ExpressionStatement$1, code, options);
  14713. }
  14714. }
  14715. else {
  14716. const operator = this.operator[0];
  14717. renderSystemExportSequenceBeforeExpression(variable, this.start, this.end, this.parent.type !== ExpressionStatement$1, code, options, `${_}${operator}${_}1`);
  14718. }
  14719. }
  14720. }
  14721. }
  14722. applyDeoptimizations() {
  14723. this.deoptimized = true;
  14724. this.argument.deoptimizePath(EMPTY_PATH);
  14725. if (this.argument instanceof Identifier) {
  14726. const variable = this.scope.findVariable(this.argument.name);
  14727. variable.markReassigned();
  14728. }
  14729. this.scope.context.requestTreeshakingPass();
  14730. }
  14731. }
  14732. UpdateExpression.prototype.includeNode = onlyIncludeSelf;
  14733. function isReassignedExportsMember(variable, exportNamesByVariable) {
  14734. return (variable.renderBaseName !== null && exportNamesByVariable.has(variable) && variable.isReassigned);
  14735. }
  14736. class VariableDeclaration extends NodeBase {
  14737. deoptimizePath() {
  14738. for (const declarator of this.declarations) {
  14739. declarator.deoptimizePath(EMPTY_PATH);
  14740. }
  14741. }
  14742. hasEffectsOnInteractionAtPath() {
  14743. return false;
  14744. }
  14745. include(context, includeChildrenRecursively, { asSingleStatement } = BLANK) {
  14746. this.included = true;
  14747. for (const declarator of this.declarations) {
  14748. if (includeChildrenRecursively || declarator.shouldBeIncluded(context)) {
  14749. declarator.include(context, includeChildrenRecursively);
  14750. }
  14751. const { id, init } = declarator;
  14752. if (asSingleStatement) {
  14753. id.include(context, includeChildrenRecursively);
  14754. }
  14755. if (init &&
  14756. id.included &&
  14757. !init.included &&
  14758. (id instanceof ObjectPattern || id instanceof ArrayPattern)) {
  14759. init.include(context, includeChildrenRecursively);
  14760. }
  14761. }
  14762. }
  14763. initialise() {
  14764. super.initialise();
  14765. for (const declarator of this.declarations) {
  14766. declarator.declareDeclarator(this.kind);
  14767. }
  14768. }
  14769. removeAnnotations(code) {
  14770. this.declarations[0].removeAnnotations(code);
  14771. }
  14772. render(code, options, nodeRenderOptions = BLANK) {
  14773. if (this.areAllDeclarationsIncludedAndNotExported(options.exportNamesByVariable)) {
  14774. for (const declarator of this.declarations) {
  14775. declarator.render(code, options);
  14776. }
  14777. if (!nodeRenderOptions.isNoStatement &&
  14778. code.original.charCodeAt(this.end - 1) !== 59 /*";"*/) {
  14779. code.appendLeft(this.end, ';');
  14780. }
  14781. }
  14782. else {
  14783. this.renderReplacedDeclarations(code, options);
  14784. }
  14785. }
  14786. renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, systemPatternExports, options) {
  14787. if (code.original.charCodeAt(this.end - 1) === 59 /*";"*/) {
  14788. code.remove(this.end - 1, this.end);
  14789. }
  14790. separatorString += ';';
  14791. if (lastSeparatorPos === null) {
  14792. code.appendLeft(renderedContentEnd, separatorString);
  14793. }
  14794. else {
  14795. if (code.original.charCodeAt(actualContentEnd - 1) === 10 /*"\n"*/ &&
  14796. (code.original.charCodeAt(this.end) === 10 /*"\n"*/ ||
  14797. code.original.charCodeAt(this.end) === 13) /*"\r"*/) {
  14798. actualContentEnd--;
  14799. if (code.original.charCodeAt(actualContentEnd) === 13 /*"\r"*/) {
  14800. actualContentEnd--;
  14801. }
  14802. }
  14803. if (actualContentEnd === lastSeparatorPos + 1) {
  14804. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString);
  14805. }
  14806. else {
  14807. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  14808. code.remove(actualContentEnd, renderedContentEnd);
  14809. }
  14810. }
  14811. if (systemPatternExports.length > 0) {
  14812. code.appendLeft(renderedContentEnd, ` ${getSystemExportStatement(systemPatternExports, options)};`);
  14813. }
  14814. }
  14815. renderReplacedDeclarations(code, options) {
  14816. const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.declarations, code, this.start + this.kind.length, this.end - (code.original.charCodeAt(this.end - 1) === 59 /*";"*/ ? 1 : 0));
  14817. let actualContentEnd, renderedContentEnd;
  14818. renderedContentEnd = findNonWhiteSpace(code.original, this.start + this.kind.length);
  14819. let lastSeparatorPos = renderedContentEnd - 1;
  14820. code.remove(this.start, lastSeparatorPos);
  14821. let isInDeclaration = false;
  14822. let hasRenderedContent = false;
  14823. let separatorString = '', leadingString, nextSeparatorString;
  14824. const aggregatedSystemExports = [];
  14825. const singleSystemExport = gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports);
  14826. for (const { node, start, separator, contentEnd, end } of separatedNodes) {
  14827. if (!node.included) {
  14828. treeshakeNode(node, code, start, end);
  14829. continue;
  14830. }
  14831. node.render(code, options);
  14832. leadingString = '';
  14833. nextSeparatorString = '';
  14834. if (!node.id.included ||
  14835. (node.id instanceof Identifier &&
  14836. isReassignedExportsMember(node.id.variable, options.exportNamesByVariable))) {
  14837. if (hasRenderedContent) {
  14838. separatorString += ';';
  14839. }
  14840. isInDeclaration = false;
  14841. }
  14842. else {
  14843. if (singleSystemExport && singleSystemExport === node.id.variable) {
  14844. const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', node.id.end);
  14845. renderSystemExportExpression(singleSystemExport, findNonWhiteSpace(code.original, operatorPos + 1), separator === null ? contentEnd : separator, code, options);
  14846. }
  14847. if (isInDeclaration) {
  14848. separatorString += ',';
  14849. }
  14850. else {
  14851. if (hasRenderedContent) {
  14852. separatorString += ';';
  14853. }
  14854. leadingString += `${this.kind} `;
  14855. isInDeclaration = true;
  14856. }
  14857. }
  14858. if (renderedContentEnd === lastSeparatorPos + 1) {
  14859. code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString + leadingString);
  14860. }
  14861. else {
  14862. code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
  14863. code.appendLeft(renderedContentEnd, leadingString);
  14864. }
  14865. actualContentEnd = contentEnd;
  14866. renderedContentEnd = end;
  14867. hasRenderedContent = true;
  14868. lastSeparatorPos = separator;
  14869. separatorString = nextSeparatorString;
  14870. }
  14871. this.renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, aggregatedSystemExports, options);
  14872. }
  14873. areAllDeclarationsIncludedAndNotExported(exportNamesByVariable) {
  14874. if (this.kind === 'await using' || this.kind === 'using') {
  14875. return true;
  14876. }
  14877. for (const declarator of this.declarations) {
  14878. if (!declarator.id.included)
  14879. return false;
  14880. if (declarator.id.type === Identifier$1) {
  14881. if (exportNamesByVariable.has(declarator.id.variable))
  14882. return false;
  14883. }
  14884. else {
  14885. const exportedVariables = [];
  14886. declarator.id.addExportedVariables(exportedVariables, exportNamesByVariable);
  14887. if (exportedVariables.length > 0)
  14888. return false;
  14889. }
  14890. }
  14891. return true;
  14892. }
  14893. }
  14894. function gatherSystemExportsAndGetSingleExport(separatedNodes, options, aggregatedSystemExports) {
  14895. let singleSystemExport = null;
  14896. if (options.format === 'system') {
  14897. for (const { node } of separatedNodes) {
  14898. if (node.id instanceof Identifier &&
  14899. node.init &&
  14900. aggregatedSystemExports.length === 0 &&
  14901. options.exportNamesByVariable.get(node.id.variable)?.length === 1) {
  14902. singleSystemExport = node.id.variable;
  14903. aggregatedSystemExports.push(singleSystemExport);
  14904. }
  14905. else {
  14906. node.id.addExportedVariables(aggregatedSystemExports, options.exportNamesByVariable);
  14907. }
  14908. }
  14909. if (aggregatedSystemExports.length > 1) {
  14910. singleSystemExport = null;
  14911. }
  14912. else if (singleSystemExport) {
  14913. aggregatedSystemExports.length = 0;
  14914. }
  14915. }
  14916. return singleSystemExport;
  14917. }
  14918. VariableDeclaration.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  14919. VariableDeclaration.prototype.applyDeoptimizations = doNotDeoptimize;
  14920. class VariableDeclarator extends NodeBase {
  14921. declareDeclarator(kind) {
  14922. this.isUsingDeclaration = kind === 'using';
  14923. this.isAsyncUsingDeclaration = kind === 'await using';
  14924. this.id.declare(kind, EMPTY_PATH, this.init || UNDEFINED_EXPRESSION);
  14925. }
  14926. deoptimizePath(path) {
  14927. this.id.deoptimizePath(path);
  14928. }
  14929. hasEffects(context) {
  14930. const initEffect = this.init?.hasEffects(context);
  14931. this.id.markDeclarationReached();
  14932. return (initEffect ||
  14933. this.isUsingDeclaration ||
  14934. this.isAsyncUsingDeclaration ||
  14935. this.id.hasEffects(context) ||
  14936. (this.scope.context.options.treeshake
  14937. .propertyReadSideEffects &&
  14938. this.id.hasEffectsWhenDestructuring(context, EMPTY_PATH, this.init || UNDEFINED_EXPRESSION)));
  14939. }
  14940. include(context, includeChildrenRecursively) {
  14941. const { id, init } = this;
  14942. if (!this.included)
  14943. this.includeNode(context);
  14944. init?.include(context, includeChildrenRecursively);
  14945. id.markDeclarationReached();
  14946. if (includeChildrenRecursively) {
  14947. id.include(context, includeChildrenRecursively);
  14948. }
  14949. else {
  14950. id.includeDestructuredIfNecessary(context, EMPTY_PATH, init || UNDEFINED_EXPRESSION);
  14951. }
  14952. }
  14953. removeAnnotations(code) {
  14954. this.init?.removeAnnotations(code);
  14955. }
  14956. render(code, options) {
  14957. const { exportNamesByVariable, snippets: { _, getPropertyAccess } } = options;
  14958. const { end, id, init, start } = this;
  14959. const renderId = id.included || this.isUsingDeclaration || this.isAsyncUsingDeclaration;
  14960. if (renderId) {
  14961. id.render(code, options);
  14962. }
  14963. else {
  14964. const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', id.end);
  14965. code.remove(start, findNonWhiteSpace(code.original, operatorPos + 1));
  14966. }
  14967. if (init) {
  14968. if (id instanceof Identifier && init instanceof ClassExpression && !init.id) {
  14969. const renderedVariable = id.variable.getName(getPropertyAccess);
  14970. if (renderedVariable !== id.name) {
  14971. code.appendLeft(init.start + 5, ` ${id.name}`);
  14972. }
  14973. }
  14974. init.render(code, options, renderId ? BLANK : { renderedSurroundingElement: ExpressionStatement$1 });
  14975. }
  14976. else if (id instanceof Identifier &&
  14977. isReassignedExportsMember(id.variable, exportNamesByVariable)) {
  14978. code.appendLeft(end, `${_}=${_}void 0`);
  14979. }
  14980. }
  14981. includeNode(context) {
  14982. this.included = true;
  14983. const { id, init } = this;
  14984. if (init) {
  14985. if (this.isUsingDeclaration) {
  14986. init.includePath(SYMBOL_DISPOSE_PATH, context);
  14987. }
  14988. else if (this.isAsyncUsingDeclaration) {
  14989. init.includePath(SYMBOL_ASYNC_DISPOSE_PATH, context);
  14990. }
  14991. if (id instanceof Identifier && init instanceof ClassExpression && !init.id) {
  14992. const { name, variable } = id;
  14993. for (const accessedVariable of init.scope.accessedOutsideVariables.values()) {
  14994. if (accessedVariable !== variable) {
  14995. accessedVariable.forbidName(name);
  14996. }
  14997. }
  14998. }
  14999. }
  15000. }
  15001. }
  15002. VariableDeclarator.prototype.applyDeoptimizations = doNotDeoptimize;
  15003. const SYMBOL_DISPOSE_PATH = [SymbolDispose];
  15004. const SYMBOL_ASYNC_DISPOSE_PATH = [SymbolAsyncDispose];
  15005. class WhileStatement extends NodeBase {
  15006. hasEffects(context) {
  15007. if (this.test.hasEffects(context))
  15008. return true;
  15009. return hasLoopBodyEffects(context, this.body);
  15010. }
  15011. include(context, includeChildrenRecursively) {
  15012. this.included = true;
  15013. this.test.include(context, includeChildrenRecursively);
  15014. includeLoopBody(context, this.body, includeChildrenRecursively);
  15015. }
  15016. }
  15017. WhileStatement.prototype.includeNode = onlyIncludeSelfNoDeoptimize;
  15018. WhileStatement.prototype.applyDeoptimizations = doNotDeoptimize;
  15019. class YieldExpression extends NodeBase {
  15020. applyDeoptimizations() {
  15021. this.deoptimized = true;
  15022. this.argument?.deoptimizePath(UNKNOWN_PATH);
  15023. }
  15024. hasEffects(context) {
  15025. if (!this.deoptimized)
  15026. this.applyDeoptimizations();
  15027. return !(context.ignore.returnYield && !this.argument?.hasEffects(context));
  15028. }
  15029. includeNode(context) {
  15030. this.included = true;
  15031. if (!this.deoptimized)
  15032. this.applyDeoptimizations();
  15033. this.argument?.includePath(UNKNOWN_PATH, context);
  15034. }
  15035. render(code, options) {
  15036. if (this.argument) {
  15037. this.argument.render(code, options, { preventASI: true });
  15038. if (this.argument.start === this.start + 5 /* 'yield'.length */) {
  15039. code.prependLeft(this.start + 5, ' ');
  15040. }
  15041. }
  15042. }
  15043. }
  15044. // This file is generated by scripts/generate-buffer-parsers.js.
  15045. // Do not edit this file directly.
  15046. function convertProgram(buffer, parent, parentScope) {
  15047. return convertNode(parent, parentScope, 0, getAstBuffer(buffer));
  15048. }
  15049. const nodeTypeStrings = [
  15050. 'PanicError',
  15051. 'ParseError',
  15052. 'ArrayExpression',
  15053. 'ArrayPattern',
  15054. 'ArrowFunctionExpression',
  15055. 'AssignmentExpression',
  15056. 'AssignmentPattern',
  15057. 'AwaitExpression',
  15058. 'BinaryExpression',
  15059. 'BlockStatement',
  15060. 'BreakStatement',
  15061. 'CallExpression',
  15062. 'CatchClause',
  15063. 'ChainExpression',
  15064. 'ClassBody',
  15065. 'ClassDeclaration',
  15066. 'ClassExpression',
  15067. 'ConditionalExpression',
  15068. 'ContinueStatement',
  15069. 'DebuggerStatement',
  15070. 'Decorator',
  15071. 'ExpressionStatement',
  15072. 'DoWhileStatement',
  15073. 'EmptyStatement',
  15074. 'ExportAllDeclaration',
  15075. 'ExportDefaultDeclaration',
  15076. 'ExportNamedDeclaration',
  15077. 'ExportSpecifier',
  15078. 'ExpressionStatement',
  15079. 'ForInStatement',
  15080. 'ForOfStatement',
  15081. 'ForStatement',
  15082. 'FunctionDeclaration',
  15083. 'FunctionExpression',
  15084. 'Identifier',
  15085. 'IfStatement',
  15086. 'ImportAttribute',
  15087. 'ImportDeclaration',
  15088. 'ImportDefaultSpecifier',
  15089. 'ImportExpression',
  15090. 'ImportNamespaceSpecifier',
  15091. 'ImportSpecifier',
  15092. 'JSXAttribute',
  15093. 'JSXClosingElement',
  15094. 'JSXClosingFragment',
  15095. 'JSXElement',
  15096. 'JSXEmptyExpression',
  15097. 'JSXExpressionContainer',
  15098. 'JSXFragment',
  15099. 'JSXIdentifier',
  15100. 'JSXMemberExpression',
  15101. 'JSXNamespacedName',
  15102. 'JSXOpeningElement',
  15103. 'JSXOpeningFragment',
  15104. 'JSXSpreadAttribute',
  15105. 'JSXSpreadChild',
  15106. 'JSXText',
  15107. 'LabeledStatement',
  15108. 'Literal',
  15109. 'Literal',
  15110. 'Literal',
  15111. 'Literal',
  15112. 'Literal',
  15113. 'Literal',
  15114. 'LogicalExpression',
  15115. 'MemberExpression',
  15116. 'MetaProperty',
  15117. 'MethodDefinition',
  15118. 'NewExpression',
  15119. 'ObjectExpression',
  15120. 'ObjectPattern',
  15121. 'PrivateIdentifier',
  15122. 'Program',
  15123. 'Property',
  15124. 'PropertyDefinition',
  15125. 'RestElement',
  15126. 'ReturnStatement',
  15127. 'SequenceExpression',
  15128. 'SpreadElement',
  15129. 'StaticBlock',
  15130. 'Super',
  15131. 'SwitchCase',
  15132. 'SwitchStatement',
  15133. 'TaggedTemplateExpression',
  15134. 'TemplateElement',
  15135. 'TemplateLiteral',
  15136. 'ThisExpression',
  15137. 'ThrowStatement',
  15138. 'TryStatement',
  15139. 'UnaryExpression',
  15140. 'UpdateExpression',
  15141. 'VariableDeclaration',
  15142. 'VariableDeclarator',
  15143. 'WhileStatement',
  15144. 'YieldExpression'
  15145. ];
  15146. const nodeConstructors$1 = [
  15147. PanicError,
  15148. ParseError,
  15149. ArrayExpression,
  15150. ArrayPattern,
  15151. ArrowFunctionExpression,
  15152. AssignmentExpression,
  15153. AssignmentPattern,
  15154. AwaitExpression,
  15155. BinaryExpression,
  15156. BlockStatement,
  15157. BreakStatement,
  15158. CallExpression,
  15159. CatchClause,
  15160. ChainExpression,
  15161. ClassBody,
  15162. ClassDeclaration,
  15163. ClassExpression,
  15164. ConditionalExpression,
  15165. ContinueStatement,
  15166. DebuggerStatement,
  15167. Decorator,
  15168. ExpressionStatement,
  15169. DoWhileStatement,
  15170. EmptyStatement,
  15171. ExportAllDeclaration,
  15172. ExportDefaultDeclaration,
  15173. ExportNamedDeclaration,
  15174. ExportSpecifier,
  15175. ExpressionStatement,
  15176. ForInStatement,
  15177. ForOfStatement,
  15178. ForStatement,
  15179. FunctionDeclaration,
  15180. FunctionExpression,
  15181. Identifier,
  15182. IfStatement,
  15183. ImportAttribute,
  15184. ImportDeclaration,
  15185. ImportDefaultSpecifier,
  15186. ImportExpression,
  15187. ImportNamespaceSpecifier,
  15188. ImportSpecifier,
  15189. JSXAttribute,
  15190. JSXClosingElement,
  15191. JSXClosingFragment,
  15192. JSXElement,
  15193. JSXEmptyExpression,
  15194. JSXExpressionContainer,
  15195. JSXFragment,
  15196. JSXIdentifier,
  15197. JSXMemberExpression,
  15198. JSXNamespacedName,
  15199. JSXOpeningElement,
  15200. JSXOpeningFragment,
  15201. JSXSpreadAttribute,
  15202. JSXSpreadChild,
  15203. JSXText,
  15204. LabeledStatement,
  15205. Literal,
  15206. Literal,
  15207. Literal,
  15208. Literal,
  15209. Literal,
  15210. Literal,
  15211. LogicalExpression,
  15212. MemberExpression,
  15213. MetaProperty,
  15214. MethodDefinition,
  15215. NewExpression,
  15216. ObjectExpression,
  15217. ObjectPattern,
  15218. PrivateIdentifier,
  15219. Program,
  15220. Property,
  15221. PropertyDefinition,
  15222. RestElement,
  15223. ReturnStatement,
  15224. SequenceExpression,
  15225. SpreadElement,
  15226. StaticBlock,
  15227. Super,
  15228. SwitchCase,
  15229. SwitchStatement,
  15230. TaggedTemplateExpression,
  15231. TemplateElement,
  15232. TemplateLiteral,
  15233. ThisExpression,
  15234. ThrowStatement,
  15235. TryStatement,
  15236. UnaryExpression,
  15237. UpdateExpression,
  15238. VariableDeclaration,
  15239. VariableDeclarator,
  15240. WhileStatement,
  15241. YieldExpression
  15242. ];
  15243. const bufferParsers = [
  15244. function panicError(node, position, buffer) {
  15245. node.message = buffer.convertString(buffer[position]);
  15246. },
  15247. function parseError(node, position, buffer) {
  15248. node.message = buffer.convertString(buffer[position]);
  15249. },
  15250. function arrayExpression(node, position, buffer) {
  15251. const { scope } = node;
  15252. node.elements = convertNodeList(node, scope, buffer[position], buffer);
  15253. },
  15254. function arrayPattern(node, position, buffer) {
  15255. const { scope } = node;
  15256. node.elements = convertNodeList(node, scope, buffer[position], buffer);
  15257. },
  15258. function arrowFunctionExpression(node, position, buffer) {
  15259. const { scope } = node;
  15260. const flags = buffer[position];
  15261. node.async = (flags & 1) === 1;
  15262. node.expression = (flags & 2) === 2;
  15263. node.generator = (flags & 4) === 4;
  15264. const annotations = (node.annotations = convertAnnotations(buffer[position + 1], buffer));
  15265. node.annotationNoSideEffects = annotations.some(comment => comment.type === 'noSideEffects');
  15266. const parameters = (node.params = convertNodeList(node, scope, buffer[position + 2], buffer));
  15267. scope.addParameterVariables(parameters.map(parameter => parameter.declare('parameter', EMPTY_PATH, UNKNOWN_EXPRESSION)), parameters[parameters.length - 1] instanceof RestElement);
  15268. node.body = convertNode(node, scope.bodyScope, buffer[position + 3], buffer);
  15269. },
  15270. function assignmentExpression(node, position, buffer) {
  15271. const { scope } = node;
  15272. node.operator = FIXED_STRINGS[buffer[position]];
  15273. node.left = convertNode(node, scope, buffer[position + 1], buffer);
  15274. node.right = convertNode(node, scope, buffer[position + 2], buffer);
  15275. },
  15276. function assignmentPattern(node, position, buffer) {
  15277. const { scope } = node;
  15278. node.left = convertNode(node, scope, buffer[position], buffer);
  15279. node.right = convertNode(node, scope, buffer[position + 1], buffer);
  15280. },
  15281. function awaitExpression(node, position, buffer) {
  15282. const { scope } = node;
  15283. node.argument = convertNode(node, scope, buffer[position], buffer);
  15284. },
  15285. function binaryExpression(node, position, buffer) {
  15286. const { scope } = node;
  15287. node.operator = FIXED_STRINGS[buffer[position]];
  15288. node.left = convertNode(node, scope, buffer[position + 1], buffer);
  15289. node.right = convertNode(node, scope, buffer[position + 2], buffer);
  15290. },
  15291. function blockStatement(node, position, buffer) {
  15292. const { scope } = node;
  15293. node.body = convertNodeList(node, scope, buffer[position], buffer);
  15294. },
  15295. function breakStatement(node, position, buffer) {
  15296. const { scope } = node;
  15297. const labelPosition = buffer[position];
  15298. node.label = labelPosition === 0 ? null : convertNode(node, scope, labelPosition, buffer);
  15299. },
  15300. function callExpression(node, position, buffer) {
  15301. const { scope } = node;
  15302. const flags = buffer[position];
  15303. node.optional = (flags & 1) === 1;
  15304. node.annotations = convertAnnotations(buffer[position + 1], buffer);
  15305. node.callee = convertNode(node, scope, buffer[position + 2], buffer);
  15306. node.arguments = convertNodeList(node, scope, buffer[position + 3], buffer);
  15307. },
  15308. function catchClause(node, position, buffer) {
  15309. const { scope } = node;
  15310. const parameterPosition = buffer[position];
  15311. const parameter = (node.param =
  15312. parameterPosition === 0 ? null : convertNode(node, scope, parameterPosition, buffer));
  15313. parameter?.declare('parameter', EMPTY_PATH, UNKNOWN_EXPRESSION);
  15314. node.body = convertNode(node, scope.bodyScope, buffer[position + 1], buffer);
  15315. },
  15316. function chainExpression(node, position, buffer) {
  15317. const { scope } = node;
  15318. node.expression = convertNode(node, scope, buffer[position], buffer);
  15319. },
  15320. function classBody(node, position, buffer) {
  15321. const { scope } = node;
  15322. const bodyPosition = buffer[position];
  15323. if (bodyPosition) {
  15324. const length = buffer[bodyPosition];
  15325. const body = (node.body = new Array(length));
  15326. for (let index = 0; index < length; index++) {
  15327. const nodePosition = buffer[bodyPosition + 1 + index];
  15328. body[index] = convertNode(node, buffer[nodePosition] !== 79 &&
  15329. (buffer[nodePosition + 3] & /* the static flag is always first */ 1) === 0
  15330. ? scope.instanceScope
  15331. : scope, nodePosition, buffer);
  15332. }
  15333. }
  15334. else {
  15335. node.body = [];
  15336. }
  15337. },
  15338. function classDeclaration(node, position, buffer) {
  15339. const { scope } = node;
  15340. node.decorators = convertNodeList(node, scope, buffer[position], buffer);
  15341. const idPosition = buffer[position + 1];
  15342. node.id =
  15343. idPosition === 0 ? null : convertNode(node, scope.parent, idPosition, buffer);
  15344. const superClassPosition = buffer[position + 2];
  15345. node.superClass =
  15346. superClassPosition === 0 ? null : convertNode(node, scope, superClassPosition, buffer);
  15347. node.body = convertNode(node, scope, buffer[position + 3], buffer);
  15348. },
  15349. function classExpression(node, position, buffer) {
  15350. const { scope } = node;
  15351. node.decorators = convertNodeList(node, scope, buffer[position], buffer);
  15352. const idPosition = buffer[position + 1];
  15353. node.id = idPosition === 0 ? null : convertNode(node, scope, idPosition, buffer);
  15354. const superClassPosition = buffer[position + 2];
  15355. node.superClass =
  15356. superClassPosition === 0 ? null : convertNode(node, scope, superClassPosition, buffer);
  15357. node.body = convertNode(node, scope, buffer[position + 3], buffer);
  15358. },
  15359. function conditionalExpression(node, position, buffer) {
  15360. const { scope } = node;
  15361. node.test = convertNode(node, scope, buffer[position], buffer);
  15362. node.consequent = convertNode(node, scope, buffer[position + 1], buffer);
  15363. node.alternate = convertNode(node, scope, buffer[position + 2], buffer);
  15364. },
  15365. function continueStatement(node, position, buffer) {
  15366. const { scope } = node;
  15367. const labelPosition = buffer[position];
  15368. node.label = labelPosition === 0 ? null : convertNode(node, scope, labelPosition, buffer);
  15369. },
  15370. function debuggerStatement() { },
  15371. function decorator(node, position, buffer) {
  15372. const { scope } = node;
  15373. node.expression = convertNode(node, scope, buffer[position], buffer);
  15374. },
  15375. function directive(node, position, buffer) {
  15376. const { scope } = node;
  15377. node.directive = buffer.convertString(buffer[position]);
  15378. node.expression = convertNode(node, scope, buffer[position + 1], buffer);
  15379. },
  15380. function doWhileStatement(node, position, buffer) {
  15381. const { scope } = node;
  15382. node.body = convertNode(node, scope, buffer[position], buffer);
  15383. node.test = convertNode(node, scope, buffer[position + 1], buffer);
  15384. },
  15385. function emptyStatement() { },
  15386. function exportAllDeclaration(node, position, buffer) {
  15387. const { scope } = node;
  15388. const exportedPosition = buffer[position];
  15389. node.exported =
  15390. exportedPosition === 0 ? null : convertNode(node, scope, exportedPosition, buffer);
  15391. node.source = convertNode(node, scope, buffer[position + 1], buffer);
  15392. node.attributes = convertNodeList(node, scope, buffer[position + 2], buffer);
  15393. },
  15394. function exportDefaultDeclaration(node, position, buffer) {
  15395. const { scope } = node;
  15396. node.declaration = convertNode(node, scope, buffer[position], buffer);
  15397. },
  15398. function exportNamedDeclaration(node, position, buffer) {
  15399. const { scope } = node;
  15400. node.specifiers = convertNodeList(node, scope, buffer[position], buffer);
  15401. const sourcePosition = buffer[position + 1];
  15402. node.source = sourcePosition === 0 ? null : convertNode(node, scope, sourcePosition, buffer);
  15403. node.attributes = convertNodeList(node, scope, buffer[position + 2], buffer);
  15404. const declarationPosition = buffer[position + 3];
  15405. node.declaration =
  15406. declarationPosition === 0 ? null : convertNode(node, scope, declarationPosition, buffer);
  15407. },
  15408. function exportSpecifier(node, position, buffer) {
  15409. const { scope } = node;
  15410. node.local = convertNode(node, scope, buffer[position], buffer);
  15411. const exportedPosition = buffer[position + 1];
  15412. node.exported =
  15413. exportedPosition === 0 ? node.local : convertNode(node, scope, exportedPosition, buffer);
  15414. },
  15415. function expressionStatement(node, position, buffer) {
  15416. const { scope } = node;
  15417. node.expression = convertNode(node, scope, buffer[position], buffer);
  15418. },
  15419. function forInStatement(node, position, buffer) {
  15420. const { scope } = node;
  15421. node.left = convertNode(node, scope, buffer[position], buffer);
  15422. node.right = convertNode(node, scope, buffer[position + 1], buffer);
  15423. node.body = convertNode(node, scope, buffer[position + 2], buffer);
  15424. },
  15425. function forOfStatement(node, position, buffer) {
  15426. const { scope } = node;
  15427. const flags = buffer[position];
  15428. node.await = (flags & 1) === 1;
  15429. node.left = convertNode(node, scope, buffer[position + 1], buffer);
  15430. node.right = convertNode(node, scope, buffer[position + 2], buffer);
  15431. node.body = convertNode(node, scope, buffer[position + 3], buffer);
  15432. },
  15433. function forStatement(node, position, buffer) {
  15434. const { scope } = node;
  15435. const initPosition = buffer[position];
  15436. node.init = initPosition === 0 ? null : convertNode(node, scope, initPosition, buffer);
  15437. const testPosition = buffer[position + 1];
  15438. node.test = testPosition === 0 ? null : convertNode(node, scope, testPosition, buffer);
  15439. const updatePosition = buffer[position + 2];
  15440. node.update = updatePosition === 0 ? null : convertNode(node, scope, updatePosition, buffer);
  15441. node.body = convertNode(node, scope, buffer[position + 3], buffer);
  15442. },
  15443. function functionDeclaration(node, position, buffer) {
  15444. const { scope } = node;
  15445. const flags = buffer[position];
  15446. node.async = (flags & 1) === 1;
  15447. node.generator = (flags & 2) === 2;
  15448. const annotations = (node.annotations = convertAnnotations(buffer[position + 1], buffer));
  15449. node.annotationNoSideEffects = annotations.some(comment => comment.type === 'noSideEffects');
  15450. const idPosition = buffer[position + 2];
  15451. node.id =
  15452. idPosition === 0 ? null : convertNode(node, scope.parent, idPosition, buffer);
  15453. const parameters = (node.params = convertNodeList(node, scope, buffer[position + 3], buffer));
  15454. scope.addParameterVariables(parameters.map(parameter => parameter.declare('parameter', EMPTY_PATH, UNKNOWN_EXPRESSION)), parameters[parameters.length - 1] instanceof RestElement);
  15455. node.body = convertNode(node, scope.bodyScope, buffer[position + 4], buffer);
  15456. },
  15457. function functionExpression(node, position, buffer) {
  15458. const { scope } = node;
  15459. const flags = buffer[position];
  15460. node.async = (flags & 1) === 1;
  15461. node.generator = (flags & 2) === 2;
  15462. const annotations = (node.annotations = convertAnnotations(buffer[position + 1], buffer));
  15463. node.annotationNoSideEffects = annotations.some(comment => comment.type === 'noSideEffects');
  15464. const idPosition = buffer[position + 2];
  15465. node.id = idPosition === 0 ? null : convertNode(node, node.idScope, idPosition, buffer);
  15466. const parameters = (node.params = convertNodeList(node, scope, buffer[position + 3], buffer));
  15467. scope.addParameterVariables(parameters.map(parameter => parameter.declare('parameter', EMPTY_PATH, UNKNOWN_EXPRESSION)), parameters[parameters.length - 1] instanceof RestElement);
  15468. node.body = convertNode(node, scope.bodyScope, buffer[position + 4], buffer);
  15469. },
  15470. function identifier(node, position, buffer) {
  15471. node.name = buffer.convertString(buffer[position]);
  15472. },
  15473. function ifStatement(node, position, buffer) {
  15474. const { scope } = node;
  15475. node.test = convertNode(node, scope, buffer[position], buffer);
  15476. node.consequent = convertNode(node, (node.consequentScope = new TrackingScope(scope)), buffer[position + 1], buffer);
  15477. const alternatePosition = buffer[position + 2];
  15478. node.alternate =
  15479. alternatePosition === 0
  15480. ? null
  15481. : convertNode(node, (node.alternateScope = new TrackingScope(scope)), alternatePosition, buffer);
  15482. },
  15483. function importAttribute(node, position, buffer) {
  15484. const { scope } = node;
  15485. node.key = convertNode(node, scope, buffer[position], buffer);
  15486. node.value = convertNode(node, scope, buffer[position + 1], buffer);
  15487. },
  15488. function importDeclaration(node, position, buffer) {
  15489. const { scope } = node;
  15490. node.specifiers = convertNodeList(node, scope, buffer[position], buffer);
  15491. node.source = convertNode(node, scope, buffer[position + 1], buffer);
  15492. node.attributes = convertNodeList(node, scope, buffer[position + 2], buffer);
  15493. const phaseIndex = buffer[position + 3];
  15494. node.phase = phaseIndex === 0 ? undefined : FIXED_STRINGS[phaseIndex];
  15495. },
  15496. function importDefaultSpecifier(node, position, buffer) {
  15497. const { scope } = node;
  15498. node.local = convertNode(node, scope, buffer[position], buffer);
  15499. },
  15500. function importExpression(node, position, buffer) {
  15501. const { scope } = node;
  15502. node.source = convertNode(node, scope, buffer[position], buffer);
  15503. node.sourceAstNode = convertNode$1(buffer[position], buffer);
  15504. const optionsPosition = buffer[position + 1];
  15505. node.options = optionsPosition === 0 ? null : convertNode(node, scope, optionsPosition, buffer);
  15506. const phaseIndex = buffer[position + 2];
  15507. node.phase = phaseIndex === 0 ? undefined : FIXED_STRINGS[phaseIndex];
  15508. },
  15509. function importNamespaceSpecifier(node, position, buffer) {
  15510. const { scope } = node;
  15511. node.local = convertNode(node, scope, buffer[position], buffer);
  15512. },
  15513. function importSpecifier(node, position, buffer) {
  15514. const { scope } = node;
  15515. const importedPosition = buffer[position];
  15516. node.local = convertNode(node, scope, buffer[position + 1], buffer);
  15517. node.imported =
  15518. importedPosition === 0 ? node.local : convertNode(node, scope, importedPosition, buffer);
  15519. },
  15520. function jsxAttribute(node, position, buffer) {
  15521. const { scope } = node;
  15522. node.name = convertNode(node, scope, buffer[position], buffer);
  15523. const valuePosition = buffer[position + 1];
  15524. node.value = valuePosition === 0 ? null : convertNode(node, scope, valuePosition, buffer);
  15525. },
  15526. function jsxClosingElement(node, position, buffer) {
  15527. const { scope } = node;
  15528. node.name = convertNode(node, scope, buffer[position], buffer);
  15529. },
  15530. function jsxClosingFragment() { },
  15531. function jsxElement(node, position, buffer) {
  15532. const { scope } = node;
  15533. node.openingElement = convertNode(node, scope, buffer[position], buffer);
  15534. node.children = convertNodeList(node, scope, buffer[position + 1], buffer);
  15535. const closingElementPosition = buffer[position + 2];
  15536. node.closingElement =
  15537. closingElementPosition === 0
  15538. ? null
  15539. : convertNode(node, scope, closingElementPosition, buffer);
  15540. },
  15541. function jsxEmptyExpression() { },
  15542. function jsxExpressionContainer(node, position, buffer) {
  15543. const { scope } = node;
  15544. node.expression = convertNode(node, scope, buffer[position], buffer);
  15545. },
  15546. function jsxFragment(node, position, buffer) {
  15547. const { scope } = node;
  15548. node.openingFragment = convertNode(node, scope, buffer[position], buffer);
  15549. node.children = convertNodeList(node, scope, buffer[position + 1], buffer);
  15550. node.closingFragment = convertNode(node, scope, buffer[position + 2], buffer);
  15551. },
  15552. function jsxIdentifier(node, position, buffer) {
  15553. node.name = buffer.convertString(buffer[position]);
  15554. },
  15555. function jsxMemberExpression(node, position, buffer) {
  15556. const { scope } = node;
  15557. node.object = convertNode(node, scope, buffer[position], buffer);
  15558. node.property = convertNode(node, scope, buffer[position + 1], buffer);
  15559. },
  15560. function jsxNamespacedName(node, position, buffer) {
  15561. const { scope } = node;
  15562. node.namespace = convertNode(node, scope, buffer[position], buffer);
  15563. node.name = convertNode(node, scope, buffer[position + 1], buffer);
  15564. },
  15565. function jsxOpeningElement(node, position, buffer) {
  15566. const { scope } = node;
  15567. const flags = buffer[position];
  15568. node.selfClosing = (flags & 1) === 1;
  15569. node.name = convertNode(node, scope, buffer[position + 1], buffer);
  15570. node.attributes = convertNodeList(node, scope, buffer[position + 2], buffer);
  15571. },
  15572. function jsxOpeningFragment(node) {
  15573. node.attributes = [];
  15574. node.selfClosing = false;
  15575. },
  15576. function jsxSpreadAttribute(node, position, buffer) {
  15577. const { scope } = node;
  15578. node.argument = convertNode(node, scope, buffer[position], buffer);
  15579. },
  15580. function jsxSpreadChild(node, position, buffer) {
  15581. const { scope } = node;
  15582. node.expression = convertNode(node, scope, buffer[position], buffer);
  15583. },
  15584. function jsxText(node, position, buffer) {
  15585. node.value = buffer.convertString(buffer[position]);
  15586. node.raw = buffer.convertString(buffer[position + 1]);
  15587. },
  15588. function labeledStatement(node, position, buffer) {
  15589. const { scope } = node;
  15590. node.label = convertNode(node, scope, buffer[position], buffer);
  15591. node.body = convertNode(node, scope, buffer[position + 1], buffer);
  15592. },
  15593. function literalBigInt(node, position, buffer) {
  15594. const bigint = (node.bigint = buffer.convertString(buffer[position]));
  15595. node.raw = buffer.convertString(buffer[position + 1]);
  15596. node.value = BigInt(bigint);
  15597. },
  15598. function literalBoolean(node, position, buffer) {
  15599. const flags = buffer[position];
  15600. const value = (node.value = (flags & 1) === 1);
  15601. node.raw = value ? 'true' : 'false';
  15602. },
  15603. function literalNull(node) {
  15604. node.value = null;
  15605. },
  15606. function literalNumber(node, position, buffer) {
  15607. const rawPosition = buffer[position];
  15608. node.raw = rawPosition === 0 ? undefined : buffer.convertString(rawPosition);
  15609. node.value = new DataView(buffer.buffer).getFloat64((position + 1) << 2, true);
  15610. },
  15611. function literalRegExp(node, position, buffer) {
  15612. const flags = buffer.convertString(buffer[position]);
  15613. const pattern = buffer.convertString(buffer[position + 1]);
  15614. node.raw = `/${pattern}/${flags}`;
  15615. node.regex = { flags, pattern };
  15616. node.value = new RegExp(pattern, flags);
  15617. },
  15618. function literalString(node, position, buffer) {
  15619. node.value = buffer.convertString(buffer[position]);
  15620. const rawPosition = buffer[position + 1];
  15621. node.raw = rawPosition === 0 ? undefined : buffer.convertString(rawPosition);
  15622. },
  15623. function logicalExpression(node, position, buffer) {
  15624. const { scope } = node;
  15625. node.operator = FIXED_STRINGS[buffer[position]];
  15626. node.left = convertNode(node, scope, buffer[position + 1], buffer);
  15627. node.right = convertNode(node, scope, buffer[position + 2], buffer);
  15628. },
  15629. function memberExpression(node, position, buffer) {
  15630. const { scope } = node;
  15631. const flags = buffer[position];
  15632. node.computed = (flags & 1) === 1;
  15633. node.optional = (flags & 2) === 2;
  15634. node.object = convertNode(node, scope, buffer[position + 1], buffer);
  15635. node.property = convertNode(node, scope, buffer[position + 2], buffer);
  15636. },
  15637. function metaProperty(node, position, buffer) {
  15638. const { scope } = node;
  15639. node.meta = convertNode(node, scope, buffer[position], buffer);
  15640. node.property = convertNode(node, scope, buffer[position + 1], buffer);
  15641. },
  15642. function methodDefinition(node, position, buffer) {
  15643. const { scope } = node;
  15644. const flags = buffer[position];
  15645. node.static = (flags & 1) === 1;
  15646. node.computed = (flags & 2) === 2;
  15647. node.decorators = convertNodeList(node, scope, buffer[position + 1], buffer);
  15648. node.key = convertNode(node, scope, buffer[position + 2], buffer);
  15649. node.value = convertNode(node, scope, buffer[position + 3], buffer);
  15650. node.kind = FIXED_STRINGS[buffer[position + 4]];
  15651. },
  15652. function newExpression(node, position, buffer) {
  15653. const { scope } = node;
  15654. node.annotations = convertAnnotations(buffer[position], buffer);
  15655. node.callee = convertNode(node, scope, buffer[position + 1], buffer);
  15656. node.arguments = convertNodeList(node, scope, buffer[position + 2], buffer);
  15657. },
  15658. function objectExpression(node, position, buffer) {
  15659. const { scope } = node;
  15660. node.properties = convertNodeList(node, scope, buffer[position], buffer);
  15661. },
  15662. function objectPattern(node, position, buffer) {
  15663. const { scope } = node;
  15664. node.properties = convertNodeList(node, scope, buffer[position], buffer);
  15665. },
  15666. function privateIdentifier(node, position, buffer) {
  15667. node.name = buffer.convertString(buffer[position]);
  15668. },
  15669. function program(node, position, buffer) {
  15670. const { scope } = node;
  15671. node.body = convertNodeList(node, scope, buffer[position], buffer);
  15672. node.invalidAnnotations = convertAnnotations(buffer[position + 1], buffer);
  15673. },
  15674. function property(node, position, buffer) {
  15675. const { scope } = node;
  15676. const flags = buffer[position];
  15677. node.method = (flags & 1) === 1;
  15678. node.shorthand = (flags & 2) === 2;
  15679. node.computed = (flags & 4) === 4;
  15680. const keyPosition = buffer[position + 1];
  15681. node.value = convertNode(node, scope, buffer[position + 2], buffer);
  15682. node.kind = FIXED_STRINGS[buffer[position + 3]];
  15683. node.key = keyPosition === 0 ? node.value : convertNode(node, scope, keyPosition, buffer);
  15684. },
  15685. function propertyDefinition(node, position, buffer) {
  15686. const { scope } = node;
  15687. const flags = buffer[position];
  15688. node.static = (flags & 1) === 1;
  15689. node.computed = (flags & 2) === 2;
  15690. node.decorators = convertNodeList(node, scope, buffer[position + 1], buffer);
  15691. node.key = convertNode(node, scope, buffer[position + 2], buffer);
  15692. const valuePosition = buffer[position + 3];
  15693. node.value = valuePosition === 0 ? null : convertNode(node, scope, valuePosition, buffer);
  15694. },
  15695. function restElement(node, position, buffer) {
  15696. const { scope } = node;
  15697. node.argument = convertNode(node, scope, buffer[position], buffer);
  15698. },
  15699. function returnStatement(node, position, buffer) {
  15700. const { scope } = node;
  15701. const argumentPosition = buffer[position];
  15702. node.argument =
  15703. argumentPosition === 0 ? null : convertNode(node, scope, argumentPosition, buffer);
  15704. },
  15705. function sequenceExpression(node, position, buffer) {
  15706. const { scope } = node;
  15707. node.expressions = convertNodeList(node, scope, buffer[position], buffer);
  15708. },
  15709. function spreadElement(node, position, buffer) {
  15710. const { scope } = node;
  15711. node.argument = convertNode(node, scope, buffer[position], buffer);
  15712. },
  15713. function staticBlock(node, position, buffer) {
  15714. const { scope } = node;
  15715. node.body = convertNodeList(node, scope, buffer[position], buffer);
  15716. },
  15717. function superElement() { },
  15718. function switchCase(node, position, buffer) {
  15719. const { scope } = node;
  15720. const testPosition = buffer[position];
  15721. node.test = testPosition === 0 ? null : convertNode(node, scope, testPosition, buffer);
  15722. node.consequent = convertNodeList(node, scope, buffer[position + 1], buffer);
  15723. },
  15724. function switchStatement(node, position, buffer) {
  15725. const { scope } = node;
  15726. node.discriminant = convertNode(node, node.parentScope, buffer[position], buffer);
  15727. node.cases = convertNodeList(node, scope, buffer[position + 1], buffer);
  15728. },
  15729. function taggedTemplateExpression(node, position, buffer) {
  15730. const { scope } = node;
  15731. node.tag = convertNode(node, scope, buffer[position], buffer);
  15732. node.quasi = convertNode(node, scope, buffer[position + 1], buffer);
  15733. },
  15734. function templateElement(node, position, buffer) {
  15735. const flags = buffer[position];
  15736. node.tail = (flags & 1) === 1;
  15737. const cookedPosition = buffer[position + 1];
  15738. const cooked = cookedPosition === 0 ? null : buffer.convertString(cookedPosition);
  15739. const raw = buffer.convertString(buffer[position + 2]);
  15740. node.value = { cooked, raw };
  15741. },
  15742. function templateLiteral(node, position, buffer) {
  15743. const { scope } = node;
  15744. node.quasis = convertNodeList(node, scope, buffer[position], buffer);
  15745. node.expressions = convertNodeList(node, scope, buffer[position + 1], buffer);
  15746. },
  15747. function thisExpression() { },
  15748. function throwStatement(node, position, buffer) {
  15749. const { scope } = node;
  15750. node.argument = convertNode(node, scope, buffer[position], buffer);
  15751. },
  15752. function tryStatement(node, position, buffer) {
  15753. const { scope } = node;
  15754. node.block = convertNode(node, scope, buffer[position], buffer);
  15755. const handlerPosition = buffer[position + 1];
  15756. node.handler = handlerPosition === 0 ? null : convertNode(node, scope, handlerPosition, buffer);
  15757. const finalizerPosition = buffer[position + 2];
  15758. node.finalizer =
  15759. finalizerPosition === 0 ? null : convertNode(node, scope, finalizerPosition, buffer);
  15760. },
  15761. function unaryExpression(node, position, buffer) {
  15762. const { scope } = node;
  15763. node.operator = FIXED_STRINGS[buffer[position]];
  15764. node.argument = convertNode(node, scope, buffer[position + 1], buffer);
  15765. },
  15766. function updateExpression(node, position, buffer) {
  15767. const { scope } = node;
  15768. const flags = buffer[position];
  15769. node.prefix = (flags & 1) === 1;
  15770. node.operator = FIXED_STRINGS[buffer[position + 1]];
  15771. node.argument = convertNode(node, scope, buffer[position + 2], buffer);
  15772. },
  15773. function variableDeclaration(node, position, buffer) {
  15774. const { scope } = node;
  15775. node.kind = FIXED_STRINGS[buffer[position]];
  15776. node.declarations = convertNodeList(node, scope, buffer[position + 1], buffer);
  15777. },
  15778. function variableDeclarator(node, position, buffer) {
  15779. const { scope } = node;
  15780. node.id = convertNode(node, scope, buffer[position], buffer);
  15781. const initPosition = buffer[position + 1];
  15782. node.init = initPosition === 0 ? null : convertNode(node, scope, initPosition, buffer);
  15783. },
  15784. function whileStatement(node, position, buffer) {
  15785. const { scope } = node;
  15786. node.test = convertNode(node, scope, buffer[position], buffer);
  15787. node.body = convertNode(node, scope, buffer[position + 1], buffer);
  15788. },
  15789. function yieldExpression(node, position, buffer) {
  15790. const { scope } = node;
  15791. const flags = buffer[position];
  15792. node.delegate = (flags & 1) === 1;
  15793. const argumentPosition = buffer[position + 1];
  15794. node.argument =
  15795. argumentPosition === 0 ? null : convertNode(node, scope, argumentPosition, buffer);
  15796. }
  15797. ];
  15798. function convertNode(parent, parentScope, position, buffer) {
  15799. const nodeType = buffer[position];
  15800. const NodeConstructor = nodeConstructors$1[nodeType];
  15801. /* istanbul ignore if: This should never be executed but is a safeguard against faulty buffers */
  15802. if (!NodeConstructor) {
  15803. console.trace();
  15804. throw new Error(`Unknown node type: ${nodeType}`);
  15805. }
  15806. const node = new NodeConstructor(parent, parentScope);
  15807. node.type = nodeTypeStrings[nodeType];
  15808. node.start = buffer[position + 1];
  15809. node.end = buffer[position + 2];
  15810. bufferParsers[nodeType](node, position + 3, buffer);
  15811. node.initialise();
  15812. return node;
  15813. }
  15814. function convertNodeList(parent, parentScope, position, buffer) {
  15815. if (position === 0)
  15816. return EMPTY_ARRAY;
  15817. const length = buffer[position++];
  15818. const list = new Array(length);
  15819. for (let index = 0; index < length; index++) {
  15820. const nodePosition = buffer[position++];
  15821. list[index] = nodePosition ? convertNode(parent, parentScope, nodePosition, buffer) : null;
  15822. }
  15823. return list;
  15824. }
  15825. class UnknownNode extends NodeBase {
  15826. hasEffects() {
  15827. return true;
  15828. }
  15829. include(context) {
  15830. super.include(context, true);
  15831. }
  15832. }
  15833. // This file is generated by scripts/generate-node-index.js.
  15834. // Do not edit this file directly.
  15835. const nodeConstructors = {
  15836. ArrayExpression,
  15837. ArrayPattern,
  15838. ArrowFunctionExpression,
  15839. AssignmentExpression,
  15840. AssignmentPattern,
  15841. AwaitExpression,
  15842. BinaryExpression,
  15843. BlockStatement,
  15844. BreakStatement,
  15845. CallExpression,
  15846. CatchClause,
  15847. ChainExpression,
  15848. ClassBody,
  15849. ClassDeclaration,
  15850. ClassExpression,
  15851. ConditionalExpression,
  15852. ContinueStatement,
  15853. DebuggerStatement,
  15854. Decorator,
  15855. DoWhileStatement,
  15856. EmptyStatement,
  15857. ExportAllDeclaration,
  15858. ExportDefaultDeclaration,
  15859. ExportNamedDeclaration,
  15860. ExportSpecifier,
  15861. ExpressionStatement,
  15862. ForInStatement,
  15863. ForOfStatement,
  15864. ForStatement,
  15865. FunctionDeclaration,
  15866. FunctionExpression,
  15867. Identifier,
  15868. IfStatement,
  15869. ImportAttribute,
  15870. ImportDeclaration,
  15871. ImportDefaultSpecifier,
  15872. ImportExpression,
  15873. ImportNamespaceSpecifier,
  15874. ImportSpecifier,
  15875. JSXAttribute,
  15876. JSXClosingElement,
  15877. JSXClosingFragment,
  15878. JSXElement,
  15879. JSXEmptyExpression,
  15880. JSXExpressionContainer,
  15881. JSXFragment,
  15882. JSXIdentifier,
  15883. JSXMemberExpression,
  15884. JSXNamespacedName,
  15885. JSXOpeningElement,
  15886. JSXOpeningFragment,
  15887. JSXSpreadAttribute,
  15888. JSXSpreadChild,
  15889. JSXText,
  15890. LabeledStatement,
  15891. Literal,
  15892. LogicalExpression,
  15893. MemberExpression,
  15894. MetaProperty,
  15895. MethodDefinition,
  15896. NewExpression,
  15897. ObjectExpression,
  15898. ObjectPattern,
  15899. PanicError,
  15900. ParseError,
  15901. PrivateIdentifier,
  15902. Program,
  15903. Property,
  15904. PropertyDefinition,
  15905. RestElement,
  15906. ReturnStatement,
  15907. SequenceExpression,
  15908. SpreadElement,
  15909. StaticBlock,
  15910. Super,
  15911. SwitchCase,
  15912. SwitchStatement,
  15913. TaggedTemplateExpression,
  15914. TemplateElement,
  15915. TemplateLiteral,
  15916. ThisExpression,
  15917. ThrowStatement,
  15918. TryStatement,
  15919. UnaryExpression,
  15920. UnknownNode,
  15921. UpdateExpression,
  15922. VariableDeclaration,
  15923. VariableDeclarator,
  15924. WhileStatement,
  15925. YieldExpression
  15926. };
  15927. class ExportShimVariable extends Variable {
  15928. constructor(module) {
  15929. super(MISSING_EXPORT_SHIM_VARIABLE);
  15930. this.module = module;
  15931. }
  15932. includePath(path, context) {
  15933. super.includePath(path, context);
  15934. this.module.needsExportShim = true;
  15935. }
  15936. }
  15937. var BuildPhase;
  15938. (function (BuildPhase) {
  15939. BuildPhase[BuildPhase["LOAD_AND_PARSE"] = 0] = "LOAD_AND_PARSE";
  15940. BuildPhase[BuildPhase["ANALYSE"] = 1] = "ANALYSE";
  15941. BuildPhase[BuildPhase["GENERATE"] = 2] = "GENERATE";
  15942. })(BuildPhase || (BuildPhase = {}));
  15943. const sourceMapCache = new WeakMap();
  15944. /**
  15945. * This clears the decoded array and falls back to the encoded string form.
  15946. * Sourcemap mappings arrays can be very large and holding on to them for longer
  15947. * than is necessary leads to poor heap utilization.
  15948. */
  15949. function resetCacheToEncoded(cache) {
  15950. if (cache.encodedMappings === undefined && cache.decodedMappings) {
  15951. cache.encodedMappings = encode(cache.decodedMappings);
  15952. }
  15953. cache.decodedMappings = undefined;
  15954. }
  15955. function resetSourcemapCache(map, sourcemapChain) {
  15956. if (map) {
  15957. const cache = sourceMapCache.get(map);
  15958. if (cache) {
  15959. resetCacheToEncoded(cache);
  15960. }
  15961. }
  15962. if (!sourcemapChain) {
  15963. return;
  15964. }
  15965. for (const map of sourcemapChain) {
  15966. if (map.missing)
  15967. continue;
  15968. resetSourcemapCache(map);
  15969. }
  15970. }
  15971. function decodedSourcemap(map) {
  15972. if (!map)
  15973. return null;
  15974. if (typeof map === 'string') {
  15975. map = JSON.parse(map);
  15976. }
  15977. if (!map.mappings) {
  15978. return {
  15979. mappings: [],
  15980. names: [],
  15981. sources: [],
  15982. version: 3
  15983. };
  15984. }
  15985. const originalMappings = map.mappings;
  15986. const isAlreadyDecoded = Array.isArray(originalMappings);
  15987. const cache = {
  15988. decodedMappings: isAlreadyDecoded ? originalMappings : undefined,
  15989. encodedMappings: isAlreadyDecoded ? undefined : originalMappings
  15990. };
  15991. const decodedMap = {
  15992. ...map,
  15993. // By moving mappings behind an accessor, we can avoid unneeded computation for cases
  15994. // where the mappings field is never actually accessed. This appears to greatly reduce
  15995. // the overhead of sourcemap decoding in terms of both compute time and memory usage.
  15996. get mappings() {
  15997. if (cache.decodedMappings) {
  15998. return cache.decodedMappings;
  15999. }
  16000. // If decodedMappings doesn't exist then encodedMappings should.
  16001. // The only scenario where cache.encodedMappings should be undefined is if the map
  16002. // this was constructed from was already decoded, or if mappings was set to a new
  16003. // decoded string. In either case, this line shouldn't get hit.
  16004. cache.decodedMappings = cache.encodedMappings ? decode(cache.encodedMappings) : [];
  16005. cache.encodedMappings = undefined;
  16006. return cache.decodedMappings;
  16007. }
  16008. };
  16009. sourceMapCache.set(decodedMap, cache);
  16010. return decodedMap;
  16011. }
  16012. function getId(m) {
  16013. return m.id;
  16014. }
  16015. function getOriginalLocation(sourcemapChain, location) {
  16016. const filteredSourcemapChain = sourcemapChain.filter((sourcemap) => !sourcemap.missing);
  16017. traceSourcemap: while (filteredSourcemapChain.length > 0) {
  16018. const sourcemap = filteredSourcemapChain.pop();
  16019. const line = sourcemap.mappings[location.line - 1];
  16020. if (line) {
  16021. const filteredLine = line.filter((segment) => segment.length > 1);
  16022. const lastSegment = filteredLine[filteredLine.length - 1];
  16023. let previousSegment = filteredLine[0];
  16024. for (let segment of filteredLine) {
  16025. if (segment[0] >= location.column || segment === lastSegment) {
  16026. const notMatched = segment[0] !== location.column;
  16027. segment = notMatched ? previousSegment : segment;
  16028. location = {
  16029. column: segment[3],
  16030. line: segment[2] + 1
  16031. };
  16032. continue traceSourcemap;
  16033. }
  16034. previousSegment = segment;
  16035. }
  16036. }
  16037. throw new Error("Can't resolve original location of error.");
  16038. }
  16039. return location;
  16040. }
  16041. const ATTRIBUTE_KEYWORDS = new Set(['assert', 'with']);
  16042. function getAttributesFromImportExpression(node) {
  16043. const { scope: { context }, options, start } = node;
  16044. if (!(options instanceof ObjectExpression)) {
  16045. if (options) {
  16046. context.module.log(LOGLEVEL_WARN, logImportAttributeIsInvalid(context.module.id), start);
  16047. }
  16048. return EMPTY_OBJECT;
  16049. }
  16050. const assertProperty = options.properties.find((property) => ATTRIBUTE_KEYWORDS.has(getPropertyKey(property)))?.value;
  16051. if (!assertProperty) {
  16052. return EMPTY_OBJECT;
  16053. }
  16054. if (!(assertProperty instanceof ObjectExpression)) {
  16055. context.module.log(LOGLEVEL_WARN, logImportOptionsAreInvalid(context.module.id), start);
  16056. return EMPTY_OBJECT;
  16057. }
  16058. const assertFields = assertProperty.properties
  16059. .map(property => {
  16060. const key = getPropertyKey(property);
  16061. if (typeof key === 'string' &&
  16062. typeof property.value.value === 'string') {
  16063. return [key, property.value.value];
  16064. }
  16065. context.module.log(LOGLEVEL_WARN, logImportAttributeIsInvalid(context.module.id), property.start);
  16066. return null;
  16067. })
  16068. .filter((property) => !!property);
  16069. if (assertFields.length > 0) {
  16070. return Object.fromEntries(assertFields);
  16071. }
  16072. return EMPTY_OBJECT;
  16073. }
  16074. const getPropertyKey = (property) => {
  16075. const key = property.key;
  16076. return (key &&
  16077. !property.computed &&
  16078. (key.name || key.value));
  16079. };
  16080. function getAttributesFromImportExportDeclaration(attributes) {
  16081. return attributes?.length
  16082. ? Object.fromEntries(attributes.map(assertion => [getPropertyKey(assertion), assertion.value.value]))
  16083. : EMPTY_OBJECT;
  16084. }
  16085. function doAttributesDiffer(assertionA, assertionB) {
  16086. const keysA = Object.keys(assertionA);
  16087. return (keysA.length !== Object.keys(assertionB).length ||
  16088. keysA.some(key => assertionA[key] !== assertionB[key]));
  16089. }
  16090. let timers = new Map();
  16091. function getPersistedLabel(label, level) {
  16092. switch (level) {
  16093. case 1: {
  16094. return `# ${label}`;
  16095. }
  16096. case 2: {
  16097. return `## ${label}`;
  16098. }
  16099. case 3: {
  16100. return label;
  16101. }
  16102. default: {
  16103. return `- ${label}`;
  16104. }
  16105. }
  16106. }
  16107. function timeStartImpl(label, level = 3) {
  16108. label = getPersistedLabel(label, level);
  16109. const startMemory = process$1.memoryUsage().heapUsed;
  16110. const startTime = performance.now();
  16111. const timer = timers.get(label);
  16112. if (timer === undefined) {
  16113. timers.set(label, {
  16114. memory: 0,
  16115. startMemory,
  16116. startTime,
  16117. time: 0,
  16118. totalMemory: 0
  16119. });
  16120. }
  16121. else {
  16122. timer.startMemory = startMemory;
  16123. timer.startTime = startTime;
  16124. }
  16125. }
  16126. function timeEndImpl(label, level = 3) {
  16127. label = getPersistedLabel(label, level);
  16128. const timer = timers.get(label);
  16129. if (timer !== undefined) {
  16130. const currentMemory = process$1.memoryUsage().heapUsed;
  16131. timer.memory += currentMemory - timer.startMemory;
  16132. timer.time += performance.now() - timer.startTime;
  16133. timer.totalMemory = Math.max(timer.totalMemory, currentMemory);
  16134. }
  16135. }
  16136. function getTimings() {
  16137. const newTimings = {};
  16138. for (const [label, { memory, time, totalMemory }] of timers) {
  16139. newTimings[label] = [time, memory, totalMemory];
  16140. }
  16141. return newTimings;
  16142. }
  16143. let timeStart = doNothing;
  16144. let timeEnd = doNothing;
  16145. const TIMED_PLUGIN_HOOKS = [
  16146. 'augmentChunkHash',
  16147. 'buildEnd',
  16148. 'buildStart',
  16149. 'generateBundle',
  16150. 'load',
  16151. 'moduleParsed',
  16152. 'options',
  16153. 'outputOptions',
  16154. 'renderChunk',
  16155. 'renderDynamicImport',
  16156. 'renderStart',
  16157. 'resolveDynamicImport',
  16158. 'resolveFileUrl',
  16159. 'resolveId',
  16160. 'resolveImportMeta',
  16161. 'shouldTransformCachedModule',
  16162. 'transform',
  16163. 'writeBundle'
  16164. ];
  16165. function getPluginWithTimers(plugin, index) {
  16166. if (plugin._hasTimer)
  16167. return plugin;
  16168. plugin._hasTimer = true;
  16169. for (const hook of TIMED_PLUGIN_HOOKS) {
  16170. if (hook in plugin) {
  16171. let timerLabel = `plugin ${index}`;
  16172. if (plugin.name) {
  16173. timerLabel += ` (${plugin.name})`;
  16174. }
  16175. timerLabel += ` - ${hook}`;
  16176. const handler = function (...parameters) {
  16177. timeStart(timerLabel, 4);
  16178. const result = hookFunction.apply(this, parameters);
  16179. timeEnd(timerLabel, 4);
  16180. return result;
  16181. };
  16182. let hookFunction;
  16183. if (typeof plugin[hook].handler === 'function') {
  16184. hookFunction = plugin[hook].handler;
  16185. plugin[hook].handler = handler;
  16186. }
  16187. else {
  16188. hookFunction = plugin[hook];
  16189. plugin[hook] = handler;
  16190. }
  16191. }
  16192. }
  16193. return plugin;
  16194. }
  16195. function initialiseTimers(inputOptions) {
  16196. if (inputOptions.perf) {
  16197. timers = new Map();
  16198. timeStart = timeStartImpl;
  16199. timeEnd = timeEndImpl;
  16200. inputOptions.plugins = inputOptions.plugins.map(getPluginWithTimers);
  16201. }
  16202. else {
  16203. timeStart = doNothing;
  16204. timeEnd = doNothing;
  16205. }
  16206. }
  16207. const MISSING_EXPORT_SHIM_DESCRIPTION = {
  16208. identifier: null,
  16209. localName: MISSING_EXPORT_SHIM_VARIABLE
  16210. };
  16211. function getVariableForExportNameRecursive(target, name, importerForSideEffects, isExportAllSearch, searchedNamesAndModules = new Map(), importChain, sideEffectModules, exportOrReexportModules) {
  16212. const searchedModules = searchedNamesAndModules.get(name);
  16213. if (searchedModules) {
  16214. if (searchedModules.has(target)) {
  16215. return isExportAllSearch ? [null] : error(logCircularReexport(name, target.id));
  16216. }
  16217. searchedModules.add(target);
  16218. }
  16219. else {
  16220. searchedNamesAndModules.set(name, new Set([target]));
  16221. }
  16222. return target.getVariableForExportName(name, {
  16223. exportOrReexportModules,
  16224. importChain,
  16225. importerForSideEffects,
  16226. isExportAllSearch,
  16227. searchedNamesAndModules,
  16228. sideEffectModules
  16229. });
  16230. }
  16231. function getAndExtendSideEffectModules(variable, module) {
  16232. const sideEffectModules = getOrCreate(module.sideEffectDependenciesByVariable, variable, (getNewSet));
  16233. let currentVariable = variable;
  16234. const referencedVariables = new Set([currentVariable]);
  16235. while (true) {
  16236. const importingModule = currentVariable.module;
  16237. currentVariable =
  16238. currentVariable instanceof ExportDefaultVariable
  16239. ? currentVariable.getDirectOriginalVariable()
  16240. : currentVariable instanceof SyntheticNamedExportVariable
  16241. ? currentVariable.syntheticNamespace
  16242. : null;
  16243. if (!currentVariable || referencedVariables.has(currentVariable)) {
  16244. break;
  16245. }
  16246. referencedVariables.add(currentVariable);
  16247. sideEffectModules.add(importingModule);
  16248. const originalSideEffects = importingModule.sideEffectDependenciesByVariable.get(currentVariable);
  16249. if (originalSideEffects) {
  16250. for (const module of originalSideEffects) {
  16251. sideEffectModules.add(module);
  16252. }
  16253. }
  16254. }
  16255. return sideEffectModules;
  16256. }
  16257. class Module {
  16258. constructor(graph, id, options, isEntry, moduleSideEffects, syntheticNamedExports, meta, attributes) {
  16259. this.graph = graph;
  16260. this.id = id;
  16261. this.options = options;
  16262. this.alternativeReexportModules = new Map();
  16263. this.chunkFileNames = new Set();
  16264. this.chunkNames = [];
  16265. this.cycles = new Set();
  16266. this.dependencies = new Set();
  16267. this.dynamicDependencies = new Set();
  16268. this.dynamicImporters = [];
  16269. this.dynamicImports = [];
  16270. this.execIndex = Infinity;
  16271. this.hasTreeShakingPassStarted = false;
  16272. this.implicitlyLoadedAfter = new Set();
  16273. this.implicitlyLoadedBefore = new Set();
  16274. this.importDescriptions = new Map();
  16275. this.importMetas = [];
  16276. this.importedFromNotTreeshaken = false;
  16277. this.importers = [];
  16278. this.includedDynamicImporters = [];
  16279. this.includedTopLevelAwaitingDynamicImporters = new Set();
  16280. this.includedImports = new Set();
  16281. this.isExecuted = false;
  16282. this.isUserDefinedEntryPoint = false;
  16283. this.needsExportShim = false;
  16284. this.sideEffectDependenciesByVariable = new Map();
  16285. this.sourcePhaseSources = new Set();
  16286. this.sourcesWithAttributes = new Map();
  16287. this.allExportsIncluded = false;
  16288. this.ast = null;
  16289. this.exportAllModules = [];
  16290. this.exportAllSources = new Set();
  16291. this.exportDescriptions = new Map();
  16292. this.exportedVariablesByName = null;
  16293. this.exportNamesByVariable = null;
  16294. this.exportShimVariable = new ExportShimVariable(this);
  16295. this.namespaceReexportsByName = new Map();
  16296. this.reexportDescriptions = new Map();
  16297. this.relevantDependencies = null;
  16298. this.syntheticExports = new Map();
  16299. this.syntheticNamespace = null;
  16300. this.transformDependencies = [];
  16301. this.excludeFromSourcemap = /\0/.test(id);
  16302. this.context = options.moduleContext(id);
  16303. this.preserveSignature = this.options.preserveEntrySignatures;
  16304. // eslint-disable-next-line @typescript-eslint/no-this-alias
  16305. const module = this;
  16306. const { dynamicImports, dynamicImporters, exportAllSources, exportDescriptions, implicitlyLoadedAfter, implicitlyLoadedBefore, importers, reexportDescriptions, sourcesWithAttributes } = this;
  16307. this.info = {
  16308. ast: null,
  16309. attributes,
  16310. code: null,
  16311. get dynamicallyImportedIdResolutions() {
  16312. return dynamicImports
  16313. .map(({ argument }) => typeof argument === 'string' && module.resolvedIds[argument])
  16314. .filter(Boolean);
  16315. },
  16316. get dynamicallyImportedIds() {
  16317. // We cannot use this.dynamicDependencies because this is needed before
  16318. // dynamicDependencies are populated
  16319. return dynamicImports.map(({ id }) => id).filter((id) => id != null);
  16320. },
  16321. get dynamicImporters() {
  16322. return dynamicImporters.sort();
  16323. },
  16324. get exportedBindings() {
  16325. const exportBindings = { '.': [...exportDescriptions.keys()] };
  16326. for (const [name, { source }] of reexportDescriptions) {
  16327. (exportBindings[source] ??= []).push(name);
  16328. }
  16329. for (const source of exportAllSources) {
  16330. (exportBindings[source] ??= []).push('*');
  16331. }
  16332. return exportBindings;
  16333. },
  16334. get exports() {
  16335. return [
  16336. ...exportDescriptions.keys(),
  16337. ...reexportDescriptions.keys(),
  16338. ...[...exportAllSources].map(() => '*')
  16339. ];
  16340. },
  16341. get hasDefaultExport() {
  16342. // This information is only valid after parsing
  16343. if (!module.ast) {
  16344. return null;
  16345. }
  16346. return module.exportDescriptions.has('default') || reexportDescriptions.has('default');
  16347. },
  16348. id,
  16349. get implicitlyLoadedAfterOneOf() {
  16350. return Array.from(implicitlyLoadedAfter, getId).sort();
  16351. },
  16352. get implicitlyLoadedBefore() {
  16353. return Array.from(implicitlyLoadedBefore, getId).sort();
  16354. },
  16355. get importedIdResolutions() {
  16356. return Array.from(sourcesWithAttributes.keys(), source => module.resolvedIds[source]).filter(Boolean);
  16357. },
  16358. get importedIds() {
  16359. // We cannot use this.dependencies because this is needed before
  16360. // dependencies are populated
  16361. return Array.from(sourcesWithAttributes.keys(), source => module.resolvedIds[source]?.id).filter(Boolean);
  16362. },
  16363. get importers() {
  16364. return importers.sort();
  16365. },
  16366. isEntry,
  16367. isExternal: false,
  16368. get isIncluded() {
  16369. if (graph.phase !== BuildPhase.GENERATE) {
  16370. return null;
  16371. }
  16372. return module.isIncluded();
  16373. },
  16374. meta: { ...meta },
  16375. moduleSideEffects,
  16376. safeVariableNames: null,
  16377. syntheticNamedExports
  16378. };
  16379. }
  16380. basename() {
  16381. const base = basename(this.id);
  16382. const extension = extname(this.id);
  16383. return makeLegal(extension ? base.slice(0, -extension.length) : base);
  16384. }
  16385. bindReferences() {
  16386. this.ast.bind();
  16387. }
  16388. cacheInfoGetters() {
  16389. cacheObjectGetters(this.info, [
  16390. 'dynamicallyImportedIdResolutions',
  16391. 'dynamicallyImportedIds',
  16392. 'dynamicImporters',
  16393. 'exportedBindings',
  16394. 'exports',
  16395. 'hasDefaultExport',
  16396. 'implicitlyLoadedAfterOneOf',
  16397. 'implicitlyLoadedBefore',
  16398. 'importedIdResolutions',
  16399. 'importedIds',
  16400. 'importers'
  16401. ]);
  16402. }
  16403. error(properties, pos) {
  16404. if (pos !== undefined) {
  16405. this.addLocationToLogProps(properties, pos);
  16406. }
  16407. return error(properties);
  16408. }
  16409. // sum up the length of all ast nodes that are included
  16410. estimateSize() {
  16411. let size = 0;
  16412. for (const node of this.ast.body) {
  16413. if (node.included) {
  16414. size += node.end - node.start;
  16415. }
  16416. }
  16417. return size;
  16418. }
  16419. getDependenciesToBeIncluded() {
  16420. if (this.relevantDependencies)
  16421. return this.relevantDependencies;
  16422. this.relevantDependencies = new Set();
  16423. const necessaryDependencies = new Set();
  16424. const alwaysCheckedDependencies = new Set();
  16425. const dependencyVariables = new Set(this.includedImports);
  16426. if (this.info.isEntry ||
  16427. this.includedDynamicImporters.length > 0 ||
  16428. this.namespace.included ||
  16429. this.implicitlyLoadedAfter.size > 0) {
  16430. for (const variable of this.getExportedVariablesByName().values()) {
  16431. if (variable.included) {
  16432. dependencyVariables.add(variable);
  16433. }
  16434. }
  16435. }
  16436. for (let variable of dependencyVariables) {
  16437. const sideEffectDependencies = this.sideEffectDependenciesByVariable.get(variable);
  16438. if (sideEffectDependencies) {
  16439. for (const module of sideEffectDependencies) {
  16440. alwaysCheckedDependencies.add(module);
  16441. }
  16442. }
  16443. if (variable instanceof SyntheticNamedExportVariable) {
  16444. variable = variable.getBaseVariable();
  16445. }
  16446. else if (variable instanceof ExportDefaultVariable) {
  16447. variable = variable.getOriginalVariable();
  16448. }
  16449. necessaryDependencies.add(variable.module);
  16450. }
  16451. if (!this.options.treeshake || this.info.moduleSideEffects === 'no-treeshake') {
  16452. for (const dependency of this.dependencies) {
  16453. this.relevantDependencies.add(dependency);
  16454. }
  16455. }
  16456. else {
  16457. this.addRelevantSideEffectDependencies(this.relevantDependencies, necessaryDependencies, alwaysCheckedDependencies);
  16458. }
  16459. for (const dependency of necessaryDependencies) {
  16460. this.relevantDependencies.add(dependency);
  16461. }
  16462. return this.relevantDependencies;
  16463. }
  16464. getExportedVariablesByName() {
  16465. if (this.exportedVariablesByName) {
  16466. return this.exportedVariablesByName;
  16467. }
  16468. const exportedVariablesByName = (this.exportedVariablesByName = new Map());
  16469. for (const name of this.exportDescriptions.keys()) {
  16470. // We do not count the synthetic namespace as a regular export to hide it
  16471. // from entry signatures and namespace objects
  16472. if (name !== this.info.syntheticNamedExports) {
  16473. const [exportedVariable] = this.getVariableForExportName(name);
  16474. if (exportedVariable) {
  16475. exportedVariablesByName.set(name, exportedVariable);
  16476. }
  16477. else {
  16478. return error(logMissingEntryExport(name, this.id));
  16479. }
  16480. }
  16481. }
  16482. for (const name of this.reexportDescriptions.keys()) {
  16483. const [exportedVariable] = this.getVariableForExportName(name);
  16484. if (exportedVariable) {
  16485. exportedVariablesByName.set(name, exportedVariable);
  16486. }
  16487. }
  16488. for (const module of this.exportAllModules) {
  16489. if (module instanceof ExternalModule) {
  16490. exportedVariablesByName.set(`*${module.id}`, module.getVariableForExportName('*', {
  16491. importChain: [this.id]
  16492. })[0]);
  16493. continue;
  16494. }
  16495. for (const name of module.getExportedVariablesByName().keys()) {
  16496. if (name !== 'default' && !exportedVariablesByName.has(name)) {
  16497. const [exportedVariable] = this.getVariableForExportName(name);
  16498. if (exportedVariable) {
  16499. exportedVariablesByName.set(name, exportedVariable);
  16500. }
  16501. }
  16502. }
  16503. }
  16504. return (this.exportedVariablesByName = new Map([...exportedVariablesByName].sort(sortExportedVariables)));
  16505. }
  16506. getExportNamesByVariable() {
  16507. if (this.exportNamesByVariable) {
  16508. return this.exportNamesByVariable;
  16509. }
  16510. const exportNamesByVariable = new Map();
  16511. for (const [exportName, variable] of this.getExportedVariablesByName().entries()) {
  16512. const tracedVariable = variable instanceof ExportDefaultVariable ? variable.getOriginalVariable() : variable;
  16513. if (!variable || !(variable.included || variable instanceof ExternalVariable)) {
  16514. continue;
  16515. }
  16516. const existingExportNames = exportNamesByVariable.get(tracedVariable);
  16517. if (existingExportNames) {
  16518. existingExportNames.push(exportName);
  16519. }
  16520. else {
  16521. exportNamesByVariable.set(tracedVariable, [exportName]);
  16522. }
  16523. }
  16524. return (this.exportNamesByVariable = exportNamesByVariable);
  16525. }
  16526. getRenderedExports() {
  16527. // only direct exports are counted here, not reexports at all
  16528. const renderedExports = [];
  16529. const removedExports = [];
  16530. for (const exportName of this.exportDescriptions.keys()) {
  16531. (this.getExportedVariablesByName().get(exportName)?.included
  16532. ? renderedExports
  16533. : removedExports).push(exportName);
  16534. }
  16535. return { removedExports, renderedExports };
  16536. }
  16537. getSyntheticNamespace() {
  16538. if (this.syntheticNamespace === null) {
  16539. this.syntheticNamespace = undefined;
  16540. [this.syntheticNamespace] = this.getVariableForExportName(typeof this.info.syntheticNamedExports === 'string'
  16541. ? this.info.syntheticNamedExports
  16542. : 'default', { onlyExplicit: true });
  16543. }
  16544. if (!this.syntheticNamespace) {
  16545. return error(logSyntheticNamedExportsNeedNamespaceExport(this.id, this.info.syntheticNamedExports));
  16546. }
  16547. return this.syntheticNamespace;
  16548. }
  16549. getVariableForExportName(name, { importerForSideEffects, importChain = [], isExportAllSearch, onlyExplicit, searchedNamesAndModules, sideEffectModules, exportOrReexportModules } = EMPTY_OBJECT) {
  16550. if (name[0] === '*') {
  16551. if (name.length === 1) {
  16552. // export * from './other'
  16553. return [this.namespace];
  16554. }
  16555. // export * from 'external'
  16556. const module = this.graph.modulesById.get(name.slice(1));
  16557. return module.getVariableForExportName('*', {
  16558. importChain: [...importChain, this.id]
  16559. });
  16560. }
  16561. // export { foo } from './other'
  16562. const reexportDeclaration = this.reexportDescriptions.get(name);
  16563. if (reexportDeclaration) {
  16564. const [variable, options] = getVariableForExportNameRecursive(reexportDeclaration.module, reexportDeclaration.localName, importerForSideEffects, false, searchedNamesAndModules, [...importChain, this.id], sideEffectModules, exportOrReexportModules);
  16565. if (!variable) {
  16566. return this.error(logMissingExport(reexportDeclaration.localName, this.id, reexportDeclaration.module.id, !!options?.missingButExportExists), reexportDeclaration.start);
  16567. }
  16568. if (importerForSideEffects) {
  16569. setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
  16570. if (this.info.moduleSideEffects) {
  16571. getOrCreate(importerForSideEffects.sideEffectDependenciesByVariable, variable, (getNewSet)).add(this);
  16572. }
  16573. }
  16574. if (this.info.moduleSideEffects) {
  16575. sideEffectModules?.add(this);
  16576. }
  16577. exportOrReexportModules?.add(this);
  16578. return [variable];
  16579. }
  16580. const exportDeclaration = this.exportDescriptions.get(name);
  16581. if (exportDeclaration) {
  16582. if (exportDeclaration === MISSING_EXPORT_SHIM_DESCRIPTION) {
  16583. return [this.exportShimVariable];
  16584. }
  16585. const name = exportDeclaration.localName;
  16586. const variable = this.traceVariable(name, {
  16587. exportOrReexportModules,
  16588. importerForSideEffects,
  16589. searchedNamesAndModules,
  16590. sideEffectModules
  16591. });
  16592. if (!variable) {
  16593. return [null, { missingButExportExists: true }];
  16594. }
  16595. if (importerForSideEffects) {
  16596. setAlternativeExporterIfCyclic(variable, importerForSideEffects, this);
  16597. getOrCreate(importerForSideEffects.sideEffectDependenciesByVariable, variable, (getNewSet)).add(this);
  16598. }
  16599. sideEffectModules?.add(this);
  16600. exportOrReexportModules?.add(this);
  16601. return [variable];
  16602. }
  16603. if (onlyExplicit) {
  16604. return [null];
  16605. }
  16606. if (name !== 'default') {
  16607. const foundNamespaceReexport = this.namespaceReexportsByName.get(name) ??
  16608. this.getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules, [...importChain, this.id]);
  16609. this.namespaceReexportsByName.set(name, foundNamespaceReexport);
  16610. if (foundNamespaceReexport[0]) {
  16611. const [namespaceReexportVariable, namespaceReexportOptions] = foundNamespaceReexport;
  16612. if (importerForSideEffects) {
  16613. const { exportOrReexportModules, sideEffectModules } = namespaceReexportOptions;
  16614. for (const module of exportOrReexportModules) {
  16615. if (importerForSideEffects.alternativeReexportModules.has(namespaceReexportVariable)) {
  16616. continue;
  16617. }
  16618. setAlternativeExporterIfCyclic(namespaceReexportVariable, importerForSideEffects, module);
  16619. }
  16620. for (const module of sideEffectModules) {
  16621. getOrCreate(importerForSideEffects.sideEffectDependenciesByVariable, namespaceReexportVariable, (getNewSet)).add(module);
  16622. }
  16623. }
  16624. return foundNamespaceReexport;
  16625. }
  16626. }
  16627. if (this.info.syntheticNamedExports) {
  16628. return [
  16629. getOrCreate(this.syntheticExports, name, () => new SyntheticNamedExportVariable(this.astContext, name, this.getSyntheticNamespace()))
  16630. ];
  16631. }
  16632. // we don't want to create shims when we are just
  16633. // probing export * modules for exports
  16634. if (!isExportAllSearch && this.options.shimMissingExports) {
  16635. this.shimMissingExport(name);
  16636. return [this.exportShimVariable];
  16637. }
  16638. return [null];
  16639. }
  16640. hasEffects() {
  16641. return this.info.moduleSideEffects === 'no-treeshake' || this.ast.hasCachedEffects();
  16642. }
  16643. include() {
  16644. const context = createInclusionContext();
  16645. if (this.ast.shouldBeIncluded(context))
  16646. this.ast.include(context, false);
  16647. }
  16648. includeAllExports() {
  16649. if (this.allExportsIncluded)
  16650. return;
  16651. this.allExportsIncluded = true;
  16652. this.includeModuleInExecution();
  16653. const inclusionContext = createInclusionContext();
  16654. for (const variable of this.getExportedVariablesByName().values()) {
  16655. this.includeVariable(variable, UNKNOWN_PATH, inclusionContext);
  16656. variable.deoptimizePath(UNKNOWN_PATH);
  16657. if (variable instanceof ExternalVariable) {
  16658. variable.module.reexported = true;
  16659. }
  16660. }
  16661. }
  16662. includeAllInBundle() {
  16663. this.ast.include(createInclusionContext(), true);
  16664. this.includeAllExports();
  16665. }
  16666. includeModuleInExecution() {
  16667. if (!this.isExecuted) {
  16668. markModuleAndImpureDependenciesAsExecuted(this);
  16669. this.graph.needsTreeshakingPass = true;
  16670. }
  16671. }
  16672. isIncluded() {
  16673. // Modules where this.ast is missing have been loaded via this.load and are
  16674. // not yet fully processed, hence they cannot be included.
  16675. return (this.ast &&
  16676. (this.ast.included ||
  16677. this.namespace.included ||
  16678. this.importedFromNotTreeshaken ||
  16679. this.exportShimVariable.included));
  16680. }
  16681. linkImports() {
  16682. this.addModulesToImportDescriptions(this.importDescriptions);
  16683. this.addModulesToImportDescriptions(this.reexportDescriptions);
  16684. const externalExportAllModules = [];
  16685. for (const source of this.exportAllSources) {
  16686. const module = this.graph.modulesById.get(this.resolvedIds[source].id);
  16687. if (module instanceof ExternalModule) {
  16688. externalExportAllModules.push(module);
  16689. continue;
  16690. }
  16691. this.exportAllModules.push(module);
  16692. }
  16693. this.exportAllModules.push(...externalExportAllModules);
  16694. }
  16695. log(level, properties, pos) {
  16696. this.addLocationToLogProps(properties, pos);
  16697. this.options.onLog(level, properties);
  16698. }
  16699. render(options) {
  16700. const source = this.magicString.clone();
  16701. this.ast.render(source, options);
  16702. source.trim();
  16703. const { usesTopLevelAwait } = this.astContext;
  16704. if (usesTopLevelAwait && options.format !== 'es' && options.format !== 'system') {
  16705. return error(logInvalidFormatForTopLevelAwait(this.id, options.format));
  16706. }
  16707. return { source, usesTopLevelAwait };
  16708. }
  16709. async setSource({ ast, code, customTransformCache, originalCode, originalSourcemap, resolvedIds, sourcemapChain, transformDependencies, transformFiles, safeVariableNames, ...moduleOptions }) {
  16710. timeStart('generate ast', 3);
  16711. if (code.startsWith('#!')) {
  16712. const shebangEndPosition = code.indexOf('\n');
  16713. this.shebang = code.slice(2, shebangEndPosition);
  16714. }
  16715. this.info.code = code;
  16716. this.info.safeVariableNames = safeVariableNames;
  16717. this.originalCode = originalCode;
  16718. // We need to call decodedSourcemap on the input in case they were hydrated from json in the cache and don't
  16719. // have the lazy evaluation cache configured. Right now this isn't enforced by the type system because the
  16720. // RollupCache stores `ExistingDecodedSourcemap` instead of `ExistingRawSourcemap`
  16721. this.originalSourcemap = decodedSourcemap(originalSourcemap);
  16722. this.sourcemapChain = sourcemapChain.map(mapOrMissing => mapOrMissing.missing ? mapOrMissing : decodedSourcemap(mapOrMissing));
  16723. // If coming from cache and this value is already fully decoded, we want to re-encode here to save memory.
  16724. resetSourcemapCache(this.originalSourcemap, this.sourcemapChain);
  16725. if (transformFiles) {
  16726. this.transformFiles = transformFiles;
  16727. }
  16728. this.transformDependencies = transformDependencies;
  16729. this.customTransformCache = customTransformCache;
  16730. this.updateOptions(moduleOptions);
  16731. this.resolvedIds = resolvedIds ?? Object.create(null);
  16732. // By default, `id` is the file name. Custom resolvers and loaders
  16733. // can change that, but it makes sense to use it for the source file name
  16734. const fileName = this.id;
  16735. this.magicString = new MagicString(code, {
  16736. filename: (this.excludeFromSourcemap ? null : fileName), // don't include plugin helpers in sourcemap
  16737. indentExclusionRanges: []
  16738. });
  16739. this.astContext = {
  16740. addDynamicImport: this.addDynamicImport.bind(this),
  16741. addExport: this.addExport.bind(this),
  16742. addImport: this.addImport.bind(this),
  16743. addImportMeta: this.addImportMeta.bind(this),
  16744. addImportSource: this.addImportSource.bind(this),
  16745. code, // Only needed for debugging
  16746. deoptimizationTracker: this.graph.deoptimizationTracker,
  16747. error: this.error.bind(this),
  16748. fileName, // Needed for warnings
  16749. getImportedJsxFactoryVariable: this.getImportedJsxFactoryVariable.bind(this),
  16750. getModuleExecIndex: () => this.execIndex,
  16751. getModuleName: this.basename.bind(this),
  16752. getNodeConstructor: (name) => nodeConstructors[name] || nodeConstructors.UnknownNode,
  16753. importDescriptions: this.importDescriptions,
  16754. includeDynamicImport: this.includeDynamicImport.bind(this),
  16755. includeVariableInModule: this.includeVariableInModule.bind(this),
  16756. log: this.log.bind(this),
  16757. magicString: this.magicString,
  16758. manualPureFunctions: this.graph.pureFunctions,
  16759. module: this,
  16760. moduleContext: this.context,
  16761. newlyIncludedVariableInits: this.graph.newlyIncludedVariableInits,
  16762. options: this.options,
  16763. requestTreeshakingPass: () => (this.graph.needsTreeshakingPass = true),
  16764. traceExport: (name) => this.getVariableForExportName(name),
  16765. traceVariable: this.traceVariable.bind(this),
  16766. usesTopLevelAwait: false
  16767. };
  16768. this.scope = new ModuleScope(this.graph.scope, this.astContext, this.importDescriptions);
  16769. this.namespace = new NamespaceVariable(this.astContext);
  16770. const programParent = { context: this.astContext, type: 'Module' };
  16771. if (ast) {
  16772. this.ast = new nodeConstructors[ast.type](programParent, this.scope).parseNode(ast);
  16773. this.info.ast = ast;
  16774. }
  16775. else {
  16776. // Measuring asynchronous code does not provide reasonable results
  16777. timeEnd('generate ast', 3);
  16778. const astBuffer = await parseAsync(code, false, this.options.jsx !== false);
  16779. timeStart('generate ast', 3);
  16780. this.ast = convertProgram(astBuffer, programParent, this.scope);
  16781. // Make lazy and apply LRU cache to not hog the memory
  16782. Object.defineProperty(this.info, 'ast', {
  16783. get: () => {
  16784. if (this.graph.astLru.has(fileName)) {
  16785. return this.graph.astLru.get(fileName);
  16786. }
  16787. else {
  16788. const parsedAst = this.tryParse();
  16789. // If the cache is not disabled, we need to keep the AST in memory
  16790. // until the end when the cache is generated
  16791. if (this.options.cache !== false) {
  16792. Object.defineProperty(this.info, 'ast', {
  16793. value: parsedAst
  16794. });
  16795. return parsedAst;
  16796. }
  16797. // Otherwise, we keep it in a small LRU cache to not hog too much
  16798. // memory but allow the same AST to be requested several times.
  16799. this.graph.astLru.set(fileName, parsedAst);
  16800. return parsedAst;
  16801. }
  16802. }
  16803. });
  16804. }
  16805. timeEnd('generate ast', 3);
  16806. }
  16807. toJSON() {
  16808. return {
  16809. ast: this.info.ast,
  16810. attributes: this.info.attributes,
  16811. code: this.info.code,
  16812. customTransformCache: this.customTransformCache,
  16813. dependencies: Array.from(this.dependencies, getId),
  16814. id: this.id,
  16815. meta: this.info.meta,
  16816. moduleSideEffects: this.info.moduleSideEffects,
  16817. originalCode: this.originalCode,
  16818. originalSourcemap: this.originalSourcemap,
  16819. resolvedIds: this.resolvedIds,
  16820. safeVariableNames: this.info.safeVariableNames,
  16821. sourcemapChain: this.sourcemapChain,
  16822. syntheticNamedExports: this.info.syntheticNamedExports,
  16823. transformDependencies: this.transformDependencies,
  16824. transformFiles: this.transformFiles
  16825. };
  16826. }
  16827. traceVariable(name, { importerForSideEffects, isExportAllSearch, searchedNamesAndModules, sideEffectModules, exportOrReexportModules } = EMPTY_OBJECT) {
  16828. const localVariable = this.scope.variables.get(name);
  16829. if (localVariable) {
  16830. return localVariable;
  16831. }
  16832. const importDescription = this.importDescriptions.get(name);
  16833. if (importDescription) {
  16834. const otherModule = importDescription.module;
  16835. if (otherModule instanceof Module && importDescription.name === '*') {
  16836. return otherModule.namespace;
  16837. }
  16838. const [declaration, options] = getVariableForExportNameRecursive(otherModule, importDescription.name, importerForSideEffects || this, isExportAllSearch, searchedNamesAndModules, [this.id], sideEffectModules, exportOrReexportModules);
  16839. if (!declaration) {
  16840. return this.error(logMissingExport(importDescription.name, this.id, otherModule.id, !!options?.missingButExportExists), importDescription.start);
  16841. }
  16842. return declaration;
  16843. }
  16844. return null;
  16845. }
  16846. updateOptions({ meta, moduleSideEffects, syntheticNamedExports }) {
  16847. if (moduleSideEffects != null) {
  16848. this.info.moduleSideEffects = moduleSideEffects;
  16849. }
  16850. if (syntheticNamedExports != null) {
  16851. this.info.syntheticNamedExports = syntheticNamedExports;
  16852. }
  16853. if (meta != null) {
  16854. Object.assign(this.info.meta, meta);
  16855. }
  16856. }
  16857. addDynamicImport(node) {
  16858. let argument = node.sourceAstNode;
  16859. if (argument.type === TemplateLiteral$1) {
  16860. if (argument.quasis.length === 1 &&
  16861. typeof argument.quasis[0].value.cooked === 'string') {
  16862. argument = argument.quasis[0].value.cooked;
  16863. }
  16864. }
  16865. else if (argument.type === Literal$1 &&
  16866. typeof argument.value === 'string') {
  16867. argument = argument.value;
  16868. }
  16869. this.dynamicImports.push({ argument, id: null, node });
  16870. }
  16871. assertUniqueExportName(name, nodeStart) {
  16872. if (this.exportDescriptions.has(name) || this.reexportDescriptions.has(name)) {
  16873. this.error(logDuplicateExportError(name), nodeStart);
  16874. }
  16875. }
  16876. addExport(node) {
  16877. if (node instanceof ExportDefaultDeclaration) {
  16878. // export default foo;
  16879. this.assertUniqueExportName('default', node.start);
  16880. this.exportDescriptions.set('default', {
  16881. identifier: node.variable.getAssignedVariableName(),
  16882. localName: 'default'
  16883. });
  16884. }
  16885. else if (node instanceof ExportAllDeclaration) {
  16886. const source = node.source.value;
  16887. this.addSource(source, node);
  16888. if (node.exported) {
  16889. // export * as name from './other'
  16890. const name = node.exported instanceof Literal ? node.exported.value : node.exported.name;
  16891. this.assertUniqueExportName(name, node.exported.start);
  16892. this.reexportDescriptions.set(name, {
  16893. localName: '*',
  16894. module: null, // filled in later,
  16895. source,
  16896. start: node.start
  16897. });
  16898. }
  16899. else {
  16900. // export * from './other'
  16901. this.exportAllSources.add(source);
  16902. }
  16903. }
  16904. else if (node.source instanceof Literal) {
  16905. // export { name } from './other'
  16906. const source = node.source.value;
  16907. this.addSource(source, node);
  16908. for (const { exported, local, start } of node.specifiers) {
  16909. const name = exported instanceof Literal ? exported.value : exported.name;
  16910. this.assertUniqueExportName(name, start);
  16911. this.reexportDescriptions.set(name, {
  16912. localName: local instanceof Literal ? local.value : local.name,
  16913. module: null, // filled in later,
  16914. source,
  16915. start
  16916. });
  16917. }
  16918. }
  16919. else if (node.declaration) {
  16920. const declaration = node.declaration;
  16921. if (declaration instanceof VariableDeclaration) {
  16922. // export var { foo, bar } = ...
  16923. // export var foo = 1, bar = 2;
  16924. for (const declarator of declaration.declarations) {
  16925. for (const localName of extractAssignedNames(declarator.id)) {
  16926. this.assertUniqueExportName(localName, declarator.id.start);
  16927. this.exportDescriptions.set(localName, { identifier: null, localName });
  16928. }
  16929. }
  16930. }
  16931. else {
  16932. // export function foo () {}
  16933. const localName = declaration.id.name;
  16934. this.assertUniqueExportName(localName, declaration.id.start);
  16935. this.exportDescriptions.set(localName, { identifier: null, localName });
  16936. }
  16937. }
  16938. else {
  16939. // export { foo, bar, baz }
  16940. for (const { local, exported } of node.specifiers) {
  16941. // except for reexports, local must be an Identifier
  16942. const localName = local.name;
  16943. const exportedName = exported instanceof Identifier ? exported.name : exported.value;
  16944. this.assertUniqueExportName(exportedName, exported.start);
  16945. this.exportDescriptions.set(exportedName, { identifier: null, localName });
  16946. }
  16947. }
  16948. }
  16949. addImport(node) {
  16950. const source = node.source.value;
  16951. this.addSource(source, node);
  16952. for (const specifier of node.specifiers) {
  16953. const localName = specifier.local.name;
  16954. if (this.scope.variables.has(localName) || this.importDescriptions.has(localName)) {
  16955. this.error(logRedeclarationError(localName), specifier.local.start);
  16956. }
  16957. const name = node.phase === 'source'
  16958. ? SOURCE_PHASE_IMPORT
  16959. : specifier instanceof ImportDefaultSpecifier
  16960. ? 'default'
  16961. : specifier instanceof ImportNamespaceSpecifier
  16962. ? '*'
  16963. : specifier.imported instanceof Identifier
  16964. ? specifier.imported.name
  16965. : specifier.imported.value;
  16966. this.importDescriptions.set(localName, {
  16967. module: null, // filled in later
  16968. name,
  16969. phase: node.phase === 'source' ? 'source' : 'instance',
  16970. source,
  16971. start: specifier.start
  16972. });
  16973. }
  16974. }
  16975. addImportSource(importSource) {
  16976. if (importSource && !this.sourcesWithAttributes.has(importSource)) {
  16977. this.sourcesWithAttributes.set(importSource, EMPTY_OBJECT);
  16978. }
  16979. }
  16980. addImportMeta(node) {
  16981. this.importMetas.push(node);
  16982. }
  16983. addLocationToLogProps(properties, pos) {
  16984. properties.id = this.id;
  16985. properties.pos = pos;
  16986. let code = this.info.code;
  16987. const location = locate(code, pos, { offsetLine: 1 });
  16988. if (location) {
  16989. let { column, line } = location;
  16990. try {
  16991. ({ column, line } = getOriginalLocation(this.sourcemapChain, { column, line }));
  16992. code = this.originalCode;
  16993. }
  16994. catch (error_) {
  16995. this.options.onLog(LOGLEVEL_WARN, logInvalidSourcemapForError(error_, this.id, column, line, pos));
  16996. }
  16997. augmentCodeLocation(properties, { column, line }, code, this.id);
  16998. }
  16999. }
  17000. addModulesToImportDescriptions(importDescription) {
  17001. for (const specifier of importDescription.values()) {
  17002. const { id } = this.resolvedIds[specifier.source];
  17003. specifier.module = this.graph.modulesById.get(id);
  17004. }
  17005. }
  17006. addRelevantSideEffectDependencies(relevantDependencies, necessaryDependencies, alwaysCheckedDependencies) {
  17007. const handledDependencies = new Set();
  17008. const addSideEffectDependencies = (possibleDependencies) => {
  17009. for (const dependency of possibleDependencies) {
  17010. if (handledDependencies.has(dependency)) {
  17011. continue;
  17012. }
  17013. handledDependencies.add(dependency);
  17014. if (necessaryDependencies.has(dependency)) {
  17015. relevantDependencies.add(dependency);
  17016. continue;
  17017. }
  17018. if (!(dependency.info.moduleSideEffects || alwaysCheckedDependencies.has(dependency))) {
  17019. continue;
  17020. }
  17021. if (dependency instanceof ExternalModule || dependency.hasEffects()) {
  17022. relevantDependencies.add(dependency);
  17023. continue;
  17024. }
  17025. addSideEffectDependencies(dependency.dependencies);
  17026. }
  17027. };
  17028. addSideEffectDependencies(this.dependencies);
  17029. addSideEffectDependencies(alwaysCheckedDependencies);
  17030. }
  17031. addSource(source, declaration) {
  17032. const parsedAttributes = getAttributesFromImportExportDeclaration(declaration.attributes);
  17033. const existingAttributes = this.sourcesWithAttributes.get(source);
  17034. if (existingAttributes) {
  17035. if (doAttributesDiffer(existingAttributes, parsedAttributes)) {
  17036. this.log(LOGLEVEL_WARN, logInconsistentImportAttributes(existingAttributes, parsedAttributes, source, this.id), declaration.start);
  17037. }
  17038. }
  17039. else {
  17040. this.sourcesWithAttributes.set(source, parsedAttributes);
  17041. }
  17042. if (declaration.phase === 'source') {
  17043. this.sourcePhaseSources.add(source);
  17044. }
  17045. }
  17046. getImportedJsxFactoryVariable(baseName, nodeStart, importSource) {
  17047. const { id } = this.resolvedIds[importSource];
  17048. const module = this.graph.modulesById.get(id);
  17049. const [variable] = module.getVariableForExportName(baseName, { importChain: [this.id] });
  17050. if (!variable) {
  17051. return this.error(logMissingJsxExport(baseName, id, this.id), nodeStart);
  17052. }
  17053. return variable;
  17054. }
  17055. getVariableFromNamespaceReexports(name, importerForSideEffects, searchedNamesAndModules, importChain) {
  17056. let foundSyntheticDeclaration = null;
  17057. const foundInternalDeclarations = new Map();
  17058. const foundExternalDeclarations = new Set();
  17059. const sideEffectModules = new Set();
  17060. const exportOrReexportModules = new Set();
  17061. for (const module of this.exportAllModules) {
  17062. // Synthetic namespaces should not hide "regular" exports of the same name
  17063. if (module.info.syntheticNamedExports === name) {
  17064. continue;
  17065. }
  17066. const [variable, options] = getVariableForExportNameRecursive(module, name, importerForSideEffects, true,
  17067. // We are creating a copy to handle the case where the same binding is
  17068. // imported through different namespace reexports gracefully
  17069. copyNameToModulesMap(searchedNamesAndModules), importChain, sideEffectModules, exportOrReexportModules);
  17070. if (module instanceof ExternalModule || options?.indirectExternal) {
  17071. foundExternalDeclarations.add(variable);
  17072. }
  17073. else if (variable instanceof SyntheticNamedExportVariable) {
  17074. if (!foundSyntheticDeclaration) {
  17075. foundSyntheticDeclaration = variable;
  17076. }
  17077. }
  17078. else if (variable) {
  17079. foundInternalDeclarations.set(variable, module);
  17080. }
  17081. }
  17082. if (foundInternalDeclarations.size > 0) {
  17083. const foundDeclarationList = [...foundInternalDeclarations];
  17084. const usedDeclaration = foundDeclarationList[0][0];
  17085. if (foundDeclarationList.length === 1) {
  17086. return [usedDeclaration, { exportOrReexportModules, sideEffectModules }];
  17087. }
  17088. this.options.onLog(LOGLEVEL_WARN, logNamespaceConflict(name, this.id, foundDeclarationList.map(([, module]) => module.id)));
  17089. // TODO we are pretending it was not found while it should behave like "undefined"
  17090. return [null];
  17091. }
  17092. if (foundExternalDeclarations.size > 0) {
  17093. const foundDeclarationList = [...foundExternalDeclarations];
  17094. const usedDeclaration = foundDeclarationList[0];
  17095. if (foundDeclarationList.length > 1) {
  17096. this.options.onLog(LOGLEVEL_WARN, logAmbiguousExternalNamespaces(name, this.id, usedDeclaration.module.id, foundDeclarationList.map(declaration => declaration.module.id)));
  17097. }
  17098. return [
  17099. usedDeclaration,
  17100. { exportOrReexportModules, indirectExternal: true, sideEffectModules }
  17101. ];
  17102. }
  17103. if (foundSyntheticDeclaration) {
  17104. return [foundSyntheticDeclaration, { exportOrReexportModules, sideEffectModules }];
  17105. }
  17106. return [null];
  17107. }
  17108. includeAndGetAdditionalMergedNamespaces() {
  17109. const externalNamespaces = new Set();
  17110. const syntheticNamespaces = new Set();
  17111. for (const module of [this, ...this.exportAllModules]) {
  17112. if (module instanceof ExternalModule) {
  17113. const [externalVariable] = module.getVariableForExportName('*', {
  17114. importChain: [this.id]
  17115. });
  17116. externalVariable.includePath(UNKNOWN_PATH, createInclusionContext());
  17117. this.includedImports.add(externalVariable);
  17118. externalNamespaces.add(externalVariable);
  17119. }
  17120. else if (module.info.syntheticNamedExports) {
  17121. const syntheticNamespace = module.getSyntheticNamespace();
  17122. syntheticNamespace.includePath(UNKNOWN_PATH, createInclusionContext());
  17123. this.includedImports.add(syntheticNamespace);
  17124. syntheticNamespaces.add(syntheticNamespace);
  17125. }
  17126. }
  17127. return [...syntheticNamespaces, ...externalNamespaces];
  17128. }
  17129. includeDynamicImport(node) {
  17130. const { resolution } = node;
  17131. if (resolution instanceof Module) {
  17132. if (!resolution.includedDynamicImporters.includes(this)) {
  17133. resolution.includedDynamicImporters.push(this);
  17134. // If a module has a top-level await, removing this entry can create
  17135. // deadlocks.
  17136. if (this.astContext.usesTopLevelAwait) {
  17137. resolution.includedTopLevelAwaitingDynamicImporters.add(this);
  17138. }
  17139. }
  17140. }
  17141. }
  17142. includeVariable(variable, path, context) {
  17143. const { included, module: variableModule } = variable;
  17144. variable.includePath(path, context);
  17145. if (included) {
  17146. if (variableModule instanceof Module && variableModule !== this) {
  17147. getAndExtendSideEffectModules(variable, this);
  17148. }
  17149. return;
  17150. }
  17151. this.graph.needsTreeshakingPass = true;
  17152. if (!(variableModule instanceof Module)) {
  17153. return;
  17154. }
  17155. variableModule.includeModuleInExecution();
  17156. if (variableModule !== this) {
  17157. const sideEffectModules = getAndExtendSideEffectModules(variable, this);
  17158. for (const module of sideEffectModules) {
  17159. module.includeModuleInExecution();
  17160. }
  17161. }
  17162. }
  17163. includeVariableInModule(variable, path, context) {
  17164. this.includeVariable(variable, path, context);
  17165. const variableModule = variable.module;
  17166. if (variableModule && variableModule !== this) {
  17167. this.includedImports.add(variable);
  17168. }
  17169. }
  17170. shimMissingExport(name) {
  17171. this.options.onLog(LOGLEVEL_WARN, logShimmedExport(this.id, name));
  17172. this.exportDescriptions.set(name, MISSING_EXPORT_SHIM_DESCRIPTION);
  17173. }
  17174. tryParse() {
  17175. try {
  17176. return parseAst(this.info.code, { jsx: this.options.jsx !== false });
  17177. }
  17178. catch (error_) {
  17179. return this.error(logModuleParseError(error_, this.id), error_.pos);
  17180. }
  17181. }
  17182. }
  17183. // if there is a cyclic import in the reexport chain, we should not
  17184. // import from the original module but from the cyclic module to not
  17185. // mess up execution order.
  17186. function setAlternativeExporterIfCyclic(variable, importer, reexporter) {
  17187. if (variable.module instanceof Module && variable.module !== reexporter) {
  17188. const exporterCycles = variable.module.cycles;
  17189. if (exporterCycles.size > 0) {
  17190. const importerCycles = reexporter.cycles;
  17191. for (const cycleSymbol of importerCycles) {
  17192. if (exporterCycles.has(cycleSymbol)) {
  17193. importer.alternativeReexportModules.set(variable, reexporter);
  17194. break;
  17195. }
  17196. }
  17197. }
  17198. }
  17199. }
  17200. const copyNameToModulesMap = (searchedNamesAndModules) => searchedNamesAndModules &&
  17201. new Map(Array.from(searchedNamesAndModules, ([name, modules]) => [name, new Set(modules)]));
  17202. const sortExportedVariables = ([a], [b]) => a < b ? -1 : a > b ? 1 : 0;
  17203. const concatSeparator = (out, next) => (next ? `${out}\n${next}` : out);
  17204. const concatDblSeparator = (out, next) => (next ? `${out}\n\n${next}` : out);
  17205. async function createAddons(options, outputPluginDriver, chunk) {
  17206. try {
  17207. let [banner, footer, intro, outro] = await Promise.all([
  17208. outputPluginDriver.hookReduceValue('banner', options.banner(chunk), [chunk], concatSeparator),
  17209. outputPluginDriver.hookReduceValue('footer', options.footer(chunk), [chunk], concatSeparator),
  17210. outputPluginDriver.hookReduceValue('intro', options.intro(chunk), [chunk], concatDblSeparator),
  17211. outputPluginDriver.hookReduceValue('outro', options.outro(chunk), [chunk], concatDblSeparator)
  17212. ]);
  17213. if (intro)
  17214. intro += '\n\n';
  17215. if (outro)
  17216. outro = `\n\n${outro}`;
  17217. if (banner)
  17218. banner += '\n';
  17219. if (footer)
  17220. footer = '\n' + footer;
  17221. return { banner, footer, intro, outro };
  17222. }
  17223. catch (error_) {
  17224. return error(logAddonNotGenerated(error_.message, error_.hook, error_.plugin));
  17225. }
  17226. }
  17227. const DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT = {
  17228. amd: deconflictImportsOther,
  17229. cjs: deconflictImportsOther,
  17230. es: deconflictImportsEsmOrSystem,
  17231. iife: deconflictImportsOther,
  17232. system: deconflictImportsEsmOrSystem,
  17233. umd: deconflictImportsOther
  17234. };
  17235. function deconflictChunk(modules, dependenciesToBeDeconflicted, imports, usedNames, format, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports, exportNamesByVariable, accessedGlobalsByScope, includedNamespaces) {
  17236. const reversedModules = [...modules].reverse();
  17237. for (const module of reversedModules) {
  17238. module.scope.addUsedOutsideNames(usedNames, accessedGlobalsByScope);
  17239. }
  17240. deconflictTopLevelVariables(usedNames, reversedModules, includedNamespaces);
  17241. DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT[format](usedNames, imports, dependenciesToBeDeconflicted, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports);
  17242. for (const module of reversedModules) {
  17243. module.scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
  17244. }
  17245. }
  17246. function deconflictImportsEsmOrSystem(usedNames, imports, dependenciesToBeDeconflicted, _interop, preserveModules, _externalLiveBindings, chunkByModule, externalChunkByModule, syntheticExports) {
  17247. // This is needed for namespace reexports
  17248. for (const dependency of dependenciesToBeDeconflicted.dependencies) {
  17249. if (preserveModules || dependency instanceof ExternalChunk) {
  17250. dependency.variableName = getSafeName(dependency.suggestedVariableName, usedNames, null);
  17251. }
  17252. }
  17253. for (const variable of imports) {
  17254. const module = variable.module;
  17255. const name = variable.name;
  17256. if (variable.isNamespace && (preserveModules || module instanceof ExternalModule)) {
  17257. variable.setRenderNames(null, (module instanceof ExternalModule
  17258. ? externalChunkByModule.get(module)
  17259. : chunkByModule.get(module)).variableName);
  17260. }
  17261. else if (module instanceof ExternalModule && variable.isSourcePhase) {
  17262. variable.setRenderNames(null, getSafeName(module.suggestedVariableName + '__source', usedNames, variable.forbiddenNames));
  17263. }
  17264. else if (module instanceof ExternalModule && name === 'default') {
  17265. variable.setRenderNames(null, getSafeName([...module.exportedVariables].some(([exportedVariable, exportedName]) => exportedName === '*' && exportedVariable.included)
  17266. ? module.suggestedVariableName + '__default'
  17267. : module.suggestedVariableName, usedNames, variable.forbiddenNames));
  17268. }
  17269. else {
  17270. variable.setRenderNames(null, getSafeName(makeLegal(name), usedNames, variable.forbiddenNames));
  17271. }
  17272. }
  17273. for (const variable of syntheticExports) {
  17274. variable.setRenderNames(null, getSafeName(variable.name, usedNames, variable.forbiddenNames));
  17275. }
  17276. }
  17277. function deconflictImportsOther(usedNames, imports, { deconflictedDefault, deconflictedNamespace, dependencies }, interop, preserveModules, externalLiveBindings, chunkByModule, externalChunkByModule) {
  17278. for (const chunk of dependencies) {
  17279. chunk.variableName = getSafeName(chunk.suggestedVariableName, usedNames, null);
  17280. }
  17281. for (const chunk of deconflictedNamespace) {
  17282. chunk.namespaceVariableName = getSafeName(`${chunk.suggestedVariableName}__namespace`, usedNames, null);
  17283. }
  17284. for (const externalModule of deconflictedDefault) {
  17285. externalModule.defaultVariableName =
  17286. deconflictedNamespace.has(externalModule) &&
  17287. canDefaultBeTakenFromNamespace(interop(externalModule.id), externalLiveBindings)
  17288. ? externalModule.namespaceVariableName
  17289. : getSafeName(`${externalModule.suggestedVariableName}__default`, usedNames, null);
  17290. }
  17291. for (const variable of imports) {
  17292. const module = variable.module;
  17293. if (module instanceof ExternalModule) {
  17294. const chunk = externalChunkByModule.get(module);
  17295. const name = variable.name;
  17296. if (name === 'default') {
  17297. const moduleInterop = interop(module.id);
  17298. const variableName = defaultInteropHelpersByInteropType[moduleInterop]
  17299. ? chunk.defaultVariableName
  17300. : chunk.variableName;
  17301. if (isDefaultAProperty(moduleInterop, externalLiveBindings)) {
  17302. variable.setRenderNames(variableName, 'default');
  17303. }
  17304. else {
  17305. variable.setRenderNames(null, variableName);
  17306. }
  17307. }
  17308. else if (name === '*') {
  17309. variable.setRenderNames(null, namespaceInteropHelpersByInteropType[interop(module.id)]
  17310. ? chunk.namespaceVariableName
  17311. : chunk.variableName);
  17312. }
  17313. else {
  17314. // if the second parameter is `null`, it uses its "name" for the property name
  17315. variable.setRenderNames(chunk.variableName, null);
  17316. }
  17317. }
  17318. else {
  17319. const chunk = chunkByModule.get(module);
  17320. if (preserveModules && variable.isNamespace) {
  17321. variable.setRenderNames(null, chunk.exportMode === 'default' ? chunk.namespaceVariableName : chunk.variableName);
  17322. }
  17323. else if (chunk.exportMode === 'default') {
  17324. variable.setRenderNames(null, chunk.variableName);
  17325. }
  17326. else {
  17327. variable.setRenderNames(chunk.variableName, chunk.getVariableExportName(variable));
  17328. }
  17329. }
  17330. }
  17331. }
  17332. function deconflictTopLevelVariables(usedNames, modules, includedNamespaces) {
  17333. for (const module of modules) {
  17334. module.info.safeVariableNames ||= {};
  17335. for (const variable of module.scope.variables.values()) {
  17336. if (variable.included &&
  17337. // this will only happen for exports in some formats
  17338. !(variable.renderBaseName ||
  17339. (variable instanceof ExportDefaultVariable && variable.getOriginalVariable() !== variable))) {
  17340. // We need to make sure that variables that corresponding to object
  17341. // prototype methods are not accidentally matched.
  17342. const cachedSafeVariableName = Object.getOwnPropertyDescriptor(module.info.safeVariableNames, variable.name)?.value;
  17343. if (cachedSafeVariableName && !usedNames.has(cachedSafeVariableName)) {
  17344. usedNames.add(cachedSafeVariableName);
  17345. variable.setRenderNames(null, cachedSafeVariableName);
  17346. continue;
  17347. }
  17348. variable.setRenderNames(null, getSafeName(variable.name, usedNames, variable.forbiddenNames));
  17349. module.info.safeVariableNames[variable.name] = variable.renderName;
  17350. }
  17351. }
  17352. if (includedNamespaces.has(module)) {
  17353. const namespace = module.namespace;
  17354. namespace.setRenderNames(null, getSafeName(namespace.name, usedNames, namespace.forbiddenNames));
  17355. }
  17356. }
  17357. }
  17358. function assignExportsToMangledNames(exports$1, exportsByName, exportNamesByVariable) {
  17359. let nameIndex = 0;
  17360. for (const variable of exports$1) {
  17361. let [exportName] = variable.name;
  17362. if (exportsByName.has(exportName)) {
  17363. do {
  17364. exportName = toBase64(++nameIndex);
  17365. // skip past leading number identifiers
  17366. if (exportName.charCodeAt(0) === 49 /* '1' */) {
  17367. nameIndex += 9 * 64 ** (exportName.length - 1);
  17368. exportName = toBase64(nameIndex);
  17369. }
  17370. } while (RESERVED_NAMES.has(exportName) || exportsByName.has(exportName));
  17371. }
  17372. exportsByName.set(exportName, variable);
  17373. exportNamesByVariable.set(variable, [exportName]);
  17374. }
  17375. }
  17376. function assignExportsToNames(exports$1, exportsByName, exportNamesByVariable) {
  17377. for (const variable of exports$1) {
  17378. let nameIndex = 0;
  17379. let exportName = variable.name;
  17380. while (exportsByName.has(exportName)) {
  17381. exportName = variable.name + '$' + ++nameIndex;
  17382. }
  17383. exportsByName.set(exportName, variable);
  17384. exportNamesByVariable.set(variable, [exportName]);
  17385. }
  17386. }
  17387. function getExportMode(chunk, { exports: exportMode, name, format }, facadeModuleId, log) {
  17388. const exportKeys = chunk.getExportNames();
  17389. if (exportMode === 'default') {
  17390. if (exportKeys.length !== 1 || exportKeys[0] !== 'default') {
  17391. return error(logIncompatibleExportOptionValue('default', exportKeys, facadeModuleId));
  17392. }
  17393. }
  17394. else if (exportMode === 'none' && exportKeys.length > 0) {
  17395. return error(logIncompatibleExportOptionValue('none', exportKeys, facadeModuleId));
  17396. }
  17397. if (exportMode === 'auto') {
  17398. if (exportKeys.length === 0) {
  17399. exportMode = 'none';
  17400. }
  17401. else if (exportKeys.length === 1 && exportKeys[0] === 'default') {
  17402. exportMode = 'default';
  17403. }
  17404. else {
  17405. if (format !== 'es' && format !== 'system' && exportKeys.includes('default')) {
  17406. log(LOGLEVEL_WARN, logMixedExport(facadeModuleId, name));
  17407. }
  17408. exportMode = 'named';
  17409. }
  17410. }
  17411. return exportMode;
  17412. }
  17413. function guessIndentString(code) {
  17414. const lines = code.split('\n');
  17415. const tabbed = lines.filter(line => /^\t+/.test(line));
  17416. const spaced = lines.filter(line => /^ {2,}/.test(line));
  17417. if (tabbed.length === 0 && spaced.length === 0) {
  17418. return null;
  17419. }
  17420. // More lines tabbed than spaced? Assume tabs, and
  17421. // default to tabs in the case of a tie (or nothing
  17422. // to go on)
  17423. if (tabbed.length >= spaced.length) {
  17424. return '\t';
  17425. }
  17426. // Otherwise, we need to guess the multiple
  17427. const min = spaced.reduce((previous, current) => {
  17428. const numberSpaces = /^ +/.exec(current)[0].length;
  17429. return Math.min(numberSpaces, previous);
  17430. }, Infinity);
  17431. return ' '.repeat(min);
  17432. }
  17433. function getIndentString(modules, options) {
  17434. if (options.indent !== true)
  17435. return options.indent;
  17436. for (const module of modules) {
  17437. const indent = guessIndentString(module.originalCode);
  17438. if (indent !== null)
  17439. return indent;
  17440. }
  17441. return '\t';
  17442. }
  17443. function getStaticDependencies(chunk, orderedModules, chunkByModule, externalChunkByModule) {
  17444. const staticDependencyBlocks = [];
  17445. const handledDependencies = new Set();
  17446. for (let modulePos = orderedModules.length - 1; modulePos >= 0; modulePos--) {
  17447. const module = orderedModules[modulePos];
  17448. if (!handledDependencies.has(module)) {
  17449. const staticDependencies = [];
  17450. addStaticDependencies(module, staticDependencies, handledDependencies, chunk, chunkByModule, externalChunkByModule);
  17451. staticDependencyBlocks.unshift(staticDependencies);
  17452. }
  17453. }
  17454. const dependencies = new Set();
  17455. for (const block of staticDependencyBlocks) {
  17456. for (const dependency of block) {
  17457. dependencies.add(dependency);
  17458. }
  17459. }
  17460. return dependencies;
  17461. }
  17462. function addStaticDependencies(module, staticDependencies, handledModules, chunk, chunkByModule, externalChunkByModule) {
  17463. const dependencies = module.getDependenciesToBeIncluded();
  17464. for (const dependency of dependencies) {
  17465. if (dependency instanceof ExternalModule) {
  17466. staticDependencies.push(externalChunkByModule.get(dependency));
  17467. continue;
  17468. }
  17469. const dependencyChunk = chunkByModule.get(dependency);
  17470. if (dependencyChunk !== chunk) {
  17471. staticDependencies.push(dependencyChunk);
  17472. continue;
  17473. }
  17474. if (!handledModules.has(dependency)) {
  17475. handledModules.add(dependency);
  17476. addStaticDependencies(dependency, staticDependencies, handledModules, chunk, chunkByModule, externalChunkByModule);
  17477. }
  17478. }
  17479. }
  17480. // Four random characters from the private use area to minimize risk of
  17481. // conflicts
  17482. const hashPlaceholderLeft = '!~{';
  17483. const hashPlaceholderRight = '}~';
  17484. const hashPlaceholderOverhead = hashPlaceholderLeft.length + hashPlaceholderRight.length;
  17485. // This is the size of a 128-bits xxhash with base64url encoding
  17486. const MAX_HASH_SIZE = 21;
  17487. const DEFAULT_HASH_SIZE = 8;
  17488. const getHashPlaceholderGenerator = () => {
  17489. let nextIndex = 0;
  17490. return (optionName, hashSize) => {
  17491. if (hashSize > MAX_HASH_SIZE) {
  17492. return error(logFailedValidation(`Hashes cannot be longer than ${MAX_HASH_SIZE} characters, received ${hashSize}. Check the "${optionName}" option.`));
  17493. }
  17494. const placeholder = `${hashPlaceholderLeft}${toBase64(++nextIndex).padStart(hashSize - hashPlaceholderOverhead, '0')}${hashPlaceholderRight}`;
  17495. if (placeholder.length > hashSize) {
  17496. 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.`));
  17497. }
  17498. return placeholder;
  17499. };
  17500. };
  17501. const REPLACER_REGEX = new RegExp(`${hashPlaceholderLeft}[0-9a-zA-Z_$]{1,${MAX_HASH_SIZE - hashPlaceholderOverhead}}${hashPlaceholderRight}`, 'g');
  17502. const replacePlaceholders = (code, hashesByPlaceholder) => code.replace(REPLACER_REGEX, placeholder => hashesByPlaceholder.get(placeholder) || placeholder);
  17503. const replaceSinglePlaceholder = (code, placeholder, value) => code.replace(REPLACER_REGEX, match => (match === placeholder ? value : match));
  17504. const replacePlaceholdersWithDefaultAndGetContainedPlaceholders = (code, placeholders) => {
  17505. const containedPlaceholders = new Set();
  17506. const transformedCode = code.replace(REPLACER_REGEX, placeholder => {
  17507. if (placeholders.has(placeholder)) {
  17508. containedPlaceholders.add(placeholder);
  17509. return `${hashPlaceholderLeft}${'0'.repeat(placeholder.length - hashPlaceholderOverhead)}${hashPlaceholderRight}`;
  17510. }
  17511. return placeholder;
  17512. });
  17513. return { containedPlaceholders, transformedCode };
  17514. };
  17515. const lowercaseBundleKeys = Symbol('bundleKeys');
  17516. const FILE_PLACEHOLDER = {
  17517. type: 'placeholder'
  17518. };
  17519. const getOutputBundle = (outputBundleBase) => {
  17520. const reservedLowercaseBundleKeys = new Set();
  17521. return new Proxy(outputBundleBase, {
  17522. deleteProperty(target, key) {
  17523. if (typeof key === 'string') {
  17524. reservedLowercaseBundleKeys.delete(key.toLowerCase());
  17525. }
  17526. return Reflect.deleteProperty(target, key);
  17527. },
  17528. get(target, key) {
  17529. if (key === lowercaseBundleKeys) {
  17530. return reservedLowercaseBundleKeys;
  17531. }
  17532. return Reflect.get(target, key);
  17533. },
  17534. set(target, key, value) {
  17535. if (typeof key === 'string') {
  17536. reservedLowercaseBundleKeys.add(key.toLowerCase());
  17537. }
  17538. return Reflect.set(target, key, value);
  17539. }
  17540. });
  17541. };
  17542. const removeUnreferencedAssets = (outputBundle) => {
  17543. const unreferencedAssets = new Set();
  17544. const bundleEntries = Object.values(outputBundle);
  17545. for (const asset of bundleEntries) {
  17546. if (asset.type === 'asset' && asset.needsCodeReference) {
  17547. unreferencedAssets.add(asset.fileName);
  17548. }
  17549. }
  17550. for (const chunk of bundleEntries) {
  17551. if (chunk.type === 'chunk') {
  17552. for (const referencedFile of chunk.referencedFiles) {
  17553. if (unreferencedAssets.has(referencedFile)) {
  17554. unreferencedAssets.delete(referencedFile);
  17555. }
  17556. }
  17557. }
  17558. }
  17559. for (const file of unreferencedAssets) {
  17560. delete outputBundle[file];
  17561. }
  17562. };
  17563. function renderNamePattern(pattern, patternName, replacements) {
  17564. if (isPathFragment(pattern))
  17565. 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.`));
  17566. return pattern.replace(/\[(\w+)(:\d+)?]/g, (_match, type, size) => {
  17567. if (!replacements.hasOwnProperty(type) || (size && type !== 'hash')) {
  17568. return error(logFailedValidation(`"[${type}${size || ''}]" is not a valid placeholder in the "${patternName}" pattern.`));
  17569. }
  17570. const replacement = replacements[type](size && Number.parseInt(size.slice(1)));
  17571. if (isPathFragment(replacement))
  17572. return error(logFailedValidation(`Invalid substitution "${replacement}" for placeholder "[${type}]" in "${patternName}" pattern, can be neither absolute nor relative path.`));
  17573. return replacement;
  17574. });
  17575. }
  17576. function makeUnique(name, { [lowercaseBundleKeys]: reservedLowercaseBundleKeys }) {
  17577. if (!reservedLowercaseBundleKeys.has(name.toLowerCase()))
  17578. return name;
  17579. const extension = extname(name);
  17580. name = name.slice(0, Math.max(0, name.length - extension.length));
  17581. let uniqueName, uniqueIndex = 1;
  17582. while (reservedLowercaseBundleKeys.has((uniqueName = name + ++uniqueIndex + extension).toLowerCase()))
  17583. ;
  17584. return uniqueName;
  17585. }
  17586. const RESERVED_USED_NAMES = [
  17587. 'Object',
  17588. 'Promise',
  17589. 'module',
  17590. 'exports',
  17591. 'require',
  17592. '__filename',
  17593. '__dirname',
  17594. ...HELPER_NAMES
  17595. ];
  17596. const NON_ASSET_EXTENSIONS = new Set([
  17597. '.js',
  17598. '.jsx',
  17599. '.ts',
  17600. '.tsx',
  17601. '.mjs',
  17602. '.mts',
  17603. '.cjs',
  17604. '.cts'
  17605. ]);
  17606. function getGlobalName(chunk, globals, hasExports, log) {
  17607. const globalName = typeof globals === 'function' ? globals(chunk.id) : globals[chunk.id];
  17608. if (globalName) {
  17609. return globalName;
  17610. }
  17611. if (hasExports) {
  17612. log(LOGLEVEL_WARN, logMissingGlobalName(chunk.id, chunk.variableName));
  17613. return chunk.variableName;
  17614. }
  17615. }
  17616. class Chunk {
  17617. constructor(orderedModules, inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, manualChunkAlias, getPlaceholder, bundle, inputBase, snippets) {
  17618. this.orderedModules = orderedModules;
  17619. this.inputOptions = inputOptions;
  17620. this.outputOptions = outputOptions;
  17621. this.unsetOptions = unsetOptions;
  17622. this.pluginDriver = pluginDriver;
  17623. this.modulesById = modulesById;
  17624. this.chunkByModule = chunkByModule;
  17625. this.externalChunkByModule = externalChunkByModule;
  17626. this.facadeChunkByModule = facadeChunkByModule;
  17627. this.includedNamespaces = includedNamespaces;
  17628. this.manualChunkAlias = manualChunkAlias;
  17629. this.getPlaceholder = getPlaceholder;
  17630. this.bundle = bundle;
  17631. this.inputBase = inputBase;
  17632. this.snippets = snippets;
  17633. this.dependencies = new Set();
  17634. this.entryModules = [];
  17635. this.exportMode = 'named';
  17636. this.facadeModule = null;
  17637. this.namespaceVariableName = '';
  17638. this.variableName = '';
  17639. this.isManualChunk = false;
  17640. this.accessedGlobalsByScope = new Map();
  17641. this.dynamicEntryModules = [];
  17642. this.dynamicName = null;
  17643. this.exportNamesByVariable = new Map();
  17644. this.exports = new Set();
  17645. this.exportsByName = new Map();
  17646. this.fileName = null;
  17647. this.implicitEntryModules = [];
  17648. this.implicitlyLoadedBefore = new Set();
  17649. this.imports = new Set();
  17650. this.includedDynamicImports = null;
  17651. this.includedReexportsByModule = new Map();
  17652. // This may be updated in the constructor
  17653. this.isEmpty = true;
  17654. this.name = null;
  17655. this.needsExportsShim = false;
  17656. this.preRenderedChunkInfo = null;
  17657. this.preliminaryFileName = null;
  17658. this.preliminarySourcemapFileName = null;
  17659. this.renderedChunkInfo = null;
  17660. this.renderedDependencies = null;
  17661. this.renderedModules = Object.create(null);
  17662. this.sortedExportNames = null;
  17663. this.strictFacade = false;
  17664. /** Modules with 'allow-extension' that should have preserved exports within the chunk */
  17665. this.allowExtensionModules = new Set();
  17666. this.execIndex = orderedModules.length > 0 ? orderedModules[0].execIndex : Infinity;
  17667. const chunkModules = new Set(orderedModules);
  17668. for (const module of orderedModules) {
  17669. chunkByModule.set(module, this);
  17670. if (module.namespace.included && !outputOptions.preserveModules) {
  17671. includedNamespaces.add(module);
  17672. }
  17673. if (this.isEmpty && module.isIncluded()) {
  17674. this.isEmpty = false;
  17675. }
  17676. if (module.info.isEntry || outputOptions.preserveModules) {
  17677. this.entryModules.push(module);
  17678. }
  17679. for (const importer of module.includedDynamicImporters) {
  17680. if (!chunkModules.has(importer)) {
  17681. this.dynamicEntryModules.push(module);
  17682. // Modules with synthetic exports need an artificial namespace for dynamic imports
  17683. if (module.info.syntheticNamedExports) {
  17684. includedNamespaces.add(module);
  17685. this.exports.add(module.namespace);
  17686. }
  17687. // This only needs to run once
  17688. break;
  17689. }
  17690. }
  17691. if (module.implicitlyLoadedAfter.size > 0) {
  17692. this.implicitEntryModules.push(module);
  17693. }
  17694. }
  17695. this.suggestedVariableName = makeLegal(this.generateVariableName());
  17696. this.isManualChunk = manualChunkAlias !== null;
  17697. }
  17698. static generateFacade(inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, facadedModule, facadeName, getPlaceholder, bundle, inputBase, snippets) {
  17699. const chunk = new Chunk([], inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, externalChunkByModule, facadeChunkByModule, includedNamespaces, null, getPlaceholder, bundle, inputBase, snippets);
  17700. chunk.assignFacadeName(facadeName, facadedModule);
  17701. if (!facadeChunkByModule.has(facadedModule)) {
  17702. facadeChunkByModule.set(facadedModule, chunk);
  17703. }
  17704. for (const dependency of facadedModule.getDependenciesToBeIncluded()) {
  17705. chunk.dependencies.add(dependency instanceof Module
  17706. ? chunkByModule.get(dependency)
  17707. : externalChunkByModule.get(dependency));
  17708. }
  17709. if (!chunk.dependencies.has(chunkByModule.get(facadedModule)) &&
  17710. facadedModule.info.moduleSideEffects &&
  17711. facadedModule.hasEffects()) {
  17712. chunk.dependencies.add(chunkByModule.get(facadedModule));
  17713. }
  17714. chunk.ensureReexportsAreAvailableForModule(facadedModule);
  17715. chunk.facadeModule = facadedModule;
  17716. chunk.strictFacade = true;
  17717. return chunk;
  17718. }
  17719. canModuleBeFacade(module, exposedVariables) {
  17720. const moduleExportNamesByVariable = module.getExportNamesByVariable();
  17721. // All exports of this chunk need to be exposed by the candidate module
  17722. for (const exposedVariable of this.exports) {
  17723. if (!moduleExportNamesByVariable.has(exposedVariable)) {
  17724. return false;
  17725. }
  17726. }
  17727. // Additionally, we need to expose namespaces of dynamic entries that are not the facade module and exports from other entry modules
  17728. for (const exposedVariable of exposedVariables) {
  17729. if (!(exposedVariable.module === module ||
  17730. moduleExportNamesByVariable.has(exposedVariable) ||
  17731. (exposedVariable instanceof SyntheticNamedExportVariable &&
  17732. moduleExportNamesByVariable.has(exposedVariable.getBaseVariable())))) {
  17733. return false;
  17734. }
  17735. }
  17736. return true;
  17737. }
  17738. finalizeChunk(code, map, sourcemapFileName, hashesByPlaceholder) {
  17739. const renderedChunkInfo = this.getRenderedChunkInfo();
  17740. const finalize = (code) => replacePlaceholders(code, hashesByPlaceholder);
  17741. const preliminaryFileName = renderedChunkInfo.fileName;
  17742. const fileName = (this.fileName = finalize(preliminaryFileName));
  17743. return {
  17744. ...renderedChunkInfo,
  17745. code,
  17746. dynamicImports: renderedChunkInfo.dynamicImports.map(finalize),
  17747. fileName,
  17748. implicitlyLoadedBefore: renderedChunkInfo.implicitlyLoadedBefore.map(finalize),
  17749. importedBindings: Object.fromEntries(Object.entries(renderedChunkInfo.importedBindings).map(([fileName, bindings]) => [
  17750. finalize(fileName),
  17751. bindings
  17752. ])),
  17753. imports: renderedChunkInfo.imports.map(finalize),
  17754. map,
  17755. preliminaryFileName,
  17756. referencedFiles: renderedChunkInfo.referencedFiles.map(finalize),
  17757. sourcemapFileName
  17758. };
  17759. }
  17760. generateExports() {
  17761. this.sortedExportNames = null;
  17762. const remainingExports = new Set(this.exports);
  17763. if (this.facadeModule !== null &&
  17764. (this.facadeModule.preserveSignature !== false || this.strictFacade)) {
  17765. const exportNamesByVariable = this.facadeModule.getExportNamesByVariable();
  17766. for (const [variable, exportNames] of exportNamesByVariable) {
  17767. this.exportNamesByVariable.set(variable, [...exportNames]);
  17768. for (const exportName of exportNames) {
  17769. this.exportsByName.set(exportName, variable);
  17770. }
  17771. remainingExports.delete(variable);
  17772. }
  17773. }
  17774. for (const module of this.allowExtensionModules) {
  17775. const exportNamesByVariable = module.getExportNamesByVariable();
  17776. for (const [variable, exportNames] of exportNamesByVariable) {
  17777. this.exportNamesByVariable.set(variable, [...exportNames]);
  17778. for (const exportName of exportNames) {
  17779. this.exportsByName.set(exportName, variable);
  17780. }
  17781. remainingExports.delete(variable);
  17782. }
  17783. }
  17784. if (this.outputOptions.minifyInternalExports) {
  17785. assignExportsToMangledNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  17786. }
  17787. else {
  17788. assignExportsToNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
  17789. }
  17790. if (this.outputOptions.preserveModules || (this.facadeModule && this.facadeModule.info.isEntry))
  17791. this.exportMode = getExportMode(this, this.outputOptions, this.facadeModule.id, this.inputOptions.onLog);
  17792. }
  17793. generateFacades() {
  17794. const facades = [];
  17795. const entryModules = new Set([...this.entryModules, ...this.implicitEntryModules]);
  17796. const exposedVariables = new Set(this.dynamicEntryModules.map(({ namespace }) => namespace));
  17797. for (const module of entryModules) {
  17798. if (module.preserveSignature === 'allow-extension') {
  17799. const canPreserveExports = this.canPreserveModuleExports(module);
  17800. if (canPreserveExports &&
  17801. !module.chunkFileNames.size &&
  17802. module.chunkNames.every(({ isUserDefined }) => !isUserDefined)) {
  17803. this.allowExtensionModules.add(module);
  17804. if (!this.facadeModule) {
  17805. this.facadeModule = module;
  17806. this.strictFacade = false;
  17807. this.assignFacadeName({}, module, this.outputOptions.preserveModules);
  17808. }
  17809. this.facadeChunkByModule.set(module, this);
  17810. continue;
  17811. }
  17812. }
  17813. const requiredFacades = Array.from(new Set(module.chunkNames.filter(({ isUserDefined }) => isUserDefined).map(({ name }) => name)),
  17814. // mapping must run after Set 'name' dedupe
  17815. name => ({
  17816. name
  17817. }));
  17818. if (requiredFacades.length === 0 && module.isUserDefinedEntryPoint) {
  17819. requiredFacades.push({});
  17820. }
  17821. requiredFacades.push(...Array.from(module.chunkFileNames, fileName => ({ fileName })));
  17822. if (requiredFacades.length === 0) {
  17823. requiredFacades.push({});
  17824. }
  17825. if (!this.facadeModule) {
  17826. const needsStrictFacade = !this.outputOptions.preserveModules &&
  17827. (module.preserveSignature === 'strict' ||
  17828. (module.preserveSignature === 'exports-only' &&
  17829. module.getExportNamesByVariable().size > 0));
  17830. if (!needsStrictFacade || this.canModuleBeFacade(module, exposedVariables)) {
  17831. this.facadeModule = module;
  17832. this.facadeChunkByModule.set(module, this);
  17833. if (module.preserveSignature) {
  17834. this.strictFacade = needsStrictFacade;
  17835. }
  17836. this.assignFacadeName(requiredFacades.shift(), module, this.outputOptions.preserveModules);
  17837. }
  17838. }
  17839. for (const facadeName of requiredFacades) {
  17840. 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));
  17841. }
  17842. }
  17843. for (const module of this.dynamicEntryModules) {
  17844. if (module.info.syntheticNamedExports)
  17845. continue;
  17846. if (!this.facadeModule && this.canModuleBeFacade(module, exposedVariables)) {
  17847. this.facadeModule = module;
  17848. this.facadeChunkByModule.set(module, this);
  17849. this.strictFacade = true;
  17850. this.dynamicName = getChunkNameFromModule(module);
  17851. }
  17852. else if (this.facadeModule === module &&
  17853. !this.strictFacade &&
  17854. this.canModuleBeFacade(module, exposedVariables)) {
  17855. this.strictFacade = true;
  17856. }
  17857. else if (!this.facadeChunkByModule.get(module)?.strictFacade) {
  17858. this.includedNamespaces.add(module);
  17859. this.exports.add(module.namespace);
  17860. }
  17861. }
  17862. if (!this.outputOptions.preserveModules) {
  17863. this.addNecessaryImportsForFacades();
  17864. }
  17865. return facades;
  17866. }
  17867. canPreserveModuleExports(module) {
  17868. const exportNamesByVariable = module.getExportNamesByVariable();
  17869. // Check for conflicts - an export name is a conflict if it points to a different module or definition
  17870. for (const [variable, exportNames] of exportNamesByVariable) {
  17871. for (const exportName of exportNames) {
  17872. const existingVariable = this.exportsByName.get(exportName);
  17873. // It's ok if the same export name in two modules references the exact same variable
  17874. if (existingVariable && existingVariable !== variable) {
  17875. return false;
  17876. }
  17877. }
  17878. }
  17879. // No actual conflicts found, add export names for future conflict checks
  17880. for (const [variable, exportNames] of exportNamesByVariable) {
  17881. for (const exportName of exportNames) {
  17882. this.exportsByName.set(exportName, variable);
  17883. }
  17884. }
  17885. return true;
  17886. }
  17887. getChunkName() {
  17888. return (this.name ??= this.outputOptions.sanitizeFileName(this.getFallbackChunkName()));
  17889. }
  17890. getExportNames() {
  17891. return (this.sortedExportNames ??= [...this.exportsByName.keys()].sort());
  17892. }
  17893. getFileName() {
  17894. return this.fileName || this.getPreliminaryFileName().fileName;
  17895. }
  17896. getImportPath(importer) {
  17897. return escapeId(getImportPath(importer, this.getFileName(), this.outputOptions.format === 'amd' && !this.outputOptions.amd.forceJsExtensionForImports, true));
  17898. }
  17899. getPreliminaryFileName() {
  17900. if (this.preliminaryFileName) {
  17901. return this.preliminaryFileName;
  17902. }
  17903. let fileName;
  17904. let hashPlaceholder = null;
  17905. const { chunkFileNames, entryFileNames, file, format, preserveModules } = this.outputOptions;
  17906. if (file) {
  17907. fileName = basename(file);
  17908. }
  17909. else if (this.fileName === null) {
  17910. const [pattern, patternName] = preserveModules || this.facadeModule?.isUserDefinedEntryPoint
  17911. ? [entryFileNames, 'output.entryFileNames']
  17912. : [chunkFileNames, 'output.chunkFileNames'];
  17913. fileName = renderNamePattern(typeof pattern === 'function' ? pattern(this.getPreRenderedChunkInfo()) : pattern, patternName, {
  17914. format: () => format,
  17915. hash: size => hashPlaceholder ||
  17916. (hashPlaceholder = this.getPlaceholder(patternName, size || DEFAULT_HASH_SIZE)),
  17917. name: () => this.getChunkName()
  17918. });
  17919. if (!hashPlaceholder) {
  17920. fileName = makeUnique(fileName, this.bundle);
  17921. }
  17922. }
  17923. else {
  17924. fileName = this.fileName;
  17925. }
  17926. if (!hashPlaceholder) {
  17927. this.bundle[fileName] = FILE_PLACEHOLDER;
  17928. }
  17929. // Caching is essential to not conflict with the file name reservation above
  17930. return (this.preliminaryFileName = { fileName, hashPlaceholder });
  17931. }
  17932. getPreliminarySourcemapFileName() {
  17933. if (this.preliminarySourcemapFileName) {
  17934. return this.preliminarySourcemapFileName;
  17935. }
  17936. const { sourcemapFileNames, format } = this.outputOptions;
  17937. if (!sourcemapFileNames) {
  17938. return null;
  17939. }
  17940. let hashPlaceholder = null;
  17941. const [pattern, patternName] = [sourcemapFileNames, 'output.sourcemapFileNames'];
  17942. let sourcemapFileName = renderNamePattern(typeof pattern === 'function' ? pattern(this.getPreRenderedChunkInfo()) : pattern, patternName, {
  17943. chunkhash: () => this.getPreliminaryFileName().hashPlaceholder || '',
  17944. format: () => format,
  17945. hash: size => hashPlaceholder ||
  17946. (hashPlaceholder = this.getPlaceholder(patternName, size || DEFAULT_HASH_SIZE)),
  17947. name: () => this.getChunkName()
  17948. });
  17949. if (!hashPlaceholder) {
  17950. sourcemapFileName = makeUnique(sourcemapFileName, this.bundle);
  17951. }
  17952. return (this.preliminarySourcemapFileName = {
  17953. fileName: sourcemapFileName,
  17954. hashPlaceholder
  17955. });
  17956. }
  17957. getRenderedChunkInfo() {
  17958. if (this.renderedChunkInfo) {
  17959. return this.renderedChunkInfo;
  17960. }
  17961. return (this.renderedChunkInfo = {
  17962. ...this.getPreRenderedChunkInfo(),
  17963. dynamicImports: this.getDynamicDependencies().map(resolveFileName),
  17964. fileName: this.getFileName(),
  17965. implicitlyLoadedBefore: Array.from(this.implicitlyLoadedBefore, resolveFileName),
  17966. importedBindings: getImportedBindingsPerDependency(this.getRenderedDependencies(), resolveFileName),
  17967. imports: Array.from(this.dependencies, resolveFileName),
  17968. modules: this.renderedModules,
  17969. referencedFiles: this.getReferencedFiles()
  17970. });
  17971. }
  17972. getVariableExportName(variable) {
  17973. if (this.outputOptions.preserveModules && variable instanceof NamespaceVariable) {
  17974. return '*';
  17975. }
  17976. return this.exportNamesByVariable.get(variable)[0];
  17977. }
  17978. link() {
  17979. this.dependencies = getStaticDependencies(this, this.orderedModules, this.chunkByModule, this.externalChunkByModule);
  17980. for (const module of this.orderedModules) {
  17981. this.addImplicitlyLoadedBeforeFromModule(module);
  17982. this.setUpChunkImportsAndExportsForModule(module);
  17983. }
  17984. }
  17985. inlineTransitiveImports() {
  17986. const { facadeModule, dependencies, outputOptions } = this;
  17987. const { hoistTransitiveImports, preserveModules } = outputOptions;
  17988. // for static and dynamic entry points, add transitive dependencies to this
  17989. // chunk's dependencies to avoid loading latency
  17990. if (hoistTransitiveImports && !preserveModules && facadeModule !== null) {
  17991. for (const dep of dependencies) {
  17992. if (dep instanceof Chunk)
  17993. this.inlineChunkDependencies(dep);
  17994. }
  17995. }
  17996. }
  17997. async render() {
  17998. const { exportMode, facadeModule, inputOptions: { onLog }, outputOptions, pluginDriver, snippets } = this;
  17999. const { format, preserveModules } = outputOptions;
  18000. const preliminaryFileName = this.getPreliminaryFileName();
  18001. const preliminarySourcemapFileName = this.getPreliminarySourcemapFileName();
  18002. const { accessedGlobals, indent, magicString, renderedSource, usedModules, usesTopLevelAwait } = this.renderModules(preliminaryFileName.fileName);
  18003. const renderedDependencies = [...this.getRenderedDependencies().values()];
  18004. const renderedExports = exportMode === 'none' ? [] : this.getChunkExportDeclarations(format);
  18005. let hasExports = renderedExports.length > 0;
  18006. let hasDefaultExport = false;
  18007. for (const renderedDependency of renderedDependencies) {
  18008. const { reexports } = renderedDependency;
  18009. if (reexports?.length) {
  18010. hasExports = true;
  18011. if (!hasDefaultExport && reexports.some(reexport => reexport.reexported === 'default')) {
  18012. hasDefaultExport = true;
  18013. }
  18014. if (format === 'es') {
  18015. renderedDependency.reexports = reexports.filter(({ reexported }) => !renderedExports.find(({ exported }) => exported === reexported));
  18016. }
  18017. }
  18018. }
  18019. if (!hasDefaultExport) {
  18020. for (const { exported } of renderedExports) {
  18021. if (exported === 'default') {
  18022. hasDefaultExport = true;
  18023. break;
  18024. }
  18025. }
  18026. }
  18027. const { intro, outro, banner, footer } = await createAddons(outputOptions, pluginDriver, this.getRenderedChunkInfo());
  18028. finalisers[format](renderedSource, {
  18029. accessedGlobals,
  18030. dependencies: renderedDependencies,
  18031. exports: renderedExports,
  18032. hasDefaultExport,
  18033. hasExports,
  18034. id: preliminaryFileName.fileName,
  18035. indent,
  18036. intro,
  18037. isEntryFacade: preserveModules || (facadeModule !== null && facadeModule.info.isEntry),
  18038. isModuleFacade: facadeModule !== null,
  18039. log: onLog,
  18040. namedExportsMode: exportMode !== 'default',
  18041. outro,
  18042. snippets,
  18043. usesTopLevelAwait
  18044. }, outputOptions);
  18045. if (banner)
  18046. magicString.prepend(banner);
  18047. if (format === 'es' || format === 'cjs') {
  18048. const shebang = facadeModule !== null && facadeModule.info.isEntry && facadeModule.shebang;
  18049. if (shebang) {
  18050. magicString.prepend(`#!${shebang}\n`);
  18051. }
  18052. }
  18053. if (footer)
  18054. magicString.append(footer);
  18055. return {
  18056. chunk: this,
  18057. magicString,
  18058. preliminaryFileName,
  18059. preliminarySourcemapFileName,
  18060. usedModules
  18061. };
  18062. }
  18063. addImplicitlyLoadedBeforeFromModule(baseModule) {
  18064. const { chunkByModule, implicitlyLoadedBefore } = this;
  18065. for (const module of baseModule.implicitlyLoadedBefore) {
  18066. const chunk = chunkByModule.get(module);
  18067. if (chunk && chunk !== this) {
  18068. implicitlyLoadedBefore.add(chunk);
  18069. }
  18070. }
  18071. }
  18072. addNecessaryImportsForFacades() {
  18073. for (const [module, variables] of this.includedReexportsByModule) {
  18074. if (this.includedNamespaces.has(module)) {
  18075. for (const variable of variables) {
  18076. this.imports.add(variable);
  18077. }
  18078. }
  18079. }
  18080. }
  18081. assignFacadeName({ fileName, name }, facadedModule, preservePath) {
  18082. if (fileName) {
  18083. this.fileName = fileName;
  18084. }
  18085. else {
  18086. this.name = this.outputOptions.sanitizeFileName(name ||
  18087. (preservePath
  18088. ? this.getPreserveModulesChunkNameFromModule(facadedModule)
  18089. : getChunkNameFromModule(facadedModule)));
  18090. }
  18091. }
  18092. checkCircularDependencyImport(variable, importingModule) {
  18093. const variableModule = variable.module;
  18094. if (variableModule instanceof Module) {
  18095. const exportChunk = this.chunkByModule.get(variableModule);
  18096. let alternativeReexportModule;
  18097. do {
  18098. alternativeReexportModule = importingModule.alternativeReexportModules.get(variable);
  18099. if (alternativeReexportModule) {
  18100. const exportingChunk = this.chunkByModule.get(alternativeReexportModule);
  18101. if (exportingChunk !== exportChunk) {
  18102. this.inputOptions.onLog(LOGLEVEL_WARN, logCyclicCrossChunkReexport(
  18103. // Namespaces do not have an export name
  18104. variableModule.getExportNamesByVariable().get(variable)?.[0] || '*', variableModule.id, alternativeReexportModule.id, importingModule.id, this.outputOptions.preserveModules));
  18105. }
  18106. importingModule = alternativeReexportModule;
  18107. }
  18108. } while (alternativeReexportModule);
  18109. }
  18110. }
  18111. ensureReexportsAreAvailableForModule(module) {
  18112. const includedReexports = [];
  18113. const map = module.getExportNamesByVariable();
  18114. for (const exportedVariable of map.keys()) {
  18115. const isSynthetic = exportedVariable instanceof SyntheticNamedExportVariable;
  18116. const importedVariable = isSynthetic ? exportedVariable.getBaseVariable() : exportedVariable;
  18117. this.checkCircularDependencyImport(importedVariable, module);
  18118. // When preserving modules, we do not create namespace objects but directly
  18119. // use the actual namespaces, which would be broken by this logic.
  18120. if (!(importedVariable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
  18121. const exportingModule = importedVariable.module;
  18122. if (exportingModule instanceof Module) {
  18123. const chunk = this.chunkByModule.get(exportingModule);
  18124. if (chunk && chunk !== this) {
  18125. chunk.exports.add(importedVariable);
  18126. includedReexports.push(importedVariable);
  18127. if (isSynthetic) {
  18128. this.imports.add(importedVariable);
  18129. }
  18130. }
  18131. }
  18132. }
  18133. }
  18134. if (includedReexports.length > 0) {
  18135. this.includedReexportsByModule.set(module, includedReexports);
  18136. }
  18137. }
  18138. generateVariableName() {
  18139. if (this.manualChunkAlias) {
  18140. return this.manualChunkAlias;
  18141. }
  18142. const moduleForNaming = this.entryModules[0] ||
  18143. this.implicitEntryModules[0] ||
  18144. this.dynamicEntryModules[0] ||
  18145. this.orderedModules[this.orderedModules.length - 1];
  18146. if (moduleForNaming) {
  18147. return getChunkNameFromModule(moduleForNaming);
  18148. }
  18149. return 'chunk';
  18150. }
  18151. getChunkExportDeclarations(format) {
  18152. const exports$1 = [];
  18153. for (const exportName of this.getExportNames()) {
  18154. if (exportName[0] === '*')
  18155. continue;
  18156. const variable = this.exportsByName.get(exportName);
  18157. if (!(variable instanceof SyntheticNamedExportVariable)) {
  18158. const module = variable.module;
  18159. if (module) {
  18160. const chunk = this.chunkByModule.get(module);
  18161. if (chunk !== this) {
  18162. if (!chunk || format !== 'es') {
  18163. continue;
  18164. }
  18165. const chunkDep = this.renderedDependencies.get(chunk);
  18166. if (!chunkDep) {
  18167. continue;
  18168. }
  18169. const { imports, reexports } = chunkDep;
  18170. const importedByReexported = reexports?.find(({ reexported }) => reexported === exportName);
  18171. const isImported = imports?.find(({ imported }) => imported === importedByReexported?.imported);
  18172. if (!isImported) {
  18173. continue;
  18174. }
  18175. }
  18176. }
  18177. }
  18178. let expression = null;
  18179. let hoisted = false;
  18180. let local = variable.getName(this.snippets.getPropertyAccess);
  18181. if (variable instanceof LocalVariable) {
  18182. for (const declaration of variable.declarations) {
  18183. if (declaration.parent instanceof FunctionDeclaration ||
  18184. (declaration instanceof ExportDefaultDeclaration &&
  18185. declaration.declaration instanceof FunctionDeclaration)) {
  18186. hoisted = true;
  18187. break;
  18188. }
  18189. }
  18190. }
  18191. else if (variable instanceof SyntheticNamedExportVariable) {
  18192. expression = local;
  18193. if (format === 'es') {
  18194. local = variable.renderName;
  18195. }
  18196. }
  18197. exports$1.push({
  18198. exported: exportName,
  18199. expression,
  18200. hoisted,
  18201. local
  18202. });
  18203. }
  18204. return exports$1;
  18205. }
  18206. getDependenciesToBeDeconflicted(addNonNamespacesAndInteropHelpers, addDependenciesWithoutBindings, interop) {
  18207. const dependencies = new Set();
  18208. const deconflictedDefault = new Set();
  18209. const deconflictedNamespace = new Set();
  18210. for (const variable of [...this.exportNamesByVariable.keys(), ...this.imports]) {
  18211. if (addNonNamespacesAndInteropHelpers || variable.isNamespace) {
  18212. const module = variable.module;
  18213. if (module instanceof ExternalModule) {
  18214. const chunk = this.externalChunkByModule.get(module);
  18215. dependencies.add(chunk);
  18216. if (addNonNamespacesAndInteropHelpers) {
  18217. if (variable.name === 'default') {
  18218. if (defaultInteropHelpersByInteropType[interop(module.id)]) {
  18219. deconflictedDefault.add(chunk);
  18220. }
  18221. }
  18222. else if (variable.isNamespace &&
  18223. namespaceInteropHelpersByInteropType[interop(module.id)] &&
  18224. (this.imports.has(variable) ||
  18225. !this.exportNamesByVariable.get(variable)?.every(name => name[0] === '*'))) {
  18226. // We only need to deconflict it if the namespace is actually
  18227. // created as a variable, i.e. because it is used internally or
  18228. // because it is reexported as an object
  18229. deconflictedNamespace.add(chunk);
  18230. }
  18231. }
  18232. }
  18233. else {
  18234. const chunk = this.chunkByModule.get(module);
  18235. if (chunk !== this) {
  18236. dependencies.add(chunk);
  18237. if (addNonNamespacesAndInteropHelpers &&
  18238. chunk.exportMode === 'default' &&
  18239. variable.isNamespace) {
  18240. deconflictedNamespace.add(chunk);
  18241. }
  18242. }
  18243. }
  18244. }
  18245. }
  18246. if (addDependenciesWithoutBindings) {
  18247. for (const dependency of this.dependencies) {
  18248. dependencies.add(dependency);
  18249. }
  18250. }
  18251. return { deconflictedDefault, deconflictedNamespace, dependencies };
  18252. }
  18253. getDynamicDependencies() {
  18254. return this.getIncludedDynamicImports()
  18255. .map(resolvedDynamicImport => resolvedDynamicImport.facadeChunk ||
  18256. resolvedDynamicImport.chunk ||
  18257. resolvedDynamicImport.externalChunk ||
  18258. resolvedDynamicImport.resolution)
  18259. .filter((resolution) => resolution !== this &&
  18260. (resolution instanceof Chunk || resolution instanceof ExternalChunk));
  18261. }
  18262. getDynamicImportStringAndAttributes(resolution, fileName, node) {
  18263. const { externalImportAttributes } = this.outputOptions;
  18264. const keepExternalImportAttributes = ['es', 'cjs'].includes(this.outputOptions.format) && externalImportAttributes;
  18265. if (resolution instanceof ExternalModule) {
  18266. const chunk = this.externalChunkByModule.get(resolution);
  18267. const dynamicAttributes = chunk.getImportAttributes(this.snippets);
  18268. return [
  18269. `'${chunk.getImportPath(fileName)}'`,
  18270. dynamicAttributes || (keepExternalImportAttributes ? true : null)
  18271. ];
  18272. }
  18273. let attributes = null;
  18274. if (keepExternalImportAttributes) {
  18275. const attributesFromImportAttributes = getAttributesFromImportExpression(node);
  18276. attributes =
  18277. attributesFromImportAttributes === EMPTY_OBJECT
  18278. ? true
  18279. : formatAttributes(attributesFromImportAttributes, this.snippets);
  18280. }
  18281. return [resolution || '', attributes];
  18282. }
  18283. getFallbackChunkName() {
  18284. if (this.manualChunkAlias) {
  18285. return this.manualChunkAlias;
  18286. }
  18287. if (this.dynamicName) {
  18288. return this.dynamicName;
  18289. }
  18290. if (this.fileName) {
  18291. return getAliasName(this.fileName);
  18292. }
  18293. return getAliasName(this.orderedModules[this.orderedModules.length - 1].id);
  18294. }
  18295. getImportSpecifiers() {
  18296. const { interop } = this.outputOptions;
  18297. const importsByDependency = new Map();
  18298. for (const variable of this.imports) {
  18299. const module = variable.module;
  18300. let dependency;
  18301. let imported;
  18302. const isSourcePhase = module instanceof ExternalModule && variable.isSourcePhase;
  18303. if (module instanceof ExternalModule) {
  18304. dependency = this.externalChunkByModule.get(module);
  18305. imported = variable.name;
  18306. if (!isSourcePhase &&
  18307. imported !== 'default' &&
  18308. imported !== '*' &&
  18309. interop(module.id) === 'defaultOnly') {
  18310. return error(logUnexpectedNamedImport(module.id, imported, false));
  18311. }
  18312. }
  18313. else {
  18314. dependency = this.chunkByModule.get(module);
  18315. imported = dependency.getVariableExportName(variable);
  18316. }
  18317. getOrCreate(importsByDependency, dependency, getNewArray).push({
  18318. imported,
  18319. local: variable.getName(this.snippets.getPropertyAccess),
  18320. phase: isSourcePhase ? 'source' : 'instance'
  18321. });
  18322. }
  18323. return importsByDependency;
  18324. }
  18325. getIncludedDynamicImports() {
  18326. if (this.includedDynamicImports) {
  18327. return this.includedDynamicImports;
  18328. }
  18329. const includedDynamicImports = [];
  18330. for (const module of this.orderedModules) {
  18331. for (const { node } of module.dynamicImports) {
  18332. if (!node.included) {
  18333. continue;
  18334. }
  18335. const { resolution } = node;
  18336. includedDynamicImports.push(resolution instanceof Module
  18337. ? {
  18338. chunk: this.chunkByModule.get(resolution),
  18339. externalChunk: null,
  18340. facadeChunk: this.facadeChunkByModule.get(resolution),
  18341. node,
  18342. resolution
  18343. }
  18344. : resolution instanceof ExternalModule
  18345. ? {
  18346. chunk: null,
  18347. externalChunk: this.externalChunkByModule.get(resolution),
  18348. facadeChunk: null,
  18349. node,
  18350. resolution
  18351. }
  18352. : { chunk: null, externalChunk: null, facadeChunk: null, node, resolution });
  18353. }
  18354. }
  18355. return (this.includedDynamicImports = includedDynamicImports);
  18356. }
  18357. getPreRenderedChunkInfo() {
  18358. if (this.preRenderedChunkInfo) {
  18359. return this.preRenderedChunkInfo;
  18360. }
  18361. const { dynamicEntryModules, facadeModule, implicitEntryModules, orderedModules } = this;
  18362. return (this.preRenderedChunkInfo = {
  18363. exports: this.getExportNames(),
  18364. facadeModuleId: facadeModule && facadeModule.id,
  18365. isDynamicEntry: dynamicEntryModules.length > 0,
  18366. isEntry: !!facadeModule?.info.isEntry,
  18367. isImplicitEntry: implicitEntryModules.length > 0,
  18368. moduleIds: orderedModules.map(({ id }) => id),
  18369. name: this.getChunkName(),
  18370. type: 'chunk'
  18371. });
  18372. }
  18373. getPreserveModulesChunkNameFromModule(module) {
  18374. const predefinedChunkName = getPredefinedChunkNameFromModule(module);
  18375. if (predefinedChunkName)
  18376. return predefinedChunkName;
  18377. const { preserveModulesRoot, sanitizeFileName } = this.outputOptions;
  18378. const sanitizedId = sanitizeFileName(normalize(module.id.split(QUERY_HASH_REGEX, 1)[0]));
  18379. const extensionName = extname(sanitizedId);
  18380. const idWithoutExtension = NON_ASSET_EXTENSIONS.has(extensionName)
  18381. ? sanitizedId.slice(0, -extensionName.length)
  18382. : sanitizedId;
  18383. if (isAbsolute$1(idWithoutExtension)) {
  18384. if (preserveModulesRoot && resolve$1(idWithoutExtension).startsWith(preserveModulesRoot)) {
  18385. return idWithoutExtension.slice(preserveModulesRoot.length).replace(/^[/\\]/, '');
  18386. }
  18387. else {
  18388. // handle edge case in Windows
  18389. if (this.inputBase === '/' && idWithoutExtension[0] !== '/') {
  18390. return relative$1(this.inputBase, idWithoutExtension.replace(/^[a-zA-Z]:[/\\]/, '/'));
  18391. }
  18392. return relative$1(this.inputBase, idWithoutExtension);
  18393. }
  18394. }
  18395. else {
  18396. return (this.outputOptions.virtualDirname.replace(/\/$/, '') + '/' + basename(idWithoutExtension));
  18397. }
  18398. }
  18399. getReexportSpecifiers() {
  18400. const { externalLiveBindings, interop } = this.outputOptions;
  18401. const reexportSpecifiers = new Map();
  18402. for (let exportName of this.getExportNames()) {
  18403. let dependency;
  18404. let imported;
  18405. let needsLiveBinding;
  18406. if (exportName[0] === '*') {
  18407. const id = exportName.slice(1);
  18408. if (interop(id) === 'defaultOnly') {
  18409. this.inputOptions.onLog(LOGLEVEL_WARN, logUnexpectedNamespaceReexport(id));
  18410. }
  18411. needsLiveBinding = externalLiveBindings;
  18412. dependency = this.externalChunkByModule.get(this.modulesById.get(id));
  18413. imported = exportName = '*';
  18414. }
  18415. else {
  18416. const variable = this.exportsByName.get(exportName);
  18417. if (variable instanceof SyntheticNamedExportVariable)
  18418. continue;
  18419. const module = variable.module;
  18420. if (module instanceof Module) {
  18421. dependency = this.chunkByModule.get(module);
  18422. if (dependency === this)
  18423. continue;
  18424. imported = dependency.getVariableExportName(variable);
  18425. needsLiveBinding = variable.isReassigned;
  18426. }
  18427. else {
  18428. dependency = this.externalChunkByModule.get(module);
  18429. imported = variable.name;
  18430. if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
  18431. return error(logUnexpectedNamedImport(module.id, imported, true));
  18432. }
  18433. needsLiveBinding =
  18434. externalLiveBindings &&
  18435. (imported !== 'default' || isDefaultAProperty(interop(module.id), true));
  18436. }
  18437. }
  18438. getOrCreate(reexportSpecifiers, dependency, getNewArray).push({
  18439. imported,
  18440. needsLiveBinding,
  18441. reexported: exportName
  18442. });
  18443. }
  18444. return reexportSpecifiers;
  18445. }
  18446. getReferencedFiles() {
  18447. const referencedFiles = new Set();
  18448. for (const module of this.orderedModules) {
  18449. for (const meta of module.importMetas) {
  18450. const fileName = meta.getReferencedFileName(this.pluginDriver);
  18451. if (fileName) {
  18452. referencedFiles.add(fileName);
  18453. }
  18454. }
  18455. }
  18456. return [...referencedFiles];
  18457. }
  18458. getRenderedDependencies() {
  18459. if (this.renderedDependencies) {
  18460. return this.renderedDependencies;
  18461. }
  18462. const importSpecifiers = this.getImportSpecifiers();
  18463. const reexportSpecifiers = this.getReexportSpecifiers();
  18464. const renderedDependencies = new Map();
  18465. const fileName = this.getFileName();
  18466. for (const dependency of this.dependencies) {
  18467. const imports = importSpecifiers.get(dependency) || null;
  18468. const reexports = reexportSpecifiers.get(dependency) || null;
  18469. const namedExportsMode = dependency instanceof ExternalChunk || dependency.exportMode !== 'default';
  18470. const importPath = dependency.getImportPath(fileName);
  18471. // Separate source-phase imports from regular imports
  18472. const sourcePhaseImport = imports?.find(index => index.phase === 'source');
  18473. const instanceImports = imports?.filter(index => index.phase !== 'source') ?? null;
  18474. renderedDependencies.set(dependency, {
  18475. attributes: dependency instanceof ExternalChunk
  18476. ? dependency.getImportAttributes(this.snippets)
  18477. : null,
  18478. defaultVariableName: dependency.defaultVariableName,
  18479. globalName: dependency instanceof ExternalChunk &&
  18480. (this.outputOptions.format === 'umd' || this.outputOptions.format === 'iife') &&
  18481. getGlobalName(dependency, this.outputOptions.globals, (imports || reexports) !== null, this.inputOptions.onLog),
  18482. importPath,
  18483. imports: instanceImports && instanceImports.length > 0 ? instanceImports : null,
  18484. isChunk: dependency instanceof Chunk,
  18485. name: dependency.variableName,
  18486. namedExportsMode,
  18487. namespaceVariableName: dependency.namespaceVariableName,
  18488. reexports,
  18489. sourcePhaseImport: sourcePhaseImport?.local
  18490. });
  18491. }
  18492. return (this.renderedDependencies = renderedDependencies);
  18493. }
  18494. inlineChunkDependencies(chunk) {
  18495. for (const dep of chunk.dependencies) {
  18496. if (this.dependencies.has(dep))
  18497. continue;
  18498. this.dependencies.add(dep);
  18499. if (dep instanceof Chunk) {
  18500. this.inlineChunkDependencies(dep);
  18501. }
  18502. }
  18503. }
  18504. // This method changes properties on the AST before rendering and must not be async
  18505. renderModules(fileName) {
  18506. const { accessedGlobalsByScope, dependencies, exportNamesByVariable, includedNamespaces, inputOptions: { onLog }, isEmpty, orderedModules, outputOptions, pluginDriver, renderedModules, snippets } = this;
  18507. const { compact, format, freeze, generatedCode: { symbols }, importAttributesKey } = outputOptions;
  18508. const { _, cnst, n } = snippets;
  18509. this.setDynamicImportResolutions(fileName);
  18510. this.setImportMetaResolutions(fileName);
  18511. this.setIdentifierRenderResolutions();
  18512. const magicString = new Bundle$1({ separator: `${n}${n}` });
  18513. const indent = getIndentString(orderedModules, outputOptions);
  18514. const usedModules = [];
  18515. let hoistedSource = '';
  18516. const accessedGlobals = new Set();
  18517. const renderedModuleSources = new Map();
  18518. const renderOptions = {
  18519. accessedDocumentCurrentScript: false,
  18520. exportNamesByVariable,
  18521. format,
  18522. freeze,
  18523. importAttributesKey,
  18524. indent,
  18525. pluginDriver,
  18526. snippets,
  18527. symbols,
  18528. useOriginalName: null
  18529. };
  18530. let usesTopLevelAwait = false;
  18531. for (const module of orderedModules) {
  18532. let renderedLength = 0;
  18533. let source;
  18534. if (module.isIncluded() || includedNamespaces.has(module)) {
  18535. const rendered = module.render(renderOptions);
  18536. if (!renderOptions.accessedDocumentCurrentScript &&
  18537. formatsMaybeAccessDocumentCurrentScript.includes(format)) {
  18538. this.accessedGlobalsByScope.get(module.scope)?.delete(DOCUMENT_CURRENT_SCRIPT);
  18539. }
  18540. renderOptions.accessedDocumentCurrentScript = false;
  18541. ({ source } = rendered);
  18542. usesTopLevelAwait ||= rendered.usesTopLevelAwait;
  18543. renderedLength = source.length();
  18544. if (renderedLength) {
  18545. if (compact && source.lastLine().includes('//'))
  18546. source.append('\n');
  18547. renderedModuleSources.set(module, source);
  18548. magicString.addSource(source);
  18549. usedModules.push(module);
  18550. }
  18551. const namespace = module.namespace;
  18552. if (includedNamespaces.has(module)) {
  18553. const rendered = namespace.renderBlock(renderOptions);
  18554. if (namespace.renderFirst())
  18555. hoistedSource += n + rendered;
  18556. else
  18557. magicString.addSource(new MagicString(rendered));
  18558. }
  18559. const accessedGlobalVariables = accessedGlobalsByScope.get(module.scope);
  18560. if (accessedGlobalVariables) {
  18561. for (const name of accessedGlobalVariables) {
  18562. accessedGlobals.add(name);
  18563. }
  18564. }
  18565. }
  18566. const { renderedExports, removedExports } = module.getRenderedExports();
  18567. renderedModules[module.id] = {
  18568. get code() {
  18569. return source?.toString() ?? null;
  18570. },
  18571. originalLength: module.originalCode.length,
  18572. removedExports,
  18573. renderedExports,
  18574. renderedLength
  18575. };
  18576. }
  18577. if (hoistedSource)
  18578. magicString.prepend(hoistedSource + n + n);
  18579. if (this.needsExportsShim) {
  18580. magicString.prepend(`${n}${cnst} ${MISSING_EXPORT_SHIM_VARIABLE}${_}=${_}void 0;${n}${n}`);
  18581. }
  18582. const renderedSource = compact ? magicString : magicString.trim();
  18583. if (isEmpty && this.getExportNames().length === 0 && dependencies.size === 0) {
  18584. onLog(LOGLEVEL_WARN, logEmptyChunk(this.getChunkName()));
  18585. }
  18586. return { accessedGlobals, indent, magicString, renderedSource, usedModules, usesTopLevelAwait };
  18587. }
  18588. setDynamicImportResolutions(fileName) {
  18589. const { accessedGlobalsByScope, outputOptions, pluginDriver, snippets } = this;
  18590. for (const resolvedDynamicImport of this.getIncludedDynamicImports()) {
  18591. if (resolvedDynamicImport.chunk) {
  18592. const { chunk, facadeChunk, node, resolution } = resolvedDynamicImport;
  18593. if (chunk === this) {
  18594. node.setInternalResolution(resolution.namespace);
  18595. }
  18596. else {
  18597. node.setExternalResolution((facadeChunk || chunk).exportMode, outputOptions, snippets, pluginDriver, accessedGlobalsByScope, `'${(facadeChunk || chunk).getImportPath(fileName)}'`, !facadeChunk?.strictFacade && chunk.exportNamesByVariable.get(resolution.namespace)[0], null, this, facadeChunk || chunk);
  18598. }
  18599. }
  18600. else {
  18601. const { node, resolution } = resolvedDynamicImport;
  18602. const [resolutionString, attributes] = this.getDynamicImportStringAndAttributes(resolution, fileName, node);
  18603. node.setExternalResolution('external', outputOptions, snippets, pluginDriver, accessedGlobalsByScope, resolutionString, false, attributes, this, null);
  18604. }
  18605. }
  18606. }
  18607. setIdentifierRenderResolutions() {
  18608. const { format, generatedCode: { symbols }, interop, preserveModules, externalLiveBindings } = this.outputOptions;
  18609. const syntheticExports = new Set();
  18610. for (const exportName of this.getExportNames()) {
  18611. const exportVariable = this.exportsByName.get(exportName);
  18612. if (format !== 'es' &&
  18613. format !== 'system' &&
  18614. exportVariable.isReassigned &&
  18615. !exportVariable.isId) {
  18616. exportVariable.setRenderNames('exports', exportName);
  18617. }
  18618. else if (exportVariable instanceof SyntheticNamedExportVariable) {
  18619. syntheticExports.add(exportVariable);
  18620. }
  18621. else {
  18622. exportVariable.setRenderNames(null, null);
  18623. }
  18624. }
  18625. for (const module of this.orderedModules) {
  18626. if (module.needsExportShim) {
  18627. this.needsExportsShim = true;
  18628. break;
  18629. }
  18630. }
  18631. const usedNames = new Set(RESERVED_USED_NAMES);
  18632. if (this.needsExportsShim) {
  18633. usedNames.add(MISSING_EXPORT_SHIM_VARIABLE);
  18634. }
  18635. if (symbols) {
  18636. usedNames.add('Symbol');
  18637. }
  18638. 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);
  18639. }
  18640. setImportMetaResolutions(fileName) {
  18641. const { accessedGlobalsByScope, includedNamespaces, orderedModules, outputOptions: { format } } = this;
  18642. for (const module of orderedModules) {
  18643. for (const importMeta of module.importMetas) {
  18644. importMeta.setResolution(format, accessedGlobalsByScope, fileName);
  18645. }
  18646. if (includedNamespaces.has(module)) {
  18647. module.namespace.prepare(accessedGlobalsByScope);
  18648. }
  18649. }
  18650. }
  18651. setUpChunkImportsAndExportsForModule(module) {
  18652. const moduleImports = new Set(module.includedImports);
  18653. // when we are not preserving modules, we need to make all namespace variables available for
  18654. // rendering the namespace object
  18655. if (!this.outputOptions.preserveModules && this.includedNamespaces.has(module)) {
  18656. for (const variable of module.getExportedVariablesByName().values()) {
  18657. if (variable.included) {
  18658. moduleImports.add(variable);
  18659. }
  18660. }
  18661. }
  18662. for (let variable of moduleImports) {
  18663. if (variable instanceof ExportDefaultVariable) {
  18664. variable = variable.getOriginalVariable();
  18665. }
  18666. if (variable instanceof SyntheticNamedExportVariable) {
  18667. variable = variable.getBaseVariable();
  18668. }
  18669. const chunk = this.chunkByModule.get(variable.module);
  18670. if (chunk !== this) {
  18671. this.imports.add(variable);
  18672. if (variable.module instanceof Module) {
  18673. this.checkCircularDependencyImport(variable, module);
  18674. // When preserving modules, we do not create namespace objects but directly
  18675. // use the actual namespaces, which would be broken by this logic.
  18676. if (!(variable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
  18677. chunk.exports.add(variable);
  18678. }
  18679. }
  18680. }
  18681. }
  18682. if (this.includedNamespaces.has(module) ||
  18683. (module.info.isEntry && module.preserveSignature !== false) ||
  18684. module.includedDynamicImporters.some(importer => this.chunkByModule.get(importer) !== this)) {
  18685. this.ensureReexportsAreAvailableForModule(module);
  18686. }
  18687. for (const { node: { included, resolution } } of module.dynamicImports) {
  18688. if (included &&
  18689. resolution instanceof Module &&
  18690. this.chunkByModule.get(resolution) === this &&
  18691. !this.includedNamespaces.has(resolution)) {
  18692. this.includedNamespaces.add(resolution);
  18693. this.ensureReexportsAreAvailableForModule(resolution);
  18694. }
  18695. }
  18696. }
  18697. }
  18698. function getChunkNameFromModule(module) {
  18699. return getPredefinedChunkNameFromModule(module) ?? getAliasName(module.id);
  18700. }
  18701. function getPredefinedChunkNameFromModule(module) {
  18702. return (module.chunkNames.find(({ isUserDefined }) => isUserDefined)?.name ?? module.chunkNames[0]?.name);
  18703. }
  18704. function getImportedBindingsPerDependency(renderedDependencies, resolveFileName) {
  18705. const importedBindingsPerDependency = {};
  18706. for (const [dependency, declaration] of renderedDependencies) {
  18707. const specifiers = new Set();
  18708. if (declaration.imports) {
  18709. for (const { imported } of declaration.imports) {
  18710. specifiers.add(imported);
  18711. }
  18712. }
  18713. if (declaration.reexports) {
  18714. for (const { imported } of declaration.reexports) {
  18715. specifiers.add(imported);
  18716. }
  18717. }
  18718. importedBindingsPerDependency[resolveFileName(dependency)] = [...specifiers];
  18719. }
  18720. return importedBindingsPerDependency;
  18721. }
  18722. const QUERY_HASH_REGEX = /[#?]/;
  18723. const resolveFileName = (dependency) => dependency.getFileName();
  18724. /**
  18725. * Concatenate a number of iterables to a new iterable without fully evaluating
  18726. * their iterators. Useful when e.g. working with large sets or lists and when
  18727. * there is a chance that the iterators will not be fully exhausted.
  18728. */
  18729. function* concatLazy(iterables) {
  18730. for (const iterable of iterables) {
  18731. yield* iterable;
  18732. }
  18733. }
  18734. /**
  18735. * At its core, the algorithm first starts from each static or dynamic entry
  18736. * point and then assigns that entry point to all modules than can be reached
  18737. * via static imports. We call this the *dependent entry points* of that
  18738. * module.
  18739. *
  18740. * Then we group all modules with the same dependent entry points into chunks
  18741. * as those modules will always be loaded together.
  18742. *
  18743. * One non-trivial optimization we can apply is that dynamic entries are
  18744. * different from static entries in so far as when a dynamic import occurs,
  18745. * some modules are already in memory. If some of these modules are also
  18746. * dependencies of the dynamic entry, then it does not make sense to create a
  18747. * separate chunk for them. Instead, the dynamic import target can load them
  18748. * from the importing chunk.
  18749. *
  18750. * With regard to chunking, if B is implicitly loaded after A, then this can be
  18751. * handled the same way as if there was a dynamic import A => B.
  18752. *
  18753. * Example:
  18754. * Assume A -> B (A imports B), A => C (A dynamically imports C) and C -> B.
  18755. * Then the initial algorithm would assign A into the A chunk, C into the C
  18756. * chunk and B into the AC chunk, i.e. the chunk with the dependent entry
  18757. * points A and C.
  18758. * However we know that C can only be loaded from A, so A and its dependency B
  18759. * must already be in memory when C is loaded. So it is enough to create only
  18760. * two chunks A containing [AB] and C containing [C].
  18761. *
  18762. * So we do not assign the dynamic entry C as dependent entry point to modules
  18763. * that are already loaded.
  18764. *
  18765. * In a more complex example, let us assume that we have entry points X and Y.
  18766. * Further, let us assume
  18767. * X -> A, X -> B, X -> C,
  18768. * Y -> A, Y -> B,
  18769. * A => D,
  18770. * D -> B, D -> C
  18771. * So without dynamic import optimization, the dependent entry points are
  18772. * A: XY, B: DXY, C: DX, D: D, X: X, Y: Y, so we would for now create six
  18773. * chunks.
  18774. *
  18775. * Now D is loaded only after A is loaded. But A is loaded if either X is
  18776. * loaded or Y is loaded. So the modules that are already in memory when D is
  18777. * loaded are the intersection of all modules that X depends on with all
  18778. * modules that Y depends on, which in this case are the modules A and B.
  18779. * We could also say they are all modules that have both X and Y as dependent
  18780. * entry points.
  18781. *
  18782. * So we can remove D as dependent entry point from A and B, which means they
  18783. * both now have only XY as dependent entry points and can be merged into the
  18784. * same chunk.
  18785. *
  18786. * Now let us extend this to the most general case where we have several
  18787. * dynamic importers for one dynamic entry point.
  18788. *
  18789. * In the most general form, it works like this:
  18790. * For each dynamic entry point, we have a number of dynamic importers, which
  18791. * are the modules importing it. Using the previous ideas, we can determine
  18792. * the modules already in memory for each dynamic importer by looking for all
  18793. * modules that have all the dependent entry points of the dynamic importer as
  18794. * dependent entry points.
  18795. * So the modules that are guaranteed to be in memory when the dynamic entry
  18796. * point is loaded are the intersection of the modules already in memory for
  18797. * each dynamic importer.
  18798. *
  18799. * Assuming that A => D and B => D and A has dependent entry points XY and B
  18800. * has dependent entry points YZ, then the modules guaranteed to be in memory
  18801. * are all modules that have at least XYZ as dependent entry points.
  18802. * We call XYZ the *dynamically dependent entry points* of D.
  18803. *
  18804. * Now there is one last case to consider: If one of the dynamically dependent
  18805. * entries is itself a dynamic entry, then any module is in memory that either
  18806. * is a dependency of that dynamic entry or again has the dynamic dependent
  18807. * entries of that dynamic entry as dependent entry points.
  18808. *
  18809. * A naive algorithm for this proved to be costly as it contained an O(n^3)
  18810. * complexity with regard to dynamic entries that blew up for very large
  18811. * projects.
  18812. *
  18813. * If we have an efficient way to do Set operations, an alternative approach
  18814. * would be to instead collect already loaded modules per dynamic entry. And as
  18815. * all chunks from the initial grouping would behave the same, we can instead
  18816. * collect already loaded chunks for a performance improvement.
  18817. *
  18818. * To do that efficiently, need
  18819. * - a Map of dynamic imports per dynamic entry, which contains all dynamic
  18820. * imports that can be triggered by a dynamic entry
  18821. * - a Map of static dependencies per entry
  18822. * - a Map of already loaded chunks per entry that we initially populate with
  18823. * empty Sets for static entries and Sets containing all entries for dynamic
  18824. * entries
  18825. *
  18826. * For efficient operations, we assign each entry a numerical index and
  18827. * represent Sets of Chunks as BigInt values where each chunk corresponds to a
  18828. * bit index. Then the last two maps can be represented as arrays of BigInt
  18829. * values.
  18830. *
  18831. * Then we iterate through each dynamic entry. We set the already loaded modules
  18832. * to the intersection of the previously already loaded modules with the union
  18833. * of the already loaded modules of that chunk with its static dependencies.
  18834. *
  18835. * If the already loaded modules changed, then we use the Map of dynamic imports
  18836. * per dynamic entry to marks all dynamic entry dependencies as "dirty" and put
  18837. * them back into the iteration. As an additional optimization, we note for
  18838. * each dynamic entry which dynamic dependent entries have changed and only
  18839. * intersect those entries again on subsequent interations.
  18840. *
  18841. * Then we remove the dynamic entries from the list of dependent entries for
  18842. * those chunks that are already loaded for that dynamic entry and create
  18843. * another round of chunks.
  18844. */
  18845. function getChunkAssignments(entries, manualChunkAliasByEntry, minChunkSize, log, isManualChunksFunctionForm, onlyExplicitManualChunks) {
  18846. const { chunkDefinitions, modulesInManualChunks } = getChunkDefinitionsFromManualChunks(manualChunkAliasByEntry, isManualChunksFunctionForm, onlyExplicitManualChunks);
  18847. const { allEntries, dependentEntriesByModule, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry, dynamicallyDependentEntriesByAwaitedDynamicEntry, awaitedDynamicImportsByEntry } = analyzeModuleGraph(entries);
  18848. // Each chunk is identified by its position in this array
  18849. const chunkAtoms = getChunksWithSameDependentEntries(getModulesWithDependentEntriesAndHandleTLACycles(dependentEntriesByModule, modulesInManualChunks, chunkDefinitions));
  18850. const staticDependencyAtomsByEntry = getStaticDependencyAtomsByEntry(allEntries, chunkAtoms);
  18851. // Warning: This will consume dynamicallyDependentEntriesByDynamicEntry.
  18852. // If we no longer want this, we should make a copy here.
  18853. const alreadyLoadedAtomsByEntry = getAlreadyLoadedAtomsByEntry(staticDependencyAtomsByEntry, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry, allEntries);
  18854. const awaitedAlreadyLoadedAtomsByEntry = getAlreadyLoadedAtomsByEntry(staticDependencyAtomsByEntry, dynamicallyDependentEntriesByAwaitedDynamicEntry, awaitedDynamicImportsByEntry, allEntries);
  18855. // This mutates the dependentEntries in chunkAtoms
  18856. removeUnnecessaryDependentEntries(chunkAtoms, alreadyLoadedAtomsByEntry, awaitedAlreadyLoadedAtomsByEntry);
  18857. const { chunks, sideEffectAtoms, sizeByAtom } = getChunksWithSameDependentEntriesAndCorrelatedAtoms(chunkAtoms, staticDependencyAtomsByEntry, alreadyLoadedAtomsByEntry, minChunkSize);
  18858. chunkDefinitions.push(...getOptimizedChunks(chunks, minChunkSize, sideEffectAtoms, sizeByAtom, log).map(({ modules }) => ({
  18859. alias: null,
  18860. modules
  18861. })));
  18862. return chunkDefinitions;
  18863. }
  18864. function getChunkDefinitionsFromManualChunks(manualChunkAliasByEntry, isManualChunksFunctionForm, onlyExplicitManualChunks) {
  18865. const modulesInManualChunks = new Set(manualChunkAliasByEntry.keys());
  18866. const manualChunkModulesByAlias = Object.create(null);
  18867. const sortedEntriesWithAlias = [...manualChunkAliasByEntry].sort(([entryA], [entryB]) => entryA.execIndex - entryB.execIndex);
  18868. for (const [entry, alias] of sortedEntriesWithAlias) {
  18869. if (isManualChunksFunctionForm && onlyExplicitManualChunks) {
  18870. (manualChunkModulesByAlias[alias] ||= []).push(entry);
  18871. }
  18872. else {
  18873. addStaticDependenciesToManualChunk(entry, (manualChunkModulesByAlias[alias] ||= []), modulesInManualChunks);
  18874. }
  18875. }
  18876. const manualChunks = Object.entries(manualChunkModulesByAlias);
  18877. const chunkDefinitions = new Array(manualChunks.length);
  18878. let index = 0;
  18879. for (const [alias, modules] of manualChunks) {
  18880. chunkDefinitions[index++] = { alias, modules };
  18881. }
  18882. return { chunkDefinitions, modulesInManualChunks };
  18883. }
  18884. function addStaticDependenciesToManualChunk(entry, manualChunkModules, modulesInManualChunks) {
  18885. const modulesToHandle = new Set([entry]);
  18886. for (const module of modulesToHandle) {
  18887. modulesInManualChunks.add(module);
  18888. manualChunkModules.push(module);
  18889. for (const dependency of module.dependencies) {
  18890. if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
  18891. modulesToHandle.add(dependency);
  18892. }
  18893. }
  18894. }
  18895. }
  18896. function analyzeModuleGraph(entries) {
  18897. const dynamicEntryModules = new Set();
  18898. const awaitedDynamicEntryModules = new Set();
  18899. const dependentEntriesByModule = new Map();
  18900. const allEntriesSet = new Set(entries);
  18901. const dynamicImportModulesByEntry = new Array(allEntriesSet.size);
  18902. const awaitedDynamicImportModulesByEntry = new Array(allEntriesSet.size);
  18903. let entryIndex = 0;
  18904. for (const currentEntry of allEntriesSet) {
  18905. const dynamicImportsForCurrentEntry = new Set();
  18906. const awaitedDynamicImportsForCurrentEntry = new Set();
  18907. dynamicImportModulesByEntry[entryIndex] = dynamicImportsForCurrentEntry;
  18908. awaitedDynamicImportModulesByEntry[entryIndex] = awaitedDynamicImportsForCurrentEntry;
  18909. const staticDependencies = new Set([currentEntry]);
  18910. for (const module of staticDependencies) {
  18911. getOrCreate(dependentEntriesByModule, module, (getNewSet)).add(entryIndex);
  18912. for (const dependency of module.getDependenciesToBeIncluded()) {
  18913. if (!(dependency instanceof ExternalModule)) {
  18914. staticDependencies.add(dependency);
  18915. }
  18916. }
  18917. for (const { node: { resolution } } of module.dynamicImports) {
  18918. if (resolution instanceof Module &&
  18919. resolution.includedDynamicImporters.length > 0 &&
  18920. !allEntriesSet.has(resolution)) {
  18921. dynamicEntryModules.add(resolution);
  18922. allEntriesSet.add(resolution);
  18923. dynamicImportsForCurrentEntry.add(resolution);
  18924. for (const includedTopLevelAwaitingDynamicImporter of resolution.includedTopLevelAwaitingDynamicImporters) {
  18925. if (staticDependencies.has(includedTopLevelAwaitingDynamicImporter)) {
  18926. awaitedDynamicEntryModules.add(resolution);
  18927. awaitedDynamicImportsForCurrentEntry.add(resolution);
  18928. break;
  18929. }
  18930. }
  18931. }
  18932. }
  18933. for (const dependency of module.implicitlyLoadedBefore) {
  18934. if (!allEntriesSet.has(dependency)) {
  18935. dynamicEntryModules.add(dependency);
  18936. allEntriesSet.add(dependency);
  18937. }
  18938. }
  18939. }
  18940. entryIndex++;
  18941. }
  18942. const allEntries = [...allEntriesSet];
  18943. const { awaitedDynamicEntries, awaitedDynamicImportsByEntry, dynamicEntries, dynamicImportsByEntry } = getDynamicEntries(allEntries, dynamicEntryModules, dynamicImportModulesByEntry, awaitedDynamicEntryModules, awaitedDynamicImportModulesByEntry);
  18944. return {
  18945. allEntries,
  18946. awaitedDynamicImportsByEntry,
  18947. dependentEntriesByModule,
  18948. dynamicallyDependentEntriesByAwaitedDynamicEntry: getDynamicallyDependentEntriesByDynamicEntry(dependentEntriesByModule, awaitedDynamicEntries, allEntries, dynamicEntry => dynamicEntry.includedTopLevelAwaitingDynamicImporters),
  18949. dynamicallyDependentEntriesByDynamicEntry: getDynamicallyDependentEntriesByDynamicEntry(dependentEntriesByModule, dynamicEntries, allEntries, dynamicEntry => dynamicEntry.includedDynamicImporters),
  18950. dynamicImportsByEntry
  18951. };
  18952. }
  18953. function getDynamicEntries(allEntries, dynamicEntryModules, dynamicImportModulesByEntry, awaitedDynamicEntryModules, awaitedDynamicImportModulesByEntry) {
  18954. const entryIndexByModule = new Map();
  18955. const dynamicEntries = new Set();
  18956. const awaitedDynamicEntries = new Set();
  18957. for (const [entryIndex, entry] of allEntries.entries()) {
  18958. entryIndexByModule.set(entry, entryIndex);
  18959. if (dynamicEntryModules.has(entry)) {
  18960. dynamicEntries.add(entryIndex);
  18961. }
  18962. if (awaitedDynamicEntryModules.has(entry)) {
  18963. awaitedDynamicEntries.add(entryIndex);
  18964. }
  18965. }
  18966. const dynamicImportsByEntry = getDynamicImportsByEntry(dynamicImportModulesByEntry, entryIndexByModule);
  18967. const awaitedDynamicImportsByEntry = getDynamicImportsByEntry(awaitedDynamicImportModulesByEntry, entryIndexByModule);
  18968. return {
  18969. awaitedDynamicEntries,
  18970. awaitedDynamicImportsByEntry,
  18971. dynamicEntries,
  18972. dynamicImportsByEntry
  18973. };
  18974. }
  18975. function getDynamicImportsByEntry(dynamicImportModulesByEntry, entryIndexByModule) {
  18976. const dynamicImportsByEntry = new Array(dynamicImportModulesByEntry.length);
  18977. let index = 0;
  18978. for (const dynamicImportModules of dynamicImportModulesByEntry) {
  18979. const dynamicImports = new Set();
  18980. for (const dynamicEntry of dynamicImportModules) {
  18981. dynamicImports.add(entryIndexByModule.get(dynamicEntry));
  18982. }
  18983. dynamicImportsByEntry[index++] = dynamicImports;
  18984. }
  18985. return dynamicImportsByEntry;
  18986. }
  18987. function getDynamicallyDependentEntriesByDynamicEntry(dependentEntriesByModule, dynamicEntries, allEntries, getDynamicImporters) {
  18988. const dynamicallyDependentEntriesByDynamicEntry = new Map();
  18989. for (const dynamicEntryIndex of dynamicEntries) {
  18990. const dynamicallyDependentEntries = getOrCreate(dynamicallyDependentEntriesByDynamicEntry, dynamicEntryIndex, (getNewSet));
  18991. const dynamicEntry = allEntries[dynamicEntryIndex];
  18992. for (const importer of concatLazy([
  18993. getDynamicImporters(dynamicEntry),
  18994. dynamicEntry.implicitlyLoadedAfter
  18995. ])) {
  18996. const importerEntries = dependentEntriesByModule.get(importer);
  18997. if (!importerEntries) {
  18998. continue;
  18999. }
  19000. for (const entry of importerEntries) {
  19001. dynamicallyDependentEntries.add(entry);
  19002. }
  19003. }
  19004. }
  19005. return dynamicallyDependentEntriesByDynamicEntry;
  19006. }
  19007. function getChunksWithSameDependentEntries(modulesWithDependentEntries) {
  19008. const chunkModules = Object.create(null);
  19009. for (const { dependentEntries, modules } of modulesWithDependentEntries) {
  19010. let chunkSignature = 0n;
  19011. for (const entryIndex of dependentEntries) {
  19012. chunkSignature |= 1n << BigInt(entryIndex);
  19013. }
  19014. (chunkModules[String(chunkSignature)] ||= {
  19015. dependentEntries: new Set(dependentEntries),
  19016. modules: []
  19017. }).modules.push(...modules);
  19018. }
  19019. return Object.values(chunkModules);
  19020. }
  19021. function* getModulesWithDependentEntriesAndHandleTLACycles(dependentEntriesByModule, modulesInManualChunks, chunkDefinitions) {
  19022. for (const [module, dependentEntries] of dependentEntriesByModule) {
  19023. if (!modulesInManualChunks.has(module)) {
  19024. if (module.cycles.size > 0 && module.includedTopLevelAwaitingDynamicImporters.size > 0) {
  19025. chunkDefinitions.push({
  19026. alias: null,
  19027. modules: [module]
  19028. });
  19029. continue;
  19030. }
  19031. yield { dependentEntries, modules: [module] };
  19032. }
  19033. }
  19034. }
  19035. function getStaticDependencyAtomsByEntry(allEntries, chunkAtoms) {
  19036. // The indices correspond to the indices in allEntries. The atoms correspond
  19037. // to bits in the bigint values where chunk 0 is the lowest bit.
  19038. const staticDependencyAtomsByEntry = allEntries.map(() => 0n);
  19039. // This toggles the bits for each atom that is a dependency of an entry
  19040. let atomMask = 1n;
  19041. for (const { dependentEntries } of chunkAtoms) {
  19042. for (const entryIndex of dependentEntries) {
  19043. staticDependencyAtomsByEntry[entryIndex] |= atomMask;
  19044. }
  19045. atomMask <<= 1n;
  19046. }
  19047. return staticDependencyAtomsByEntry;
  19048. }
  19049. // Warning: This will consume dynamicallyDependentEntriesByDynamicEntry.
  19050. function getAlreadyLoadedAtomsByEntry(staticDependencyAtomsByEntry, dynamicallyDependentEntriesByDynamicEntry, dynamicImportsByEntry, allEntries) {
  19051. // Dynamic entries have all atoms as already loaded initially because we then
  19052. // intersect with the static dependency atoms of all dynamic importers.
  19053. // Static entries cannot have already loaded atoms.
  19054. const alreadyLoadedAtomsByEntry = allEntries.map((_entry, entryIndex) => dynamicallyDependentEntriesByDynamicEntry.has(entryIndex) ? -1n : 0n);
  19055. for (const [dynamicEntryIndex, dynamicallyDependentEntries] of dynamicallyDependentEntriesByDynamicEntry) {
  19056. // We delete here so that they can be added again if necessary to be handled
  19057. // again by the loop
  19058. dynamicallyDependentEntriesByDynamicEntry.delete(dynamicEntryIndex);
  19059. const knownLoadedAtoms = alreadyLoadedAtomsByEntry[dynamicEntryIndex];
  19060. let updatedLoadedAtoms = knownLoadedAtoms;
  19061. for (const entryIndex of dynamicallyDependentEntries) {
  19062. updatedLoadedAtoms &=
  19063. staticDependencyAtomsByEntry[entryIndex] | alreadyLoadedAtomsByEntry[entryIndex];
  19064. }
  19065. // If the knownLoadedAtoms changed, all dependent dynamic entries need to be
  19066. // updated again
  19067. if (updatedLoadedAtoms !== knownLoadedAtoms) {
  19068. alreadyLoadedAtomsByEntry[dynamicEntryIndex] = updatedLoadedAtoms;
  19069. for (const dynamicImport of dynamicImportsByEntry[dynamicEntryIndex]) {
  19070. // If this adds an entry that was deleted before, it will be handled
  19071. // again. This is the reason why we delete every entry from this map
  19072. // that we processed.
  19073. getOrCreate(dynamicallyDependentEntriesByDynamicEntry, dynamicImport, (getNewSet)).add(dynamicEntryIndex);
  19074. }
  19075. }
  19076. }
  19077. return alreadyLoadedAtomsByEntry;
  19078. }
  19079. /**
  19080. * This removes all unnecessary dynamic entries from the dependentEntries in its
  19081. * first argument if a chunk is already loaded without that entry.
  19082. */
  19083. function removeUnnecessaryDependentEntries(chunkAtoms, alreadyLoadedAtomsByEntry, awaitedAlreadyLoadedAtomsByEntry) {
  19084. // Remove entries from dependent entries if a chunk is already loaded without
  19085. // that entry. Do not remove already loaded atoms where some dynamic imports
  19086. // are awaited to avoid cycles in the output.
  19087. let chunkMask = 1n;
  19088. for (const { dependentEntries } of chunkAtoms) {
  19089. for (const entryIndex of dependentEntries) {
  19090. if ((alreadyLoadedAtomsByEntry[entryIndex] & chunkMask) === chunkMask &&
  19091. (awaitedAlreadyLoadedAtomsByEntry[entryIndex] & chunkMask) === 0n) {
  19092. dependentEntries.delete(entryIndex);
  19093. }
  19094. }
  19095. chunkMask <<= 1n;
  19096. }
  19097. }
  19098. function getChunksWithSameDependentEntriesAndCorrelatedAtoms(chunkAtoms, staticDependencyAtomsByEntry, alreadyLoadedAtomsByEntry, minChunkSize) {
  19099. const chunksBySignature = Object.create(null);
  19100. const chunkByModule = new Map();
  19101. const sizeByAtom = new Array(chunkAtoms.length);
  19102. let sideEffectAtoms = 0n;
  19103. let atomMask = 1n;
  19104. let index = 0;
  19105. for (const { dependentEntries, modules } of chunkAtoms) {
  19106. let chunkSignature = 0n;
  19107. let correlatedAtoms = -1n;
  19108. for (const entryIndex of dependentEntries) {
  19109. chunkSignature |= 1n << BigInt(entryIndex);
  19110. // Correlated atoms are the atoms that are guaranteed to be loaded as
  19111. // well when a given atom is loaded. It is the intersection of the already
  19112. // loaded modules of each chunk merged with its static dependencies.
  19113. correlatedAtoms &=
  19114. staticDependencyAtomsByEntry[entryIndex] | alreadyLoadedAtomsByEntry[entryIndex];
  19115. }
  19116. const chunk = (chunksBySignature[String(chunkSignature)] ||= {
  19117. containedAtoms: 0n,
  19118. correlatedAtoms,
  19119. dependencies: new Set(),
  19120. dependentChunks: new Set(),
  19121. dependentEntries: new Set(dependentEntries),
  19122. modules: [],
  19123. pure: true,
  19124. size: 0
  19125. });
  19126. let atomSize = 0;
  19127. let pure = true;
  19128. for (const module of modules) {
  19129. chunkByModule.set(module, chunk);
  19130. // Unfortunately, we cannot take tree-shaking into account here because
  19131. // rendering did not happen yet, but we can detect empty modules
  19132. if (module.isIncluded()) {
  19133. pure &&= !module.hasEffects();
  19134. // we use a trivial size for the default minChunkSize to improve
  19135. // performance
  19136. atomSize += minChunkSize > 1 ? module.estimateSize() : 1;
  19137. }
  19138. }
  19139. if (!pure) {
  19140. sideEffectAtoms |= atomMask;
  19141. }
  19142. sizeByAtom[index++] = atomSize;
  19143. chunk.containedAtoms |= atomMask;
  19144. chunk.modules.push(...modules);
  19145. chunk.pure &&= pure;
  19146. chunk.size += atomSize;
  19147. atomMask <<= 1n;
  19148. }
  19149. const chunks = Object.values(chunksBySignature);
  19150. sideEffectAtoms |= addChunkDependenciesAndGetExternalSideEffectAtoms(chunks, chunkByModule, atomMask);
  19151. return { chunks, sideEffectAtoms, sizeByAtom };
  19152. }
  19153. function addChunkDependenciesAndGetExternalSideEffectAtoms(chunks, chunkByModule, nextAvailableAtomMask) {
  19154. const signatureByExternalModule = new Map();
  19155. let externalSideEffectAtoms = 0n;
  19156. for (const chunk of chunks) {
  19157. const { dependencies, modules } = chunk;
  19158. for (const module of modules) {
  19159. for (const dependency of module.getDependenciesToBeIncluded()) {
  19160. if (dependency instanceof ExternalModule) {
  19161. if (dependency.info.moduleSideEffects) {
  19162. const signature = getOrCreate(signatureByExternalModule, dependency, () => {
  19163. const signature = nextAvailableAtomMask;
  19164. nextAvailableAtomMask <<= 1n;
  19165. externalSideEffectAtoms |= signature;
  19166. return signature;
  19167. });
  19168. chunk.containedAtoms |= signature;
  19169. chunk.correlatedAtoms |= signature;
  19170. }
  19171. }
  19172. else {
  19173. const dependencyChunk = chunkByModule.get(dependency);
  19174. if (dependencyChunk && dependencyChunk !== chunk) {
  19175. dependencies.add(dependencyChunk);
  19176. dependencyChunk.dependentChunks.add(chunk);
  19177. }
  19178. }
  19179. }
  19180. }
  19181. }
  19182. return externalSideEffectAtoms;
  19183. }
  19184. /**
  19185. * This function tries to get rid of small chunks by merging them with other
  19186. * chunks.
  19187. *
  19188. * We can only merge chunks safely if after the merge, loading any entry point
  19189. * in any allowed order will not trigger side effects that should not have been
  19190. * triggered. While side effects are usually things like global function calls,
  19191. * global variable mutations or potentially thrown errors, details do not
  19192. * matter here, and we just discern chunks without side effects (pure chunks)
  19193. * from other chunks.
  19194. *
  19195. * As a first step, we assign each pre-generated chunk with side effects a
  19196. * label. I.e. we have side effect "A" if the non-pure chunk "A" is loaded.
  19197. *
  19198. * Now to determine the side effects of loading a chunk, one also has to take
  19199. * the side effects of its dependencies into account. So if A depends on B
  19200. * (A -> B) and both have side effects, loading A triggers effects AB.
  19201. *
  19202. * Now from the previous step we know that each chunk is uniquely determine by
  19203. * the entry points that depend on it and cause it to load, which we will call
  19204. * its dependent entry points.
  19205. *
  19206. * E.g. if X -> A and Y -> A, then the dependent entry points of A are XY.
  19207. * Starting from that idea, we can determine a set of chunks—and thus a set
  19208. * of side effects—that must have been triggered if a certain chunk has been
  19209. * loaded. Basically, it is the intersection of all chunks loaded by the
  19210. * dependent entry points of a given chunk. We call the corresponding side
  19211. * effects the correlated side effects of that chunk.
  19212. *
  19213. * Example:
  19214. * X -> ABC, Y -> ADE, A-> F, B -> D
  19215. * Then taking dependencies into account, X -> ABCDF, Y -> ADEF
  19216. * The intersection is ADF. So we know that when A is loaded, D and F must also
  19217. * be in memory even though neither D nor A is a dependency of the other.
  19218. * If all have side effects, we call ADF the correlated side effects of A. The
  19219. * correlated side effects need to remain constant when merging chunks.
  19220. *
  19221. * In contrast, we have the dependency side effects of A, which represents
  19222. * the side effects we trigger if we directly load A. In this example, the
  19223. * dependency side effects are AF.
  19224. * For entry chunks, dependency and correlated side effects are the same.
  19225. *
  19226. * With these concepts, merging chunks is allowed if the correlated side
  19227. * effects of each entry do not change. Thus, we are allowed to merge two
  19228. * chunks if
  19229. *
  19230. * a) the dependency side effects of each chunk are a subset of the correlated
  19231. * side effects of the other chunk, so no additional side effects are
  19232. * triggered for any entry, or
  19233. * b) The dependent entry points of chunk A are a subset of the dependent entry
  19234. * points of chunk B while the dependency side effects of A are a subset of
  19235. * the correlated side effects of B. Because in that scenario, whenever A is
  19236. * loaded, B is loaded as well. But there are cases when B is loaded where A
  19237. * is not loaded. So if we merge the chunks, all dependency side effects of
  19238. * A will be added to the correlated side effects of B, and as the latter is
  19239. * not allowed to change, the former need to be a subset of the latter.
  19240. *
  19241. * Another consideration when merging small chunks into other chunks is to
  19242. * avoid
  19243. * that too much additional code is loaded. This is achieved when the dependent
  19244. * entries of the small chunk are a subset of the dependent entries of the
  19245. * other
  19246. * chunk. Because then when the small chunk is loaded, the other chunk was
  19247. * loaded/in memory anyway, so at most when the other chunk is loaded, the
  19248. * additional size of the small chunk is loaded unnecessarily.
  19249. *
  19250. * So the algorithm performs merges in two passes:
  19251. *
  19252. * 1. First we try to merge small chunks A only into other chunks B if the
  19253. * dependent entries of A are a subset of the dependent entries of B and the
  19254. * dependency side effects of A are a subset of the correlated side effects
  19255. * of B.
  19256. * 2. Only then for all remaining small chunks, we look for arbitrary merges
  19257. * following the rule (a), starting with the smallest chunks to look for
  19258. * possible merge targets.
  19259. */
  19260. function getOptimizedChunks(chunks, minChunkSize, sideEffectAtoms, sizeByAtom, log) {
  19261. timeStart('optimize chunks', 3);
  19262. const chunkPartition = getPartitionedChunks(chunks, minChunkSize);
  19263. if (!chunkPartition) {
  19264. timeEnd('optimize chunks', 3);
  19265. return chunks; // the actual modules
  19266. }
  19267. if (minChunkSize > 1) {
  19268. log('info', logOptimizeChunkStatus(chunks.length, chunkPartition.small.size, 'Initially'));
  19269. }
  19270. mergeChunks(chunkPartition, minChunkSize, sideEffectAtoms, sizeByAtom);
  19271. if (minChunkSize > 1) {
  19272. log('info', logOptimizeChunkStatus(chunkPartition.small.size + chunkPartition.big.size, chunkPartition.small.size, 'After merging chunks'));
  19273. }
  19274. timeEnd('optimize chunks', 3);
  19275. return [...chunkPartition.small, ...chunkPartition.big];
  19276. }
  19277. function getPartitionedChunks(chunks, minChunkSize) {
  19278. const smallChunks = [];
  19279. const bigChunks = [];
  19280. for (const chunk of chunks) {
  19281. (chunk.size < minChunkSize ? smallChunks : bigChunks).push(chunk);
  19282. }
  19283. if (smallChunks.length === 0) {
  19284. return null;
  19285. }
  19286. smallChunks.sort(compareChunkSize);
  19287. bigChunks.sort(compareChunkSize);
  19288. return {
  19289. big: new Set(bigChunks),
  19290. small: new Set(smallChunks)
  19291. };
  19292. }
  19293. function compareChunkSize({ size: sizeA }, { size: sizeB }) {
  19294. return sizeA - sizeB;
  19295. }
  19296. function mergeChunks(chunkPartition, minChunkSize, sideEffectAtoms, sizeByAtom) {
  19297. const { small } = chunkPartition;
  19298. for (const mergedChunk of small) {
  19299. const bestTargetChunk = findBestMergeTarget(mergedChunk, chunkPartition, sideEffectAtoms, sizeByAtom,
  19300. // In the default case, we do not accept size increases
  19301. minChunkSize <= 1 ? 1 : Infinity);
  19302. if (bestTargetChunk) {
  19303. const { containedAtoms, correlatedAtoms, modules, pure, size } = mergedChunk;
  19304. small.delete(mergedChunk);
  19305. getChunksInPartition(bestTargetChunk, minChunkSize, chunkPartition).delete(bestTargetChunk);
  19306. bestTargetChunk.modules.push(...modules);
  19307. bestTargetChunk.size += size;
  19308. bestTargetChunk.pure &&= pure;
  19309. const { dependencies, dependentChunks, dependentEntries } = bestTargetChunk;
  19310. bestTargetChunk.correlatedAtoms &= correlatedAtoms;
  19311. bestTargetChunk.containedAtoms |= containedAtoms;
  19312. for (const entry of mergedChunk.dependentEntries) {
  19313. dependentEntries.add(entry);
  19314. }
  19315. for (const dependency of mergedChunk.dependencies) {
  19316. dependencies.add(dependency);
  19317. dependency.dependentChunks.delete(mergedChunk);
  19318. dependency.dependentChunks.add(bestTargetChunk);
  19319. }
  19320. for (const dependentChunk of mergedChunk.dependentChunks) {
  19321. dependentChunks.add(dependentChunk);
  19322. dependentChunk.dependencies.delete(mergedChunk);
  19323. dependentChunk.dependencies.add(bestTargetChunk);
  19324. }
  19325. dependencies.delete(bestTargetChunk);
  19326. dependentChunks.delete(bestTargetChunk);
  19327. getChunksInPartition(bestTargetChunk, minChunkSize, chunkPartition).add(bestTargetChunk);
  19328. }
  19329. }
  19330. }
  19331. function findBestMergeTarget(mergedChunk, { big, small }, sideEffectAtoms, sizeByAtom, smallestAdditionalSize) {
  19332. let bestTargetChunk = null;
  19333. // In the default case, we do not accept size increases
  19334. for (const targetChunk of concatLazy([small, big])) {
  19335. if (mergedChunk === targetChunk)
  19336. continue;
  19337. const additionalSizeAfterMerge = getAdditionalSizeAfterMerge(mergedChunk, targetChunk, smallestAdditionalSize, sideEffectAtoms, sizeByAtom);
  19338. if (additionalSizeAfterMerge < smallestAdditionalSize) {
  19339. bestTargetChunk = targetChunk;
  19340. if (additionalSizeAfterMerge === 0)
  19341. break;
  19342. smallestAdditionalSize = additionalSizeAfterMerge;
  19343. }
  19344. }
  19345. return bestTargetChunk;
  19346. }
  19347. /**
  19348. * Determine the additional unused code size that would be added by merging the
  19349. * two chunks. This is not an exact measurement but rather an upper bound. If
  19350. * the merge produces cycles or adds non-correlated side effects, `Infinity`
  19351. * is returned.
  19352. * Merging will not produce cycles if none of the direct non-merged
  19353. * dependencies of a chunk have the other chunk as a transitive dependency.
  19354. */
  19355. function getAdditionalSizeAfterMerge(mergedChunk, targetChunk,
  19356. // The maximum additional unused code size allowed to be added by the merge,
  19357. // taking dependencies into account, needs to be below this number
  19358. currentAdditionalSize, sideEffectAtoms, sizeByAtom) {
  19359. const firstSize = getAdditionalSizeIfNoTransitiveDependencyOrNonCorrelatedSideEffect(mergedChunk, targetChunk, currentAdditionalSize, sideEffectAtoms, sizeByAtom);
  19360. return firstSize < currentAdditionalSize
  19361. ? firstSize +
  19362. getAdditionalSizeIfNoTransitiveDependencyOrNonCorrelatedSideEffect(targetChunk, mergedChunk, currentAdditionalSize - firstSize, sideEffectAtoms, sizeByAtom)
  19363. : Infinity;
  19364. }
  19365. function getAdditionalSizeIfNoTransitiveDependencyOrNonCorrelatedSideEffect(dependentChunk, dependencyChunk, currentAdditionalSize, sideEffectAtoms, sizeByAtom) {
  19366. const { correlatedAtoms } = dependencyChunk;
  19367. let dependencyAtoms = dependentChunk.containedAtoms;
  19368. const dependentContainedSideEffects = dependencyAtoms & sideEffectAtoms;
  19369. if ((correlatedAtoms & dependentContainedSideEffects) !== dependentContainedSideEffects) {
  19370. return Infinity;
  19371. }
  19372. const chunksToCheck = new Set(dependentChunk.dependencies);
  19373. for (const { dependencies, containedAtoms } of chunksToCheck) {
  19374. dependencyAtoms |= containedAtoms;
  19375. const containedSideEffects = containedAtoms & sideEffectAtoms;
  19376. if ((correlatedAtoms & containedSideEffects) !== containedSideEffects) {
  19377. return Infinity;
  19378. }
  19379. for (const dependency of dependencies) {
  19380. if (dependency === dependencyChunk) {
  19381. return Infinity;
  19382. }
  19383. chunksToCheck.add(dependency);
  19384. }
  19385. }
  19386. return getAtomsSizeIfBelowLimit(dependencyAtoms & ~correlatedAtoms, currentAdditionalSize, sizeByAtom);
  19387. }
  19388. function getAtomsSizeIfBelowLimit(atoms, currentAdditionalSize, sizeByAtom) {
  19389. let size = 0;
  19390. let atomIndex = 0;
  19391. let atomSignature = 1n;
  19392. const { length } = sizeByAtom;
  19393. for (; atomIndex < length; atomIndex++) {
  19394. if ((atoms & atomSignature) === atomSignature) {
  19395. size += sizeByAtom[atomIndex];
  19396. }
  19397. atomSignature <<= 1n;
  19398. if (size >= currentAdditionalSize) {
  19399. return Infinity;
  19400. }
  19401. }
  19402. return size;
  19403. }
  19404. function getChunksInPartition(chunk, minChunkSize, chunkPartition) {
  19405. return chunk.size < minChunkSize ? chunkPartition.small : chunkPartition.big;
  19406. }
  19407. // ported from https://github.com/substack/node-commondir
  19408. function commondir(files) {
  19409. if (files.length === 0)
  19410. return '/';
  19411. if (files.length === 1)
  19412. return dirname(files[0]);
  19413. const commonSegments = files.slice(1).reduce((commonSegments, file) => {
  19414. const pathSegments = file.split(/\/+|\\+/);
  19415. let index;
  19416. for (index = 0; commonSegments[index] === pathSegments[index] &&
  19417. index < Math.min(commonSegments.length, pathSegments.length); index++)
  19418. ;
  19419. return commonSegments.slice(0, index);
  19420. }, files[0].split(/\/+|\\+/));
  19421. // Windows correctly handles paths with forward-slashes
  19422. return commonSegments.length > 1 ? commonSegments.join('/') : '/';
  19423. }
  19424. const compareExecIndex = (unitA, unitB) => unitA.execIndex > unitB.execIndex ? 1 : -1;
  19425. function sortByExecutionOrder(units) {
  19426. units.sort(compareExecIndex);
  19427. }
  19428. // This process is currently faulty in so far as it only takes the first entry
  19429. // module into account and assumes that dynamic imports are imported in a
  19430. // certain order.
  19431. // A better algorithm would follow every possible execution path and mark which
  19432. // modules are executed before or after which other modules. THen the chunking
  19433. // would need to take care that in each chunk, all modules are always executed
  19434. // in the same sequence.
  19435. function analyseModuleExecution(entryModules) {
  19436. let nextExecIndex = 0;
  19437. const cyclePaths = [];
  19438. const analysedModules = new Set();
  19439. const dynamicImports = new Set();
  19440. const parents = new Map();
  19441. const orderedModules = [];
  19442. const handleSyncLoadedModule = (module, parent) => {
  19443. if (parents.has(module)) {
  19444. if (!analysedModules.has(module)) {
  19445. cyclePaths.push(getCyclePath(module, parent, parents));
  19446. }
  19447. return;
  19448. }
  19449. parents.set(module, parent);
  19450. analyseModule(module);
  19451. };
  19452. const analyseModule = (module) => {
  19453. if (module instanceof Module) {
  19454. for (const dependency of module.dependencies) {
  19455. handleSyncLoadedModule(dependency, module);
  19456. }
  19457. for (const dependency of module.implicitlyLoadedBefore) {
  19458. dynamicImports.add(dependency);
  19459. }
  19460. for (const { node: { resolution, scope } } of module.dynamicImports) {
  19461. if (resolution instanceof Module) {
  19462. if (scope.context.usesTopLevelAwait) {
  19463. handleSyncLoadedModule(resolution, module);
  19464. }
  19465. else {
  19466. dynamicImports.add(resolution);
  19467. }
  19468. }
  19469. }
  19470. orderedModules.push(module);
  19471. }
  19472. module.execIndex = nextExecIndex++;
  19473. analysedModules.add(module);
  19474. };
  19475. for (const currentEntry of entryModules) {
  19476. if (!parents.has(currentEntry)) {
  19477. parents.set(currentEntry, null);
  19478. analyseModule(currentEntry);
  19479. }
  19480. }
  19481. for (const currentEntry of dynamicImports) {
  19482. if (!parents.has(currentEntry)) {
  19483. parents.set(currentEntry, null);
  19484. analyseModule(currentEntry);
  19485. }
  19486. }
  19487. return { cyclePaths, orderedModules };
  19488. }
  19489. function getCyclePath(module, parent, parents) {
  19490. const cycleSymbol = Symbol(module.id);
  19491. const path = [module.id];
  19492. let nextModule = parent;
  19493. module.cycles.add(cycleSymbol);
  19494. while (nextModule !== module) {
  19495. nextModule.cycles.add(cycleSymbol);
  19496. path.push(nextModule.id);
  19497. nextModule = parents.get(nextModule);
  19498. }
  19499. path.push(path[0]);
  19500. path.reverse();
  19501. return path;
  19502. }
  19503. function getGenerateCodeSnippets({ compact, generatedCode: { arrowFunctions, constBindings, objectShorthand, reservedNamesAsProps } }) {
  19504. const { _, n, s } = compact ? { _: '', n: '', s: '' } : { _: ' ', n: '\n', s: ';' };
  19505. const cnst = constBindings ? 'const' : 'var';
  19506. const getNonArrowFunctionIntro = (parameters, { isAsync, name }) => `${isAsync ? `async ` : ''}function${name ? ` ${name}` : ''}${_}(${parameters.join(`,${_}`)})${_}`;
  19507. const getFunctionIntro = arrowFunctions
  19508. ? (parameters, { isAsync, name }) => {
  19509. const singleParameter = parameters.length === 1;
  19510. const asyncString = isAsync ? `async${singleParameter ? ' ' : _}` : '';
  19511. return `${name ? `${cnst} ${name}${_}=${_}` : ''}${asyncString}${singleParameter ? parameters[0] : `(${parameters.join(`,${_}`)})`}${_}=>${_}`;
  19512. }
  19513. : getNonArrowFunctionIntro;
  19514. const getDirectReturnFunction = (parameters, { functionReturn, lineBreakIndent, name }) => [
  19515. `${getFunctionIntro(parameters, {
  19516. isAsync: false,
  19517. name
  19518. })}${arrowFunctions
  19519. ? lineBreakIndent
  19520. ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}`
  19521. : ''
  19522. : `{${lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _}${functionReturn ? 'return ' : ''}`}`,
  19523. arrowFunctions
  19524. ? `${name ? ';' : ''}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : ''}`
  19525. : `${s}${lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`
  19526. ];
  19527. const isValidPropertyName = reservedNamesAsProps
  19528. ? (name) => VALID_IDENTIFIER_REGEXP.test(name)
  19529. : (name) => !RESERVED_NAMES.has(name) && VALID_IDENTIFIER_REGEXP.test(name);
  19530. return {
  19531. _,
  19532. cnst,
  19533. getDirectReturnFunction,
  19534. getDirectReturnIifeLeft: (parameters, returned, { needsArrowReturnParens, needsWrappedFunction }) => {
  19535. const [left, right] = getDirectReturnFunction(parameters, {
  19536. functionReturn: true,
  19537. lineBreakIndent: null,
  19538. name: null
  19539. });
  19540. return `${wrapIfNeeded(`${left}${wrapIfNeeded(returned, arrowFunctions && needsArrowReturnParens)}${right}`, arrowFunctions || needsWrappedFunction)}(`;
  19541. },
  19542. getFunctionIntro,
  19543. getNonArrowFunctionIntro,
  19544. getObject(fields, { lineBreakIndent }) {
  19545. const prefix = lineBreakIndent ? `${n}${lineBreakIndent.base}${lineBreakIndent.t}` : _;
  19546. return `{${fields
  19547. .map(([key, value]) => {
  19548. if (key === null)
  19549. return `${prefix}${value}`;
  19550. const keyInObject = stringifyObjectKeyIfNeeded(key);
  19551. return key === value && objectShorthand && key === keyInObject
  19552. ? prefix + key
  19553. : `${prefix}${keyInObject}:${_}${value}`;
  19554. })
  19555. .join(`,`)}${fields.length === 0 ? '' : lineBreakIndent ? `${n}${lineBreakIndent.base}` : _}}`;
  19556. },
  19557. getPropertyAccess: (name) => isValidPropertyName(name) ? `.${name}` : `[${JSON.stringify(name)}]`,
  19558. n,
  19559. s
  19560. };
  19561. }
  19562. const wrapIfNeeded = (code, needsParens) => needsParens ? `(${code})` : code;
  19563. class Source {
  19564. constructor(filename, content) {
  19565. this.isOriginal = true;
  19566. this.filename = filename;
  19567. this.content = content;
  19568. }
  19569. traceSegment(line, column, name) {
  19570. return { column, line, name, source: this };
  19571. }
  19572. }
  19573. class Link {
  19574. constructor(map, sources) {
  19575. this.sources = sources;
  19576. this.names = map.names;
  19577. this.mappings = map.mappings;
  19578. }
  19579. traceMappings() {
  19580. const sources = [];
  19581. const sourceIndexMap = new Map();
  19582. const sourcesContent = [];
  19583. const names = [];
  19584. const nameIndexMap = new Map();
  19585. const mappings = [];
  19586. for (const line of this.mappings) {
  19587. const tracedLine = [];
  19588. for (const segment of line) {
  19589. if (segment.length === 1)
  19590. continue;
  19591. const source = this.sources[segment[1]];
  19592. if (!source)
  19593. continue;
  19594. const traced = source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : '');
  19595. if (traced) {
  19596. const { column, line, name, source: { content, filename } } = traced;
  19597. let sourceIndex = sourceIndexMap.get(filename);
  19598. if (sourceIndex === undefined) {
  19599. sourceIndex = sources.length;
  19600. sources.push(filename);
  19601. sourceIndexMap.set(filename, sourceIndex);
  19602. sourcesContent[sourceIndex] = content;
  19603. }
  19604. else if (sourcesContent[sourceIndex] == null) {
  19605. sourcesContent[sourceIndex] = content;
  19606. }
  19607. else if (content != null && sourcesContent[sourceIndex] !== content) {
  19608. return error(logConflictingSourcemapSources(filename));
  19609. }
  19610. const tracedSegment = [segment[0], sourceIndex, line, column];
  19611. if (name) {
  19612. let nameIndex = nameIndexMap.get(name);
  19613. if (nameIndex === undefined) {
  19614. nameIndex = names.length;
  19615. names.push(name);
  19616. nameIndexMap.set(name, nameIndex);
  19617. }
  19618. tracedSegment[4] = nameIndex;
  19619. }
  19620. tracedLine.push(tracedSegment);
  19621. }
  19622. }
  19623. mappings.push(tracedLine);
  19624. }
  19625. return { mappings, names, sources, sourcesContent };
  19626. }
  19627. traceSegment(line, column, name) {
  19628. const segments = this.mappings[line];
  19629. if (!segments)
  19630. return null;
  19631. // binary search through segments for the given column
  19632. let searchStart = 0;
  19633. const lastSegmentIndex = segments.length - 1;
  19634. let searchEnd = lastSegmentIndex;
  19635. while (searchStart <= searchEnd) {
  19636. const m = (searchStart + searchEnd) >> 1;
  19637. let segment = segments[m];
  19638. // If a sourcemap does not have sufficient resolution to contain a
  19639. // necessary mapping, e.g. because it only contains line information or
  19640. // the column is not precise (e.g. the sourcemap is generated by esbuild, segment[0] may be shorter than the location of the first letter),
  19641. // we approximate by finding the closest segment whose segment[0] is less than the given column
  19642. if (segment[0] !== column && searchStart === searchEnd) {
  19643. const approximatedSegmentIndex = segments[searchStart][0] > column ? Math.max(0, searchStart - 1) : searchStart;
  19644. segment = segments[approximatedSegmentIndex];
  19645. }
  19646. if (segment[0] === column || searchStart === searchEnd) {
  19647. if (segment.length == 1)
  19648. return null;
  19649. const source = this.sources[segment[1]];
  19650. if (!source)
  19651. return null;
  19652. return source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : name);
  19653. }
  19654. if (segment[0] > column) {
  19655. searchEnd = m - 1;
  19656. }
  19657. else {
  19658. searchStart = m + 1;
  19659. }
  19660. }
  19661. return null;
  19662. }
  19663. }
  19664. function getLinkMap(log) {
  19665. return function linkMap(source, map) {
  19666. if (!map.missing) {
  19667. return new Link(map, [source]);
  19668. }
  19669. log(LOGLEVEL_WARN, logSourcemapBroken(map.plugin));
  19670. return new Link({
  19671. mappings: [],
  19672. names: []
  19673. }, [source]);
  19674. };
  19675. }
  19676. function getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, linkMap) {
  19677. let source;
  19678. if (originalSourcemap) {
  19679. const sources = originalSourcemap.sources;
  19680. const sourcesContent = originalSourcemap.sourcesContent || [];
  19681. const directory = dirname(id) || '.';
  19682. const sourceRoot = originalSourcemap.sourceRoot || '.';
  19683. const baseSources = sources.map((source, index) => new Source(resolve$1(directory, sourceRoot, source), sourcesContent[index]));
  19684. source = new Link(originalSourcemap, baseSources);
  19685. }
  19686. else {
  19687. source = new Source(id, originalCode);
  19688. }
  19689. return sourcemapChain.reduce(linkMap, source);
  19690. }
  19691. function collapseSourcemaps(file, map, modules, bundleSourcemapChain, excludeContent, log) {
  19692. const linkMap = getLinkMap(log);
  19693. const moduleSources = modules
  19694. .filter(module => !module.excludeFromSourcemap)
  19695. .map(module => getCollapsedSourcemap(module.id, module.originalCode, module.originalSourcemap, module.sourcemapChain, linkMap));
  19696. const link = new Link(map, moduleSources);
  19697. const source = bundleSourcemapChain.reduce(linkMap, link);
  19698. let { sources, sourcesContent, names, mappings } = source.traceMappings();
  19699. if (file) {
  19700. const directory = dirname(file);
  19701. sources = sources.map((source) => relative(directory, source));
  19702. file = basename(file);
  19703. }
  19704. for (const module of modules) {
  19705. resetSourcemapCache(module.originalSourcemap, module.sourcemapChain);
  19706. }
  19707. return new SourceMap({
  19708. file,
  19709. mappings,
  19710. names,
  19711. sources,
  19712. sourcesContent: excludeContent ? undefined : sourcesContent
  19713. });
  19714. }
  19715. function collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, log) {
  19716. if (sourcemapChain.length === 0) {
  19717. return originalSourcemap;
  19718. }
  19719. const source = getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, getLinkMap(log));
  19720. const map = source.traceMappings();
  19721. return decodedSourcemap({ version: 3, ...map });
  19722. }
  19723. let textEncoder;
  19724. const getHash64 = input => xxhashBase64Url(ensureBuffer(input));
  19725. const getHash36 = input => xxhashBase36(ensureBuffer(input));
  19726. const getHash16 = input => xxhashBase16(ensureBuffer(input));
  19727. const hasherByType = {
  19728. base36: getHash36,
  19729. base64: getHash64,
  19730. hex: getHash16
  19731. };
  19732. function ensureBuffer(input) {
  19733. if (typeof input === 'string') {
  19734. if (typeof Buffer === 'undefined') {
  19735. textEncoder ??= new TextEncoder();
  19736. return textEncoder.encode(input);
  19737. }
  19738. return Buffer.from(input);
  19739. }
  19740. return input;
  19741. }
  19742. // this looks ridiculous, but it prevents sourcemap tooling from mistaking
  19743. // this for an actual sourceMappingURL
  19744. let SOURCEMAPPING_URL = 'sourceMa';
  19745. SOURCEMAPPING_URL += 'ppingURL';
  19746. async function renderChunks(chunks, bundle, pluginDriver, outputOptions, log) {
  19747. timeStart('render chunks', 2);
  19748. reserveEntryChunksInBundle(chunks);
  19749. const renderedChunks = await Promise.all(chunks.map(chunk => chunk.render()));
  19750. timeEnd('render chunks', 2);
  19751. timeStart('transform chunks', 2);
  19752. const getHash = hasherByType[outputOptions.hashCharacters];
  19753. const chunkGraph = getChunkGraph(chunks);
  19754. const { hashDependenciesByPlaceholder, initialHashesByPlaceholder, nonHashedChunksWithPlaceholders, placeholders, renderedChunksByPlaceholder } = await transformChunksAndGenerateContentHashes(renderedChunks, chunkGraph, outputOptions, pluginDriver, getHash, log);
  19755. const hashesByPlaceholder = generateFinalHashes(renderedChunksByPlaceholder, hashDependenciesByPlaceholder, initialHashesByPlaceholder, placeholders, bundle, getHash);
  19756. addChunksToBundle(renderedChunksByPlaceholder, hashesByPlaceholder, bundle, nonHashedChunksWithPlaceholders, pluginDriver, outputOptions);
  19757. timeEnd('transform chunks', 2);
  19758. }
  19759. function reserveEntryChunksInBundle(chunks) {
  19760. for (const chunk of chunks) {
  19761. if (chunk.facadeModule && chunk.facadeModule.isUserDefinedEntryPoint) {
  19762. // reserves name in bundle as side effect if it does not contain a hash
  19763. chunk.getPreliminaryFileName();
  19764. }
  19765. }
  19766. }
  19767. function getChunkGraph(chunks) {
  19768. return Object.fromEntries(chunks.map(chunk => {
  19769. const renderedChunkInfo = chunk.getRenderedChunkInfo();
  19770. return [renderedChunkInfo.fileName, renderedChunkInfo];
  19771. }));
  19772. }
  19773. async function transformChunk(magicString, fileName, usedModules, chunkGraph, options, outputPluginDriver, log) {
  19774. let map = null;
  19775. const sourcemapChain = [];
  19776. let code = await outputPluginDriver.hookReduceArg0('renderChunk', [magicString.toString(), chunkGraph[fileName], options, { chunks: chunkGraph }], (code, result, plugin) => {
  19777. if (result == null)
  19778. return code;
  19779. if (typeof result === 'string')
  19780. result = {
  19781. code: result,
  19782. map: undefined
  19783. };
  19784. // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning
  19785. if (result.map !== null) {
  19786. const map = decodedSourcemap(result.map);
  19787. sourcemapChain.push(map || { missing: true, plugin: plugin.name });
  19788. }
  19789. return result.code;
  19790. });
  19791. const { compact, dir, file, sourcemap, sourcemapExcludeSources, sourcemapFile, sourcemapPathTransform, sourcemapIgnoreList } = options;
  19792. if (!compact && code[code.length - 1] !== '\n')
  19793. code += '\n';
  19794. if (sourcemap) {
  19795. timeStart('sourcemaps', 3);
  19796. let resultingFile;
  19797. if (file)
  19798. resultingFile = resolve$1(sourcemapFile || file);
  19799. else if (dir)
  19800. resultingFile = resolve$1(dir, fileName);
  19801. else
  19802. resultingFile = resolve$1(fileName);
  19803. const decodedMap = magicString.generateDecodedMap({});
  19804. map = collapseSourcemaps(resultingFile, decodedMap, usedModules, sourcemapChain, sourcemapExcludeSources, log);
  19805. for (let sourcesIndex = 0; sourcesIndex < map.sources.length; ++sourcesIndex) {
  19806. let sourcePath = map.sources[sourcesIndex];
  19807. const sourcemapPath = `${resultingFile}.map`;
  19808. const ignoreList = sourcemapIgnoreList(sourcePath, sourcemapPath);
  19809. if (typeof ignoreList !== 'boolean') {
  19810. error(logFailedValidation('sourcemapIgnoreList function must return a boolean.'));
  19811. }
  19812. if (ignoreList) {
  19813. if (map.x_google_ignoreList === undefined) {
  19814. map.x_google_ignoreList = [];
  19815. }
  19816. if (!map.x_google_ignoreList.includes(sourcesIndex)) {
  19817. map.x_google_ignoreList.push(sourcesIndex);
  19818. }
  19819. }
  19820. if (sourcemapPathTransform) {
  19821. sourcePath = sourcemapPathTransform(sourcePath, sourcemapPath);
  19822. if (typeof sourcePath !== 'string') {
  19823. error(logFailedValidation(`sourcemapPathTransform function must return a string.`));
  19824. }
  19825. }
  19826. map.sources[sourcesIndex] = normalize(sourcePath);
  19827. }
  19828. timeEnd('sourcemaps', 3);
  19829. }
  19830. return {
  19831. code,
  19832. map
  19833. };
  19834. }
  19835. async function transformChunksAndGenerateContentHashes(renderedChunks, chunkGraph, outputOptions, pluginDriver, getHash, log) {
  19836. const nonHashedChunksWithPlaceholders = [];
  19837. const renderedChunksByPlaceholder = new Map();
  19838. const hashDependenciesByPlaceholder = new Map();
  19839. const initialHashesByPlaceholder = new Map();
  19840. const placeholders = new Set();
  19841. for (const { preliminaryFileName: { hashPlaceholder } } of renderedChunks) {
  19842. if (hashPlaceholder)
  19843. placeholders.add(hashPlaceholder);
  19844. }
  19845. await Promise.all(renderedChunks.map(async ({ chunk, preliminaryFileName: { fileName, hashPlaceholder }, preliminarySourcemapFileName, magicString, usedModules }) => {
  19846. const transformedChunk = {
  19847. chunk,
  19848. fileName,
  19849. sourcemapFileName: preliminarySourcemapFileName?.fileName ?? null,
  19850. ...(await transformChunk(magicString, fileName, usedModules, chunkGraph, outputOptions, pluginDriver, log))
  19851. };
  19852. const { code, map } = transformedChunk;
  19853. if (hashPlaceholder) {
  19854. // To create a reproducible content-only hash, all placeholders are
  19855. // replaced with the same value before hashing
  19856. const { containedPlaceholders, transformedCode } = replacePlaceholdersWithDefaultAndGetContainedPlaceholders(code, placeholders);
  19857. let contentToHash = transformedCode;
  19858. const hashAugmentation = pluginDriver.hookReduceValueSync('augmentChunkHash', '', [chunk.getRenderedChunkInfo()], (augmentation, pluginHash) => {
  19859. if (pluginHash) {
  19860. augmentation += pluginHash;
  19861. }
  19862. return augmentation;
  19863. });
  19864. if (hashAugmentation) {
  19865. contentToHash += hashAugmentation;
  19866. }
  19867. renderedChunksByPlaceholder.set(hashPlaceholder, transformedChunk);
  19868. hashDependenciesByPlaceholder.set(hashPlaceholder, {
  19869. containedPlaceholders,
  19870. contentHash: getHash(contentToHash)
  19871. });
  19872. }
  19873. else {
  19874. nonHashedChunksWithPlaceholders.push(transformedChunk);
  19875. }
  19876. const sourcemapHashPlaceholder = preliminarySourcemapFileName?.hashPlaceholder;
  19877. if (map && sourcemapHashPlaceholder) {
  19878. initialHashesByPlaceholder.set(preliminarySourcemapFileName.hashPlaceholder, getHash(map.toString()).slice(0, preliminarySourcemapFileName.hashPlaceholder.length));
  19879. }
  19880. }));
  19881. return {
  19882. hashDependenciesByPlaceholder,
  19883. initialHashesByPlaceholder,
  19884. nonHashedChunksWithPlaceholders,
  19885. placeholders,
  19886. renderedChunksByPlaceholder
  19887. };
  19888. }
  19889. function generateFinalHashes(renderedChunksByPlaceholder, hashDependenciesByPlaceholder, initialHashesByPlaceholder, placeholders, bundle, getHash) {
  19890. const hashesByPlaceholder = new Map(initialHashesByPlaceholder);
  19891. for (const placeholder of placeholders) {
  19892. const { fileName } = renderedChunksByPlaceholder.get(placeholder);
  19893. let contentToHash = '';
  19894. const hashDependencyPlaceholders = new Set([placeholder]);
  19895. for (const dependencyPlaceholder of hashDependencyPlaceholders) {
  19896. const { containedPlaceholders, contentHash } = hashDependenciesByPlaceholder.get(dependencyPlaceholder);
  19897. contentToHash += contentHash;
  19898. for (const containedPlaceholder of containedPlaceholders) {
  19899. // When looping over a map, setting an entry only causes a new iteration if the key is new
  19900. hashDependencyPlaceholders.add(containedPlaceholder);
  19901. }
  19902. }
  19903. let finalFileName;
  19904. let finalHash;
  19905. do {
  19906. // In case of a hash collision, create a hash of the hash
  19907. if (finalHash) {
  19908. contentToHash = finalHash;
  19909. }
  19910. finalHash = getHash(contentToHash).slice(0, placeholder.length);
  19911. finalFileName = replaceSinglePlaceholder(fileName, placeholder, finalHash);
  19912. } while (bundle[lowercaseBundleKeys].has(finalFileName.toLowerCase()));
  19913. bundle[finalFileName] = FILE_PLACEHOLDER;
  19914. hashesByPlaceholder.set(placeholder, finalHash);
  19915. }
  19916. return hashesByPlaceholder;
  19917. }
  19918. function addChunksToBundle(renderedChunksByPlaceholder, hashesByPlaceholder, bundle, nonHashedChunksWithPlaceholders, pluginDriver, options) {
  19919. for (const { chunk, code, fileName, sourcemapFileName, map } of renderedChunksByPlaceholder.values()) {
  19920. let updatedCode = replacePlaceholders(code, hashesByPlaceholder);
  19921. const finalFileName = replacePlaceholders(fileName, hashesByPlaceholder);
  19922. let finalSourcemapFileName = null;
  19923. if (map) {
  19924. if (options.sourcemapDebugIds) {
  19925. updatedCode += calculateDebugIdAndGetComment(updatedCode, map);
  19926. }
  19927. finalSourcemapFileName = sourcemapFileName
  19928. ? replacePlaceholders(sourcemapFileName, hashesByPlaceholder)
  19929. : `${finalFileName}.map`;
  19930. map.file = replacePlaceholders(map.file, hashesByPlaceholder);
  19931. updatedCode += emitSourceMapAndGetComment(finalSourcemapFileName, map, pluginDriver, options);
  19932. }
  19933. bundle[finalFileName] = chunk.finalizeChunk(updatedCode, map, finalSourcemapFileName, hashesByPlaceholder);
  19934. }
  19935. for (const { chunk, code, fileName, sourcemapFileName, map } of nonHashedChunksWithPlaceholders) {
  19936. let updatedCode = hashesByPlaceholder.size > 0 ? replacePlaceholders(code, hashesByPlaceholder) : code;
  19937. let finalSourcemapFileName = null;
  19938. if (map) {
  19939. if (options.sourcemapDebugIds) {
  19940. updatedCode += calculateDebugIdAndGetComment(updatedCode, map);
  19941. }
  19942. finalSourcemapFileName = sourcemapFileName
  19943. ? replacePlaceholders(sourcemapFileName, hashesByPlaceholder)
  19944. : `${fileName}.map`;
  19945. updatedCode += emitSourceMapAndGetComment(finalSourcemapFileName, map, pluginDriver, options);
  19946. }
  19947. bundle[fileName] = chunk.finalizeChunk(updatedCode, map, finalSourcemapFileName, hashesByPlaceholder);
  19948. }
  19949. }
  19950. function emitSourceMapAndGetComment(fileName, map, pluginDriver, { sourcemap, sourcemapBaseUrl }) {
  19951. let url;
  19952. if (sourcemap === 'inline') {
  19953. url = map.toUrl();
  19954. }
  19955. else {
  19956. const sourcemapFileName = basename(fileName);
  19957. url = sourcemapBaseUrl
  19958. ? new URL(sourcemapFileName, sourcemapBaseUrl).toString()
  19959. : sourcemapFileName;
  19960. pluginDriver.emitFile({
  19961. fileName,
  19962. originalFileName: null,
  19963. source: map.toString(),
  19964. type: 'asset'
  19965. });
  19966. }
  19967. return sourcemap === 'hidden' ? '' : `//# ${SOURCEMAPPING_URL}=${url}\n`;
  19968. }
  19969. function calculateDebugIdAndGetComment(code, map) {
  19970. const hash = hasherByType.hex(code);
  19971. const debugId = [
  19972. hash.slice(0, 8),
  19973. hash.slice(8, 12),
  19974. '4' + hash.slice(12, 15),
  19975. ((parseInt(hash.slice(15, 16), 16) & 3) | 8).toString(16) + hash.slice(17, 20),
  19976. hash.slice(20, 32)
  19977. ].join('-');
  19978. map.debugId = debugId;
  19979. return '//# debugId=' + debugId + '\n';
  19980. }
  19981. class Bundle {
  19982. constructor(outputOptions, unsetOptions, inputOptions, pluginDriver, graph) {
  19983. this.outputOptions = outputOptions;
  19984. this.unsetOptions = unsetOptions;
  19985. this.inputOptions = inputOptions;
  19986. this.pluginDriver = pluginDriver;
  19987. this.graph = graph;
  19988. this.facadeChunkByModule = new Map();
  19989. this.includedNamespaces = new Set();
  19990. }
  19991. async generate(isWrite) {
  19992. timeStart('GENERATE', 1);
  19993. const outputBundleBase = Object.create(null);
  19994. const outputBundle = getOutputBundle(outputBundleBase);
  19995. this.pluginDriver.setOutputBundle(outputBundle, this.outputOptions);
  19996. try {
  19997. timeStart('initialize render', 2);
  19998. await this.pluginDriver.hookParallel('renderStart', [this.outputOptions, this.inputOptions]);
  19999. timeEnd('initialize render', 2);
  20000. timeStart('generate chunks', 2);
  20001. const getHashPlaceholder = getHashPlaceholderGenerator();
  20002. const chunks = await this.generateChunks(outputBundle, getHashPlaceholder);
  20003. if (chunks.length > 1) {
  20004. validateOptionsForMultiChunkOutput(this.outputOptions, this.inputOptions.onLog);
  20005. }
  20006. this.pluginDriver.setChunkInformation(this.facadeChunkByModule);
  20007. for (const chunk of chunks) {
  20008. chunk.generateExports();
  20009. chunk.inlineTransitiveImports();
  20010. }
  20011. timeEnd('generate chunks', 2);
  20012. await renderChunks(chunks, outputBundle, this.pluginDriver, this.outputOptions, this.inputOptions.onLog);
  20013. }
  20014. catch (error_) {
  20015. await this.pluginDriver.hookParallel('renderError', [error_]);
  20016. throw error_;
  20017. }
  20018. removeUnreferencedAssets(outputBundle);
  20019. timeStart('generate bundle', 2);
  20020. await this.pluginDriver.hookSeq('generateBundle', [
  20021. this.outputOptions,
  20022. outputBundle,
  20023. isWrite
  20024. ]);
  20025. this.finaliseAssets(outputBundle);
  20026. validateOutputBundleFileNames(outputBundle);
  20027. timeEnd('generate bundle', 2);
  20028. timeEnd('GENERATE', 1);
  20029. return outputBundleBase;
  20030. }
  20031. async addManualChunks(manualChunks) {
  20032. const manualChunkAliasByEntry = new Map();
  20033. const chunkEntries = await Promise.all(Object.entries(manualChunks).map(async ([alias, files]) => ({
  20034. alias,
  20035. entries: await this.graph.moduleLoader.addAdditionalModules(files, true)
  20036. })));
  20037. for (const { alias, entries } of chunkEntries) {
  20038. for (const entry of entries) {
  20039. addModuleToManualChunk(alias, entry, manualChunkAliasByEntry);
  20040. }
  20041. }
  20042. return manualChunkAliasByEntry;
  20043. }
  20044. assignManualChunks(getManualChunk) {
  20045. const manualChunkAliasByEntry = new Map();
  20046. const manualChunksApi = {
  20047. getModuleIds: () => this.graph.modulesById.keys(),
  20048. getModuleInfo: this.graph.getModuleInfo
  20049. };
  20050. for (const module of this.graph.modulesById.values()) {
  20051. if (module instanceof Module) {
  20052. const manualChunkAlias = getManualChunk(module.id, manualChunksApi);
  20053. if (typeof manualChunkAlias === 'string') {
  20054. addModuleToManualChunk(manualChunkAlias, module, manualChunkAliasByEntry);
  20055. }
  20056. }
  20057. }
  20058. return manualChunkAliasByEntry;
  20059. }
  20060. finaliseAssets(bundle) {
  20061. if (this.outputOptions.validate) {
  20062. for (const file of Object.values(bundle)) {
  20063. if ('code' in file) {
  20064. try {
  20065. parseAst(file.code, { jsx: this.inputOptions.jsx !== false });
  20066. }
  20067. catch (error_) {
  20068. this.inputOptions.onLog(LOGLEVEL_WARN, logChunkInvalid(file, error_));
  20069. }
  20070. }
  20071. }
  20072. }
  20073. this.pluginDriver.finaliseAssets();
  20074. }
  20075. async generateChunks(bundle, getHashPlaceholder) {
  20076. const { experimentalMinChunkSize, inlineDynamicImports, manualChunks, preserveModules, onlyExplicitManualChunks } = this.outputOptions;
  20077. const manualChunkAliasByEntry = typeof manualChunks === 'object'
  20078. ? await this.addManualChunks(manualChunks)
  20079. : this.assignManualChunks(manualChunks);
  20080. const snippets = getGenerateCodeSnippets(this.outputOptions);
  20081. const includedModules = getIncludedModules(this.graph.modulesById);
  20082. const inputBase = commondir(getAbsoluteEntryModulePaths(includedModules, preserveModules));
  20083. const externalChunkByModule = getExternalChunkByModule(this.graph.modulesById, this.outputOptions, inputBase);
  20084. const executableModule = inlineDynamicImports
  20085. ? [{ alias: null, modules: includedModules }]
  20086. : preserveModules
  20087. ? includedModules.map(module => ({ alias: null, modules: [module] }))
  20088. : getChunkAssignments(this.graph.entryModules, manualChunkAliasByEntry, experimentalMinChunkSize, this.inputOptions.onLog, typeof manualChunks === 'function', onlyExplicitManualChunks);
  20089. const chunks = new Array(executableModule.length);
  20090. const chunkByModule = new Map();
  20091. let index = 0;
  20092. for (const { alias, modules } of executableModule) {
  20093. sortByExecutionOrder(modules);
  20094. 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);
  20095. chunks[index++] = chunk;
  20096. }
  20097. for (const chunk of chunks) {
  20098. chunk.link();
  20099. }
  20100. if (!inlineDynamicImports && !preserveModules) {
  20101. this.checkCircularChunks(chunks);
  20102. }
  20103. const facades = [];
  20104. for (const chunk of chunks) {
  20105. facades.push(...chunk.generateFacades());
  20106. }
  20107. return [...chunks, ...facades];
  20108. }
  20109. checkCircularChunks(chunks) {
  20110. const visited = new Set();
  20111. const parents = new Map();
  20112. const handleDependency = (chunk, parent) => {
  20113. if (parents.has(chunk)) {
  20114. if (!visited.has(chunk)) {
  20115. const path = [chunk.getChunkName()];
  20116. let isManualChunkConflict = chunk.isManualChunk;
  20117. let nextChunk = parent;
  20118. while (nextChunk !== chunk && nextChunk) {
  20119. path.push(nextChunk.getChunkName());
  20120. isManualChunkConflict &&= nextChunk.isManualChunk;
  20121. nextChunk = parents.get(nextChunk);
  20122. }
  20123. path.push(path[0]);
  20124. path.reverse();
  20125. this.inputOptions.onLog(LOGLEVEL_WARN, logCircularChunk(path, isManualChunkConflict));
  20126. }
  20127. return;
  20128. }
  20129. parents.set(chunk, parent);
  20130. analyseChunk(chunk);
  20131. };
  20132. const analyseChunk = (chunk) => {
  20133. for (const dependency of chunk.dependencies) {
  20134. if (dependency instanceof Chunk) {
  20135. handleDependency(dependency, chunk);
  20136. }
  20137. }
  20138. visited.add(chunk);
  20139. };
  20140. for (const chunk of chunks) {
  20141. if (!parents.has(chunk)) {
  20142. analyseChunk(chunk);
  20143. }
  20144. }
  20145. }
  20146. }
  20147. function validateOptionsForMultiChunkOutput(outputOptions, log) {
  20148. if (outputOptions.format === 'umd' || outputOptions.format === 'iife')
  20149. return error(logInvalidOption('output.format', URL_OUTPUT_FORMAT, 'UMD and IIFE output formats are not supported for code-splitting builds', outputOptions.format));
  20150. if (typeof outputOptions.file === 'string')
  20151. 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'));
  20152. if (outputOptions.sourcemapFile)
  20153. return error(logInvalidOption('output.sourcemapFile', URL_OUTPUT_SOURCEMAPFILE, '"output.sourcemapFile" is only supported for single-file builds'));
  20154. if (!outputOptions.amd.autoId && outputOptions.amd.id)
  20155. 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'));
  20156. }
  20157. function getIncludedModules(modulesById) {
  20158. const includedModules = [];
  20159. for (const module of modulesById.values()) {
  20160. if (module instanceof Module &&
  20161. (module.isIncluded() || module.info.isEntry || module.includedDynamicImporters.length > 0)) {
  20162. includedModules.push(module);
  20163. }
  20164. }
  20165. return includedModules;
  20166. }
  20167. function getAbsoluteEntryModulePaths(includedModules, preserveModules) {
  20168. const absoluteEntryModulePaths = [];
  20169. for (const module of includedModules) {
  20170. if ((module.info.isEntry || preserveModules) && isAbsolute$1(module.id)) {
  20171. absoluteEntryModulePaths.push(module.id);
  20172. }
  20173. }
  20174. return absoluteEntryModulePaths;
  20175. }
  20176. function getExternalChunkByModule(modulesById, outputOptions, inputBase) {
  20177. const externalChunkByModule = new Map();
  20178. for (const module of modulesById.values()) {
  20179. if (module instanceof ExternalModule) {
  20180. externalChunkByModule.set(module, new ExternalChunk(module, outputOptions, inputBase));
  20181. }
  20182. }
  20183. return externalChunkByModule;
  20184. }
  20185. function addModuleToManualChunk(alias, module, manualChunkAliasByEntry) {
  20186. const existingAlias = manualChunkAliasByEntry.get(module);
  20187. if (typeof existingAlias === 'string' && existingAlias !== alias) {
  20188. return error(logCannotAssignModuleToChunk(module.id, alias, existingAlias));
  20189. }
  20190. manualChunkAliasByEntry.set(module, alias);
  20191. }
  20192. function isFileNameOutsideOutputDirectory(fileName) {
  20193. // Use join() to normalize ".." segments, then replace backslashes so the
  20194. // string checks below work identically on Windows and POSIX.
  20195. const normalized = join(fileName).replaceAll('\\', '/');
  20196. return (normalized === '..' ||
  20197. normalized.startsWith('../') ||
  20198. normalized === '.' ||
  20199. isAbsolute$1(normalized));
  20200. }
  20201. function validateOutputBundleFileNames(bundle) {
  20202. for (const [bundleKey, entry] of Object.entries(bundle)) {
  20203. if (isFileNameOutsideOutputDirectory(bundleKey)) {
  20204. return error(logFileNameOutsideOutputDirectory(bundleKey));
  20205. }
  20206. if (entry.type !== 'placeholder') {
  20207. const { fileName } = entry;
  20208. if (fileName !== bundleKey && isFileNameOutsideOutputDirectory(fileName)) {
  20209. return error(logFileNameOutsideOutputDirectory(fileName));
  20210. }
  20211. }
  20212. }
  20213. }
  20214. function flru (max) {
  20215. var num, curr, prev;
  20216. var limit = max;
  20217. function keep(key, value) {
  20218. if (++num > limit) {
  20219. prev = curr;
  20220. reset(1);
  20221. ++num;
  20222. }
  20223. curr[key] = value;
  20224. }
  20225. function reset(isPartial) {
  20226. num = 0;
  20227. curr = Object.create(null);
  20228. isPartial || (prev=Object.create(null));
  20229. }
  20230. reset();
  20231. return {
  20232. clear: reset,
  20233. has: function (key) {
  20234. return curr[key] !== void 0 || prev[key] !== void 0;
  20235. },
  20236. get: function (key) {
  20237. var val = curr[key];
  20238. if (val !== void 0) return val;
  20239. if ((val=prev[key]) !== void 0) {
  20240. keep(key, val);
  20241. return val;
  20242. }
  20243. },
  20244. set: function (key, value) {
  20245. if (curr[key] !== void 0) {
  20246. curr[key] = value;
  20247. } else {
  20248. keep(key, value);
  20249. }
  20250. }
  20251. };
  20252. }
  20253. class GlobalScope extends Scope {
  20254. constructor() {
  20255. super();
  20256. this.parent = null;
  20257. this.variables.set('undefined', new UndefinedVariable());
  20258. }
  20259. findVariable(name) {
  20260. let variable = this.variables.get(name);
  20261. if (!variable) {
  20262. variable = new GlobalVariable(name);
  20263. this.variables.set(name, variable);
  20264. }
  20265. return variable;
  20266. }
  20267. }
  20268. function resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, attributes, importerAttributes) {
  20269. let skipped = null;
  20270. let replaceContext = null;
  20271. if (skip) {
  20272. skipped = new Set();
  20273. for (const skippedCall of skip) {
  20274. if (source === skippedCall.source && importer === skippedCall.importer) {
  20275. skipped.add(skippedCall.plugin);
  20276. }
  20277. }
  20278. replaceContext = (pluginContext, plugin) => ({
  20279. ...pluginContext,
  20280. resolve: (source, importer, { attributes, custom, isEntry, skipSelf, importerAttributes } = BLANK) => {
  20281. skipSelf ??= true;
  20282. if (skipSelf &&
  20283. skip.findIndex(skippedCall => {
  20284. return (skippedCall.plugin === plugin &&
  20285. skippedCall.source === source &&
  20286. skippedCall.importer === importer);
  20287. }) !== -1) {
  20288. // This means that the plugin recursively called itself
  20289. // Thus returning Promise.resolve(null) in purpose of fallback to default behavior of `resolveId` plugin hook.
  20290. return Promise.resolve(null);
  20291. }
  20292. return moduleLoaderResolveId(source, importer, custom, isEntry, attributes || EMPTY_OBJECT, importerAttributes, skipSelf ? [...skip, { importer, plugin, source }] : skip);
  20293. }
  20294. });
  20295. }
  20296. return pluginDriver.hookFirstAndGetPlugin('resolveId', [source, importer, { attributes, custom: customOptions, importerAttributes, isEntry }], replaceContext, skipped);
  20297. }
  20298. async function resolveId(source, importer, preserveSymlinks, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, attributes, importerAttributes, fs) {
  20299. const pluginResult = await resolveIdViaPlugins(source, importer, pluginDriver, moduleLoaderResolveId, skip, customOptions, isEntry, attributes, importerAttributes);
  20300. if (pluginResult != null) {
  20301. const [resolveIdResult, plugin] = pluginResult;
  20302. if (typeof resolveIdResult === 'object' && !resolveIdResult.resolvedBy) {
  20303. return {
  20304. ...resolveIdResult,
  20305. resolvedBy: plugin.name
  20306. };
  20307. }
  20308. if (typeof resolveIdResult === 'string') {
  20309. return {
  20310. id: resolveIdResult,
  20311. resolvedBy: plugin.name
  20312. };
  20313. }
  20314. return resolveIdResult;
  20315. }
  20316. // external modules (non-entry modules that start with neither '.' or '/')
  20317. // are skipped at this stage.
  20318. if (importer !== undefined && !isAbsolute$1(source) && source[0] !== '.')
  20319. return null;
  20320. // `resolve` processes paths from right to left, prepending them until an
  20321. // absolute path is created. Absolute importees therefore shortcircuit the
  20322. // resolve call and require no special handing on our part.
  20323. // See https://nodejs.org/api/path.html#path_path_resolve_paths
  20324. return addJsExtensionIfNecessary(importer ? resolve$1(dirname(importer), source) : resolve$1(source), preserveSymlinks, fs);
  20325. }
  20326. async function addJsExtensionIfNecessary(file, preserveSymlinks, fs) {
  20327. return ((await findFile(file, preserveSymlinks, fs)) ??
  20328. (await findFile(file + '.mjs', preserveSymlinks, fs)) ??
  20329. (await findFile(file + '.js', preserveSymlinks, fs)));
  20330. }
  20331. async function findFile(file, preserveSymlinks, fs) {
  20332. try {
  20333. const stats = await fs.lstat(file);
  20334. if (!preserveSymlinks && stats.isSymbolicLink())
  20335. return await findFile(await fs.realpath(file), preserveSymlinks, fs);
  20336. if ((preserveSymlinks && stats.isSymbolicLink()) || stats.isFile()) {
  20337. // check case
  20338. const name = basename(file);
  20339. const files = await fs.readdir(dirname(file));
  20340. if (files.includes(name))
  20341. return file;
  20342. }
  20343. }
  20344. catch {
  20345. // suppress
  20346. }
  20347. }
  20348. function stripBom(content) {
  20349. if (content.charCodeAt(0) === 0xfe_ff) {
  20350. return stripBom(content.slice(1));
  20351. }
  20352. return content;
  20353. }
  20354. async function asyncFlatten(array) {
  20355. do {
  20356. array = (await Promise.all(array)).flat(Infinity);
  20357. } while (array.some((v) => v?.then));
  20358. return array;
  20359. }
  20360. const getOnLog = (config, logLevel, printLog = defaultPrintLog) => {
  20361. const { onwarn, onLog } = config;
  20362. const defaultOnLog = getDefaultOnLog(printLog, onwarn);
  20363. if (onLog) {
  20364. const minimalPriority = logLevelPriority[logLevel];
  20365. return (level, log) => onLog(level, addLogToString(log), (level, handledLog) => {
  20366. if (level === LOGLEVEL_ERROR) {
  20367. return error(normalizeLog(handledLog));
  20368. }
  20369. if (logLevelPriority[level] >= minimalPriority) {
  20370. defaultOnLog(level, normalizeLog(handledLog));
  20371. }
  20372. });
  20373. }
  20374. return defaultOnLog;
  20375. };
  20376. const getDefaultOnLog = (printLog, onwarn) => onwarn
  20377. ? (level, log) => {
  20378. if (level === LOGLEVEL_WARN) {
  20379. onwarn(addLogToString(log), warning => printLog(LOGLEVEL_WARN, normalizeLog(warning)));
  20380. }
  20381. else {
  20382. printLog(level, log);
  20383. }
  20384. }
  20385. : printLog;
  20386. const addLogToString = (log) => {
  20387. Object.defineProperty(log, 'toString', {
  20388. value: () => log.message,
  20389. writable: true
  20390. });
  20391. return log;
  20392. };
  20393. const normalizeLog = (log) => typeof log === 'string'
  20394. ? { message: log }
  20395. : typeof log === 'function'
  20396. ? normalizeLog(log())
  20397. : log;
  20398. const defaultPrintLog = (level, { message }) => {
  20399. switch (level) {
  20400. case LOGLEVEL_WARN: {
  20401. return console.warn(message);
  20402. }
  20403. case LOGLEVEL_DEBUG: {
  20404. return console.debug(message);
  20405. }
  20406. default: {
  20407. return console.info(message);
  20408. }
  20409. }
  20410. };
  20411. function warnUnknownOptions(passedOptions, validOptions, optionType, log, ignoredKeys = /$./) {
  20412. const validOptionSet = new Set(validOptions);
  20413. const unknownOptions = Object.keys(passedOptions).filter(key => !(validOptionSet.has(key) || ignoredKeys.test(key)));
  20414. if (unknownOptions.length > 0) {
  20415. log(LOGLEVEL_WARN, logUnknownOption(optionType, unknownOptions, [...validOptionSet].sort()));
  20416. }
  20417. }
  20418. const treeshakePresets = {
  20419. recommended: {
  20420. annotations: true,
  20421. correctVarValueBeforeDeclaration: false,
  20422. manualPureFunctions: EMPTY_ARRAY,
  20423. moduleSideEffects: () => true,
  20424. propertyReadSideEffects: true,
  20425. tryCatchDeoptimization: true,
  20426. unknownGlobalSideEffects: false
  20427. },
  20428. safest: {
  20429. annotations: true,
  20430. correctVarValueBeforeDeclaration: true,
  20431. manualPureFunctions: EMPTY_ARRAY,
  20432. moduleSideEffects: () => true,
  20433. propertyReadSideEffects: true,
  20434. tryCatchDeoptimization: true,
  20435. unknownGlobalSideEffects: true
  20436. },
  20437. smallest: {
  20438. annotations: true,
  20439. correctVarValueBeforeDeclaration: false,
  20440. manualPureFunctions: EMPTY_ARRAY,
  20441. moduleSideEffects: () => false,
  20442. propertyReadSideEffects: false,
  20443. tryCatchDeoptimization: false,
  20444. unknownGlobalSideEffects: false
  20445. }
  20446. };
  20447. const jsxPresets = {
  20448. preserve: {
  20449. factory: null,
  20450. fragment: null,
  20451. importSource: null,
  20452. mode: 'preserve'
  20453. },
  20454. 'preserve-react': {
  20455. factory: 'React.createElement',
  20456. fragment: 'React.Fragment',
  20457. importSource: 'react',
  20458. mode: 'preserve'
  20459. },
  20460. react: {
  20461. factory: 'React.createElement',
  20462. fragment: 'React.Fragment',
  20463. importSource: 'react',
  20464. mode: 'classic'
  20465. },
  20466. 'react-jsx': {
  20467. factory: 'React.createElement',
  20468. importSource: 'react',
  20469. jsxImportSource: 'react/jsx-runtime',
  20470. mode: 'automatic'
  20471. }
  20472. };
  20473. const generatedCodePresets = {
  20474. es2015: {
  20475. arrowFunctions: true,
  20476. constBindings: true,
  20477. objectShorthand: true,
  20478. reservedNamesAsProps: true,
  20479. symbols: true
  20480. },
  20481. es5: {
  20482. arrowFunctions: false,
  20483. constBindings: false,
  20484. objectShorthand: false,
  20485. reservedNamesAsProps: true,
  20486. symbols: false
  20487. }
  20488. };
  20489. const objectifyOption = (value) => value && typeof value === 'object' ? value : {};
  20490. const objectifyOptionWithPresets = (presets, optionName, urlSnippet, additionalValues) => (value) => {
  20491. if (typeof value === 'string') {
  20492. const preset = presets[value];
  20493. if (preset) {
  20494. return preset;
  20495. }
  20496. error(logInvalidOption(optionName, urlSnippet, `valid values are ${additionalValues}${printQuotedStringList(Object.keys(presets))}. You can also supply an object for more fine-grained control`, value));
  20497. }
  20498. return objectifyOption(value);
  20499. };
  20500. const getOptionWithPreset = (value, presets, optionName, urlSnippet, additionalValues) => {
  20501. const presetName = value?.preset;
  20502. if (presetName) {
  20503. const preset = presets[presetName];
  20504. if (preset) {
  20505. return { ...preset, ...value };
  20506. }
  20507. else {
  20508. error(logInvalidOption(`${optionName}.preset`, urlSnippet, `valid values are ${printQuotedStringList(Object.keys(presets))}`, presetName));
  20509. }
  20510. }
  20511. return objectifyOptionWithPresets(presets, optionName, urlSnippet, additionalValues)(value);
  20512. };
  20513. const normalizePluginOption = async (plugins) => (await asyncFlatten([plugins])).filter(Boolean);
  20514. const ANONYMOUS_PLUGIN_PREFIX = 'at position ';
  20515. const ANONYMOUS_OUTPUT_PLUGIN_PREFIX = 'at output position ';
  20516. function createPluginCache(cache) {
  20517. return {
  20518. delete(id) {
  20519. return delete cache[id];
  20520. },
  20521. get(id) {
  20522. const item = cache[id];
  20523. if (!item)
  20524. return;
  20525. item[0] = 0;
  20526. return item[1];
  20527. },
  20528. has(id) {
  20529. const item = cache[id];
  20530. if (!item)
  20531. return false;
  20532. item[0] = 0;
  20533. return true;
  20534. },
  20535. set(id, value) {
  20536. cache[id] = [0, value];
  20537. }
  20538. };
  20539. }
  20540. function getTrackedPluginCache(pluginCache, onUse) {
  20541. return {
  20542. delete(id) {
  20543. onUse();
  20544. return pluginCache.delete(id);
  20545. },
  20546. get(id) {
  20547. onUse();
  20548. return pluginCache.get(id);
  20549. },
  20550. has(id) {
  20551. onUse();
  20552. return pluginCache.has(id);
  20553. },
  20554. set(id, value) {
  20555. onUse();
  20556. return pluginCache.set(id, value);
  20557. }
  20558. };
  20559. }
  20560. const NO_CACHE = {
  20561. delete() {
  20562. return false;
  20563. },
  20564. get() {
  20565. return undefined;
  20566. },
  20567. has() {
  20568. return false;
  20569. },
  20570. set() { }
  20571. };
  20572. function uncacheablePluginError(pluginName) {
  20573. if (pluginName.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  20574. pluginName.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX)) {
  20575. return error(logAnonymousPluginCache());
  20576. }
  20577. return error(logDuplicatePluginName(pluginName));
  20578. }
  20579. function getCacheForUncacheablePlugin(pluginName) {
  20580. return {
  20581. delete() {
  20582. return uncacheablePluginError(pluginName);
  20583. },
  20584. get() {
  20585. return uncacheablePluginError(pluginName);
  20586. },
  20587. has() {
  20588. return uncacheablePluginError(pluginName);
  20589. },
  20590. set() {
  20591. return uncacheablePluginError(pluginName);
  20592. }
  20593. };
  20594. }
  20595. async function transform(source, module, pluginDriver, options) {
  20596. const id = module.id;
  20597. const sourcemapChain = [];
  20598. let originalSourcemap = source.map === null ? null : decodedSourcemap(source.map);
  20599. const originalCode = source.code;
  20600. let ast = source.ast;
  20601. const transformDependencies = [];
  20602. const emittedFiles = [];
  20603. let customTransformCache = false;
  20604. const useCustomTransformCache = () => (customTransformCache = true);
  20605. let pluginName = '';
  20606. let currentSource = source.code;
  20607. function transformReducer(previousCode, result, plugin) {
  20608. let code;
  20609. let map;
  20610. if (typeof result === 'string') {
  20611. code = result;
  20612. }
  20613. else if (result && typeof result === 'object') {
  20614. module.updateOptions(result);
  20615. if (result.code == null) {
  20616. if (result.map || result.ast) {
  20617. options.onLog(LOGLEVEL_WARN, logNoTransformMapOrAstWithoutCode(plugin.name));
  20618. }
  20619. return previousCode;
  20620. }
  20621. if (result.attributes) {
  20622. warnDeprecation('Returning attributes from the "transform" hook is forbidden.', URL_TRANSFORM, false, options);
  20623. }
  20624. ({ code, map, ast } = result);
  20625. }
  20626. else {
  20627. return previousCode;
  20628. }
  20629. // strict null check allows 'null' maps to not be pushed to the chain,
  20630. // while 'undefined' gets the missing map warning
  20631. if (map !== null) {
  20632. sourcemapChain.push(decodedSourcemap(typeof map === 'string' ? JSON.parse(map) : map) || {
  20633. missing: true,
  20634. plugin: plugin.name
  20635. });
  20636. }
  20637. currentSource = code;
  20638. return code;
  20639. }
  20640. const getLogHandler = (handler) => (log, pos) => {
  20641. log = normalizeLog(log);
  20642. if (pos)
  20643. augmentCodeLocation(log, pos, currentSource, id);
  20644. log.id = id;
  20645. log.hook = 'transform';
  20646. handler(log);
  20647. };
  20648. let code;
  20649. try {
  20650. code = await pluginDriver.hookReduceArg0('transform', [
  20651. currentSource,
  20652. id,
  20653. {
  20654. attributes: module.info.attributes
  20655. }
  20656. ], transformReducer, (pluginContext, plugin) => {
  20657. pluginName = plugin.name;
  20658. return {
  20659. ...pluginContext,
  20660. addWatchFile(id) {
  20661. transformDependencies.push(id);
  20662. pluginContext.addWatchFile(id);
  20663. },
  20664. cache: customTransformCache
  20665. ? pluginContext.cache
  20666. : getTrackedPluginCache(pluginContext.cache, useCustomTransformCache),
  20667. debug: getLogHandler(pluginContext.debug),
  20668. emitFile(emittedFile) {
  20669. emittedFiles.push(emittedFile);
  20670. return pluginDriver.emitFile(emittedFile);
  20671. },
  20672. error(error_, pos) {
  20673. if (typeof error_ === 'string')
  20674. error_ = { message: error_ };
  20675. if (pos)
  20676. augmentCodeLocation(error_, pos, currentSource, id);
  20677. error_.id = id;
  20678. error_.hook = 'transform';
  20679. return pluginContext.error(error_);
  20680. },
  20681. getCombinedSourcemap() {
  20682. const combinedMap = collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, options.onLog);
  20683. if (!combinedMap) {
  20684. const magicString = new MagicString(originalCode);
  20685. return magicString.generateMap({ hires: true, includeContent: true, source: id });
  20686. }
  20687. if (originalSourcemap !== combinedMap) {
  20688. originalSourcemap = combinedMap;
  20689. sourcemapChain.length = 0;
  20690. }
  20691. return new SourceMap({
  20692. ...combinedMap,
  20693. file: null,
  20694. sourcesContent: combinedMap.sourcesContent
  20695. });
  20696. },
  20697. info: getLogHandler(pluginContext.info),
  20698. setAssetSource() {
  20699. return this.error(logInvalidSetAssetSourceCall());
  20700. },
  20701. warn: getLogHandler(pluginContext.warn)
  20702. };
  20703. });
  20704. }
  20705. catch (error_) {
  20706. return error(logPluginError(error_, pluginName, { hook: 'transform', id }));
  20707. }
  20708. if (!customTransformCache && // files emitted by a transform hook need to be emitted again if the hook is skipped
  20709. emittedFiles.length > 0)
  20710. module.transformFiles = emittedFiles;
  20711. return {
  20712. ast,
  20713. code,
  20714. customTransformCache,
  20715. originalCode,
  20716. originalSourcemap,
  20717. safeVariableNames: null,
  20718. sourcemapChain,
  20719. transformDependencies
  20720. };
  20721. }
  20722. const RESOLVE_DEPENDENCIES = 'resolveDependencies';
  20723. class ModuleLoader {
  20724. constructor(graph, modulesById, options, pluginDriver) {
  20725. this.graph = graph;
  20726. this.modulesById = modulesById;
  20727. this.options = options;
  20728. this.pluginDriver = pluginDriver;
  20729. this.implicitEntryModules = new Set();
  20730. this.indexedEntryModules = [];
  20731. this.latestLoadModulesPromise = Promise.resolve();
  20732. this.moduleLoadPromises = new Map();
  20733. this.modulesWithLoadedDependencies = new Set();
  20734. this.nextChunkNamePriority = 0;
  20735. this.nextEntryModuleIndex = 0;
  20736. this.resolveId = async (source, importer, customOptions, isEntry, attributes, importerAttributes, skip = null) => this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(this.options.external(source, importer, false)
  20737. ? false
  20738. : await resolveId(source, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, skip, customOptions, typeof isEntry === 'boolean' ? isEntry : !importer, attributes, importerAttributes, this.options.fs), importer, source), attributes);
  20739. this.hasModuleSideEffects = options.treeshake
  20740. ? options.treeshake.moduleSideEffects
  20741. : () => true;
  20742. }
  20743. async addAdditionalModules(unresolvedModules, isAddForManualChunks) {
  20744. const result = this.extendLoadModulesPromise(Promise.all(unresolvedModules.map(id => this.loadEntryModule(id, false, undefined, null, isAddForManualChunks, undefined))));
  20745. await this.awaitLoadModulesPromise();
  20746. return result;
  20747. }
  20748. async addEntryModules(unresolvedEntryModules, isUserDefined) {
  20749. const firstEntryModuleIndex = this.nextEntryModuleIndex;
  20750. this.nextEntryModuleIndex += unresolvedEntryModules.length;
  20751. const firstChunkNamePriority = this.nextChunkNamePriority;
  20752. this.nextChunkNamePriority += unresolvedEntryModules.length;
  20753. const newEntryModules = await this.extendLoadModulesPromise(Promise.all(unresolvedEntryModules.map(({ id, importer }) => this.loadEntryModule(id, true, importer, null, undefined, undefined))).then(entryModules => {
  20754. for (const [index, entryModule] of entryModules.entries()) {
  20755. entryModule.isUserDefinedEntryPoint =
  20756. entryModule.isUserDefinedEntryPoint || isUserDefined;
  20757. addChunkNamesToModule(entryModule, unresolvedEntryModules[index], isUserDefined, firstChunkNamePriority + index);
  20758. const existingIndexedModule = this.indexedEntryModules.find(indexedModule => indexedModule.module === entryModule);
  20759. if (existingIndexedModule) {
  20760. existingIndexedModule.index = Math.min(existingIndexedModule.index, firstEntryModuleIndex + index);
  20761. }
  20762. else {
  20763. this.indexedEntryModules.push({
  20764. index: firstEntryModuleIndex + index,
  20765. module: entryModule
  20766. });
  20767. }
  20768. }
  20769. this.indexedEntryModules.sort(({ index: indexA }, { index: indexB }) => indexA > indexB ? 1 : -1);
  20770. return entryModules;
  20771. }));
  20772. await this.awaitLoadModulesPromise();
  20773. return {
  20774. entryModules: this.indexedEntryModules.map(({ module }) => module),
  20775. implicitEntryModules: [...this.implicitEntryModules],
  20776. newEntryModules
  20777. };
  20778. }
  20779. async emitChunk({ fileName, id, importer, name, implicitlyLoadedAfterOneOf, preserveSignature }) {
  20780. const unresolvedModule = {
  20781. fileName: fileName || null,
  20782. id,
  20783. importer,
  20784. name: name || null
  20785. };
  20786. const module = implicitlyLoadedAfterOneOf
  20787. ? await this.addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfterOneOf)
  20788. : (await this.addEntryModules([unresolvedModule], false)).newEntryModules[0];
  20789. if (preserveSignature != null) {
  20790. module.preserveSignature = preserveSignature;
  20791. }
  20792. return module;
  20793. }
  20794. async preloadModule(resolvedId) {
  20795. const module = await this.fetchModule(this.getResolvedIdWithDefaults(resolvedId, EMPTY_OBJECT), undefined, false, resolvedId.resolveDependencies ? RESOLVE_DEPENDENCIES : true);
  20796. return module.info;
  20797. }
  20798. addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfter) {
  20799. const chunkNamePriority = this.nextChunkNamePriority++;
  20800. return this.extendLoadModulesPromise(this.loadEntryModule(unresolvedModule.id, false, unresolvedModule.importer, null, undefined, undefined).then(async (entryModule) => {
  20801. addChunkNamesToModule(entryModule, unresolvedModule, false, chunkNamePriority);
  20802. if (!entryModule.info.isEntry) {
  20803. const implicitlyLoadedAfterModules = await Promise.all(implicitlyLoadedAfter.map(id => this.loadEntryModule(id, false, unresolvedModule.importer, entryModule.id, undefined, undefined)));
  20804. // We need to check again if this is still an entry module as these
  20805. // changes need to be performed atomically to avoid race conditions
  20806. // if the same module is re-emitted as an entry module.
  20807. // The inverse changes happen in "handleExistingModule"
  20808. if (!entryModule.info.isEntry) {
  20809. this.implicitEntryModules.add(entryModule);
  20810. for (const module of implicitlyLoadedAfterModules) {
  20811. entryModule.implicitlyLoadedAfter.add(module);
  20812. }
  20813. for (const dependant of entryModule.implicitlyLoadedAfter) {
  20814. dependant.implicitlyLoadedBefore.add(entryModule);
  20815. }
  20816. }
  20817. }
  20818. return entryModule;
  20819. }));
  20820. }
  20821. async addModuleSource(id, importer, module) {
  20822. let source;
  20823. try {
  20824. source = await this.graph.fileOperationQueue.run(async () => {
  20825. const content = await this.pluginDriver.hookFirst('load', [
  20826. id,
  20827. { attributes: module.info.attributes }
  20828. ]);
  20829. if (content !== null) {
  20830. if (typeof content === 'object' && content.attributes) {
  20831. warnDeprecation('Returning attributes from the "load" hook is forbidden.', URL_LOAD, false, this.options);
  20832. }
  20833. return content;
  20834. }
  20835. this.graph.watchFiles[id] = true;
  20836. return (await this.options.fs.readFile(id, { encoding: 'utf8' }));
  20837. });
  20838. }
  20839. catch (error_) {
  20840. let message = `Could not load ${id}`;
  20841. if (importer)
  20842. message += ` (imported by ${relativeId(importer)})`;
  20843. message += `: ${error_.message}`;
  20844. error_.message = message;
  20845. throw error_;
  20846. }
  20847. const sourceDescription = typeof source === 'string'
  20848. ? { code: source }
  20849. : source != null && typeof source === 'object' && typeof source.code === 'string'
  20850. ? source
  20851. : error(logBadLoader(id));
  20852. sourceDescription.code = stripBom(sourceDescription.code);
  20853. const cachedModule = this.graph.cachedModules.get(id);
  20854. if (cachedModule &&
  20855. !cachedModule.customTransformCache &&
  20856. cachedModule.originalCode === sourceDescription.code &&
  20857. !(await this.pluginDriver.hookFirst('shouldTransformCachedModule', [
  20858. {
  20859. ast: cachedModule.ast,
  20860. attributes: cachedModule.attributes,
  20861. code: cachedModule.code,
  20862. id: cachedModule.id,
  20863. meta: cachedModule.meta,
  20864. moduleSideEffects: cachedModule.moduleSideEffects,
  20865. resolvedSources: cachedModule.resolvedIds,
  20866. syntheticNamedExports: cachedModule.syntheticNamedExports
  20867. }
  20868. ]))) {
  20869. if (cachedModule.transformFiles) {
  20870. for (const emittedFile of cachedModule.transformFiles)
  20871. this.pluginDriver.emitFile(emittedFile);
  20872. }
  20873. await module.setSource(cachedModule);
  20874. }
  20875. else {
  20876. module.updateOptions(sourceDescription);
  20877. await module.setSource(await transform(sourceDescription, module, this.pluginDriver, this.options));
  20878. }
  20879. }
  20880. async awaitLoadModulesPromise() {
  20881. let startingPromise;
  20882. do {
  20883. startingPromise = this.latestLoadModulesPromise;
  20884. await startingPromise;
  20885. } while (startingPromise !== this.latestLoadModulesPromise);
  20886. }
  20887. extendLoadModulesPromise(loadNewModulesPromise) {
  20888. this.latestLoadModulesPromise = Promise.all([
  20889. loadNewModulesPromise,
  20890. this.latestLoadModulesPromise
  20891. ]);
  20892. this.latestLoadModulesPromise.catch(() => {
  20893. /* Avoid unhandled Promise rejections */
  20894. });
  20895. return loadNewModulesPromise;
  20896. }
  20897. async fetchDynamicDependencies(module, resolveDynamicImportPromises) {
  20898. const dependencies = await Promise.all(resolveDynamicImportPromises.map(resolveDynamicImportPromise => resolveDynamicImportPromise.then(async ([{ argument, node }, resolvedId]) => {
  20899. if (resolvedId === null)
  20900. return null;
  20901. if (typeof resolvedId === 'string') {
  20902. node.resolution = resolvedId;
  20903. return null;
  20904. }
  20905. if (node.phase === 'source' && !resolvedId.external) {
  20906. return error(logNonExternalSourcePhaseImport(typeof argument === 'string' ? argument : relativeId(resolvedId.id), module.id));
  20907. }
  20908. return (node.resolution = await this.fetchResolvedDependency(relativeId(resolvedId.id), module.id, resolvedId));
  20909. })));
  20910. for (const dependency of dependencies) {
  20911. if (dependency) {
  20912. module.dynamicDependencies.add(dependency);
  20913. dependency.dynamicImporters.push(module.id);
  20914. }
  20915. }
  20916. }
  20917. // If this is a preload, then this method always waits for the dependencies of
  20918. // the module to be resolved.
  20919. // Otherwise, if the module does not exist, it waits for the module and all
  20920. // its dependencies to be loaded.
  20921. // Otherwise, it returns immediately.
  20922. async fetchModule({ attributes, id, meta, moduleSideEffects, syntheticNamedExports }, importer, isEntry, isPreload) {
  20923. const existingModule = this.modulesById.get(id);
  20924. if (existingModule instanceof Module) {
  20925. if (importer && doAttributesDiffer(attributes, existingModule.info.attributes)) {
  20926. this.options.onLog(LOGLEVEL_WARN, logInconsistentImportAttributes(existingModule.info.attributes, attributes, id, importer));
  20927. }
  20928. await this.handleExistingModule(existingModule, isEntry, isPreload);
  20929. return existingModule;
  20930. }
  20931. if (existingModule instanceof ExternalModule) {
  20932. return error(logExternalModulesCannotBeTransformedToModules(existingModule.id));
  20933. }
  20934. const module = new Module(this.graph, id, this.options, isEntry, moduleSideEffects, syntheticNamedExports, meta, attributes);
  20935. this.modulesById.set(id, module);
  20936. const loadPromise = this.addModuleSource(id, importer, module).then(() => [
  20937. this.getResolveStaticDependencyPromises(module),
  20938. this.getResolveDynamicImportPromises(module),
  20939. loadAndResolveDependenciesPromise
  20940. ]);
  20941. const loadAndResolveDependenciesPromise = waitForDependencyResolution(loadPromise).then(() => this.pluginDriver.hookParallel('moduleParsed', [module.info]));
  20942. loadAndResolveDependenciesPromise.catch(() => {
  20943. /* avoid unhandled promise rejections */
  20944. });
  20945. this.moduleLoadPromises.set(module, loadPromise);
  20946. const resolveDependencyPromises = await loadPromise;
  20947. if (!isPreload) {
  20948. await this.fetchModuleDependencies(module, ...resolveDependencyPromises);
  20949. }
  20950. else if (isPreload === RESOLVE_DEPENDENCIES) {
  20951. await loadAndResolveDependenciesPromise;
  20952. }
  20953. return module;
  20954. }
  20955. async fetchModuleDependencies(module, resolveStaticDependencyPromises, resolveDynamicDependencyPromises, loadAndResolveDependenciesPromise) {
  20956. if (this.modulesWithLoadedDependencies.has(module)) {
  20957. return;
  20958. }
  20959. this.modulesWithLoadedDependencies.add(module);
  20960. await Promise.all([
  20961. this.fetchStaticDependencies(module, resolveStaticDependencyPromises),
  20962. this.fetchDynamicDependencies(module, resolveDynamicDependencyPromises)
  20963. ]);
  20964. module.linkImports();
  20965. // To handle errors when resolving dependencies or in moduleParsed
  20966. await loadAndResolveDependenciesPromise;
  20967. }
  20968. fetchResolvedDependency(source, importer, resolvedId) {
  20969. if (resolvedId.external) {
  20970. const { attributes, external, id, moduleSideEffects, meta } = resolvedId;
  20971. let externalModule = this.modulesById.get(id);
  20972. if (!externalModule) {
  20973. externalModule = new ExternalModule(this.options, id, moduleSideEffects, meta, external !== 'absolute' && isAbsolute$1(id), attributes);
  20974. this.modulesById.set(id, externalModule);
  20975. }
  20976. else if (!(externalModule instanceof ExternalModule)) {
  20977. return error(logInternalIdCannotBeExternal(source, importer));
  20978. }
  20979. else if (doAttributesDiffer(externalModule.info.attributes, attributes)) {
  20980. this.options.onLog(LOGLEVEL_WARN, logInconsistentImportAttributes(externalModule.info.attributes, attributes, source, importer));
  20981. }
  20982. return Promise.resolve(externalModule);
  20983. }
  20984. return this.fetchModule(resolvedId, importer, false, false);
  20985. }
  20986. async fetchStaticDependencies(module, resolveStaticDependencyPromises) {
  20987. for (const dependency of await Promise.all(resolveStaticDependencyPromises.map(resolveStaticDependencyPromise => resolveStaticDependencyPromise.then(([source, resolvedId]) => {
  20988. if (module.sourcePhaseSources.has(source) && !resolvedId.external) {
  20989. return error(logNonExternalSourcePhaseImport(source, module.id));
  20990. }
  20991. return this.fetchResolvedDependency(source, module.id, resolvedId);
  20992. })))) {
  20993. module.dependencies.add(dependency);
  20994. dependency.importers.push(module.id);
  20995. }
  20996. if (!this.options.treeshake || module.info.moduleSideEffects === 'no-treeshake') {
  20997. for (const dependency of module.dependencies) {
  20998. if (dependency instanceof Module) {
  20999. dependency.importedFromNotTreeshaken = true;
  21000. }
  21001. }
  21002. }
  21003. }
  21004. getNormalizedResolvedIdWithoutDefaults(resolveIdResult, importer, source) {
  21005. const { makeAbsoluteExternalsRelative } = this.options;
  21006. if (resolveIdResult) {
  21007. if (typeof resolveIdResult === 'object') {
  21008. const external = resolveIdResult.external || this.options.external(resolveIdResult.id, importer, true);
  21009. return {
  21010. ...resolveIdResult,
  21011. external: external &&
  21012. (external === 'relative' ||
  21013. !isAbsolute$1(resolveIdResult.id) ||
  21014. (external === true &&
  21015. isNotAbsoluteExternal(resolveIdResult.id, source, makeAbsoluteExternalsRelative)) ||
  21016. 'absolute')
  21017. };
  21018. }
  21019. const external = this.options.external(resolveIdResult, importer, true);
  21020. return {
  21021. external: external &&
  21022. (isNotAbsoluteExternal(resolveIdResult, source, makeAbsoluteExternalsRelative) ||
  21023. 'absolute'),
  21024. id: external && makeAbsoluteExternalsRelative
  21025. ? normalizeRelativeExternalId(resolveIdResult, importer)
  21026. : resolveIdResult
  21027. };
  21028. }
  21029. const id = makeAbsoluteExternalsRelative
  21030. ? normalizeRelativeExternalId(source, importer)
  21031. : source;
  21032. if (resolveIdResult !== false && !this.options.external(id, importer, true)) {
  21033. return null;
  21034. }
  21035. return {
  21036. external: isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) || 'absolute',
  21037. id
  21038. };
  21039. }
  21040. getResolveDynamicImportPromises(module) {
  21041. return module.dynamicImports.map(async (dynamicImport) => {
  21042. const resolvedId = await this.resolveDynamicImport(module, dynamicImport.argument, module.id, getAttributesFromImportExpression(dynamicImport.node));
  21043. if (!resolvedId || typeof resolvedId === 'string') {
  21044. dynamicImport.node.shouldIncludeDynamicAttributes = true;
  21045. }
  21046. else {
  21047. dynamicImport.node.shouldIncludeDynamicAttributes = !!resolvedId.external;
  21048. dynamicImport.id = resolvedId.id;
  21049. }
  21050. return [dynamicImport, resolvedId];
  21051. });
  21052. }
  21053. getResolveStaticDependencyPromises(module) {
  21054. return Array.from(module.sourcesWithAttributes, async ([source, attributes]) => [
  21055. source,
  21056. (module.resolvedIds[source] =
  21057. module.resolvedIds[source] ||
  21058. this.handleInvalidResolvedId(await this.resolveId(source, module.id, EMPTY_OBJECT, false, attributes, module.info.attributes), source, module.id, attributes))
  21059. ]);
  21060. }
  21061. getResolvedIdWithDefaults(resolvedId, attributes) {
  21062. if (!resolvedId) {
  21063. return null;
  21064. }
  21065. const external = resolvedId.external || false;
  21066. return {
  21067. attributes: resolvedId.attributes || attributes,
  21068. external,
  21069. id: resolvedId.id,
  21070. meta: resolvedId.meta || {},
  21071. moduleSideEffects: resolvedId.moduleSideEffects ?? this.hasModuleSideEffects(resolvedId.id, !!external),
  21072. resolvedBy: resolvedId.resolvedBy ?? 'rollup',
  21073. syntheticNamedExports: resolvedId.syntheticNamedExports ?? false
  21074. };
  21075. }
  21076. async handleExistingModule(module, isEntry, isPreload) {
  21077. const loadPromise = this.moduleLoadPromises.get(module);
  21078. if (isPreload) {
  21079. return isPreload === RESOLVE_DEPENDENCIES
  21080. ? waitForDependencyResolution(loadPromise)
  21081. : loadPromise;
  21082. }
  21083. if (isEntry) {
  21084. // This reverts the changes in addEntryWithImplicitDependants and needs to
  21085. // be performed atomically
  21086. module.info.isEntry = true;
  21087. this.implicitEntryModules.delete(module);
  21088. for (const dependant of module.implicitlyLoadedAfter) {
  21089. dependant.implicitlyLoadedBefore.delete(module);
  21090. }
  21091. module.implicitlyLoadedAfter.clear();
  21092. }
  21093. return this.fetchModuleDependencies(module, ...(await loadPromise));
  21094. }
  21095. handleInvalidResolvedId(resolvedId, source, importer, attributes) {
  21096. if (resolvedId === null) {
  21097. if (isRelative(source)) {
  21098. return error(logUnresolvedImport(source, importer));
  21099. }
  21100. this.options.onLog(LOGLEVEL_WARN, logUnresolvedImportTreatedAsExternal(source, importer));
  21101. return {
  21102. attributes,
  21103. external: true,
  21104. id: source,
  21105. meta: {},
  21106. moduleSideEffects: this.hasModuleSideEffects(source, true),
  21107. resolvedBy: 'rollup',
  21108. syntheticNamedExports: false
  21109. };
  21110. }
  21111. else if (resolvedId.external && resolvedId.syntheticNamedExports) {
  21112. this.options.onLog(LOGLEVEL_WARN, logExternalSyntheticExports(source, importer));
  21113. }
  21114. return resolvedId;
  21115. }
  21116. async loadEntryModule(unresolvedId, isEntry, importer, implicitlyLoadedBefore, isLoadForManualChunks = false, importerAttributes) {
  21117. const resolveIdResult = await resolveId(unresolvedId, importer, this.options.preserveSymlinks, this.pluginDriver, this.resolveId, null, EMPTY_OBJECT, true, EMPTY_OBJECT, importerAttributes, this.options.fs);
  21118. if (resolveIdResult == null) {
  21119. return error(implicitlyLoadedBefore === null
  21120. ? logUnresolvedEntry(unresolvedId)
  21121. : logUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore));
  21122. }
  21123. const isExternalModules = typeof resolveIdResult === 'object' && resolveIdResult.external;
  21124. if (resolveIdResult === false || isExternalModules) {
  21125. return error(implicitlyLoadedBefore === null
  21126. ? isExternalModules && isLoadForManualChunks
  21127. ? logExternalModulesCannotBeIncludedInManualChunks(unresolvedId)
  21128. : logEntryCannotBeExternal(unresolvedId)
  21129. : logImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore));
  21130. }
  21131. return this.fetchModule(this.getResolvedIdWithDefaults(typeof resolveIdResult === 'object'
  21132. ? resolveIdResult
  21133. : { id: resolveIdResult }, EMPTY_OBJECT), undefined, isEntry, false);
  21134. }
  21135. async resolveDynamicImport(module, specifier, importer, attributes) {
  21136. const resolution = await this.pluginDriver.hookFirst('resolveDynamicImport', [
  21137. specifier,
  21138. importer,
  21139. { attributes, importerAttributes: module.info.attributes }
  21140. ]);
  21141. if (typeof specifier !== 'string') {
  21142. if (typeof resolution === 'string') {
  21143. return resolution;
  21144. }
  21145. if (!resolution) {
  21146. return null;
  21147. }
  21148. return this.getResolvedIdWithDefaults(resolution, attributes);
  21149. }
  21150. if (resolution == null) {
  21151. const existingResolution = module.resolvedIds[specifier];
  21152. if (existingResolution) {
  21153. if (doAttributesDiffer(existingResolution.attributes, attributes)) {
  21154. this.options.onLog(LOGLEVEL_WARN, logInconsistentImportAttributes(existingResolution.attributes, attributes, specifier, importer));
  21155. }
  21156. return existingResolution;
  21157. }
  21158. return (module.resolvedIds[specifier] = this.handleInvalidResolvedId(await this.resolveId(specifier, module.id, EMPTY_OBJECT, false, attributes, module.info.attributes), specifier, module.id, attributes));
  21159. }
  21160. return this.handleInvalidResolvedId(this.getResolvedIdWithDefaults(this.getNormalizedResolvedIdWithoutDefaults(resolution, importer, specifier), attributes), specifier, importer, attributes);
  21161. }
  21162. }
  21163. function normalizeRelativeExternalId(source, importer) {
  21164. return isRelative(source)
  21165. ? importer
  21166. ? resolve$1(importer, '..', source)
  21167. : resolve$1(source)
  21168. : source;
  21169. }
  21170. function addChunkNamesToModule(module, { fileName, name }, isUserDefined, priority) {
  21171. if (fileName !== null) {
  21172. module.chunkFileNames.add(fileName);
  21173. }
  21174. else if (name !== null) {
  21175. // Always keep chunkNames sorted by priority
  21176. let namePosition = 0;
  21177. while (module.chunkNames[namePosition]?.priority < priority)
  21178. namePosition++;
  21179. module.chunkNames.splice(namePosition, 0, { isUserDefined, name, priority });
  21180. }
  21181. }
  21182. function isNotAbsoluteExternal(id, source, makeAbsoluteExternalsRelative) {
  21183. return (makeAbsoluteExternalsRelative === true ||
  21184. (makeAbsoluteExternalsRelative === 'ifRelativeSource' && isRelative(source)) ||
  21185. !isAbsolute$1(id));
  21186. }
  21187. async function waitForDependencyResolution(loadPromise) {
  21188. const [resolveStaticDependencyPromises, resolveDynamicImportPromises] = await loadPromise;
  21189. return Promise.all([...resolveStaticDependencyPromises, ...resolveDynamicImportPromises]);
  21190. }
  21191. function generateAssetFileName(name, names, source, originalFileName, originalFileNames, sourceHash, outputOptions, bundle, inputOptions) {
  21192. const emittedName = outputOptions.sanitizeFileName(name || 'asset');
  21193. return makeUnique(renderNamePattern(typeof outputOptions.assetFileNames === 'function'
  21194. ? outputOptions.assetFileNames({
  21195. // Additionally, this should be non-enumerable in the next major
  21196. get name() {
  21197. warnDeprecation('Accessing the "name" property of emitted assets when generating the file name is deprecated. Use the "names" property instead.', URL_GENERATEBUNDLE, false, inputOptions);
  21198. return name;
  21199. },
  21200. names,
  21201. // Additionally, this should be non-enumerable in the next major
  21202. get originalFileName() {
  21203. warnDeprecation('Accessing the "originalFileName" property of emitted assets when generating the file name is deprecated. Use the "originalFileNames" property instead.', URL_GENERATEBUNDLE, false, inputOptions);
  21204. return originalFileName;
  21205. },
  21206. originalFileNames,
  21207. source,
  21208. type: 'asset'
  21209. })
  21210. : outputOptions.assetFileNames, 'output.assetFileNames', {
  21211. ext: () => extname(emittedName).slice(1),
  21212. extname: () => extname(emittedName),
  21213. hash: size => sourceHash.slice(0, Math.min(Math.max(0, size || DEFAULT_HASH_SIZE), MAX_HASH_SIZE)),
  21214. name: () => emittedName.slice(0, Math.max(0, emittedName.length - extname(emittedName).length))
  21215. }), bundle);
  21216. }
  21217. function reserveFileNameInBundle(fileName, { bundle }, log) {
  21218. if (bundle[lowercaseBundleKeys].has(fileName.toLowerCase())) {
  21219. log(LOGLEVEL_WARN, logFileNameConflict(fileName));
  21220. }
  21221. else {
  21222. bundle[fileName] = FILE_PLACEHOLDER;
  21223. }
  21224. }
  21225. const emittedFileTypes = new Set(['chunk', 'asset', 'prebuilt-chunk']);
  21226. function hasValidType(emittedFile) {
  21227. return Boolean(emittedFile &&
  21228. emittedFileTypes.has(emittedFile.type));
  21229. }
  21230. function hasValidName(emittedFile) {
  21231. const validatedName = emittedFile.fileName || emittedFile.name;
  21232. return !validatedName || (typeof validatedName === 'string' && !isPathFragment(validatedName));
  21233. }
  21234. function getValidSource(source, emittedFile, fileReferenceId) {
  21235. if (!(typeof source === 'string' || source instanceof Uint8Array)) {
  21236. const assetName = emittedFile.fileName || emittedFile.name || fileReferenceId;
  21237. 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.`));
  21238. }
  21239. return source;
  21240. }
  21241. function getAssetFileName(file, referenceId) {
  21242. if (typeof file.fileName !== 'string') {
  21243. return error(logAssetNotFinalisedForFileName(file.name || referenceId));
  21244. }
  21245. return file.fileName;
  21246. }
  21247. function getChunkFileName(file, facadeChunkByModule) {
  21248. if (file.fileName) {
  21249. return file.fileName;
  21250. }
  21251. if (facadeChunkByModule) {
  21252. return facadeChunkByModule.get(file.module).getFileName();
  21253. }
  21254. return error(logChunkNotGeneratedForFileName(file.fileName || file.name));
  21255. }
  21256. class FileEmitter {
  21257. constructor(graph, options, baseFileEmitter) {
  21258. this.graph = graph;
  21259. this.options = options;
  21260. this.facadeChunkByModule = null;
  21261. this.nextIdBase = 1;
  21262. this.output = null;
  21263. this.outputFileEmitters = [];
  21264. this.emitFile = (emittedFile) => {
  21265. if (!hasValidType(emittedFile)) {
  21266. return error(logFailedValidation(`Emitted files must be of type "asset", "chunk" or "prebuilt-chunk", received "${emittedFile && emittedFile.type}".`));
  21267. }
  21268. if (emittedFile.type === 'prebuilt-chunk') {
  21269. return this.emitPrebuiltChunk(emittedFile);
  21270. }
  21271. if (!hasValidName(emittedFile)) {
  21272. 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}".`));
  21273. }
  21274. if (emittedFile.type === 'chunk') {
  21275. return this.emitChunk(emittedFile);
  21276. }
  21277. return this.emitAsset(emittedFile);
  21278. };
  21279. this.finaliseAssets = () => {
  21280. for (const [referenceId, emittedFile] of this.filesByReferenceId) {
  21281. if (emittedFile.type === 'asset' && typeof emittedFile.fileName !== 'string')
  21282. return error(logNoAssetSourceSet(emittedFile.name || referenceId));
  21283. }
  21284. };
  21285. this.getFileName = (fileReferenceId) => {
  21286. const emittedFile = this.filesByReferenceId.get(fileReferenceId);
  21287. if (!emittedFile)
  21288. return error(logFileReferenceIdNotFoundForFilename(fileReferenceId));
  21289. if (emittedFile.type === 'chunk') {
  21290. return getChunkFileName(emittedFile, this.facadeChunkByModule);
  21291. }
  21292. if (emittedFile.type === 'prebuilt-chunk') {
  21293. return emittedFile.fileName;
  21294. }
  21295. return getAssetFileName(emittedFile, fileReferenceId);
  21296. };
  21297. this.setAssetSource = (referenceId, requestedSource) => {
  21298. const consumedFile = this.filesByReferenceId.get(referenceId);
  21299. if (!consumedFile)
  21300. return error(logAssetReferenceIdNotFoundForSetSource(referenceId));
  21301. if (consumedFile.type !== 'asset') {
  21302. return error(logFailedValidation(`Asset sources can only be set for emitted assets but "${referenceId}" is an emitted chunk.`));
  21303. }
  21304. if (consumedFile.source !== undefined) {
  21305. return error(logAssetSourceAlreadySet(consumedFile.name || referenceId));
  21306. }
  21307. const source = getValidSource(requestedSource, consumedFile, referenceId);
  21308. if (this.output) {
  21309. this.finalizeAdditionalAsset(consumedFile, source, this.output);
  21310. }
  21311. else {
  21312. consumedFile.source = source;
  21313. for (const emitter of this.outputFileEmitters) {
  21314. emitter.finalizeAdditionalAsset(consumedFile, source, emitter.output);
  21315. }
  21316. }
  21317. };
  21318. this.setChunkInformation = (facadeChunkByModule) => {
  21319. this.facadeChunkByModule = facadeChunkByModule;
  21320. };
  21321. this.setOutputBundle = (bundle, outputOptions) => {
  21322. const getHash = hasherByType[outputOptions.hashCharacters];
  21323. const output = (this.output = {
  21324. bundle,
  21325. fileNamesBySourceHash: new Map(),
  21326. getHash,
  21327. outputOptions
  21328. });
  21329. for (const emittedFile of this.filesByReferenceId.values()) {
  21330. if (emittedFile.fileName) {
  21331. reserveFileNameInBundle(emittedFile.fileName, output, this.options.onLog);
  21332. }
  21333. }
  21334. const consumedAssetsByHash = new Map();
  21335. for (const consumedFile of this.filesByReferenceId.values()) {
  21336. if (consumedFile.type === 'asset' && consumedFile.source !== undefined) {
  21337. if (consumedFile.fileName) {
  21338. this.finalizeAdditionalAsset(consumedFile, consumedFile.source, output);
  21339. }
  21340. else {
  21341. const sourceHash = getHash(consumedFile.source);
  21342. getOrCreate(consumedAssetsByHash, sourceHash, getNewArray).push(consumedFile);
  21343. }
  21344. }
  21345. else if (consumedFile.type === 'prebuilt-chunk') {
  21346. this.output.bundle[consumedFile.fileName] = this.createPrebuiltChunk(consumedFile);
  21347. }
  21348. }
  21349. for (const [sourceHash, consumedFiles] of consumedAssetsByHash) {
  21350. this.finalizeAssetsWithSameSource(consumedFiles, sourceHash, output);
  21351. }
  21352. };
  21353. this.filesByReferenceId = baseFileEmitter
  21354. ? new Map(baseFileEmitter.filesByReferenceId)
  21355. : new Map();
  21356. baseFileEmitter?.addOutputFileEmitter(this);
  21357. }
  21358. addOutputFileEmitter(outputFileEmitter) {
  21359. this.outputFileEmitters.push(outputFileEmitter);
  21360. }
  21361. assignReferenceId(file, idBase) {
  21362. let referenceId = idBase;
  21363. do {
  21364. referenceId = getHash64(referenceId).slice(0, 8).replaceAll('-', '$');
  21365. } while (this.filesByReferenceId.has(referenceId) ||
  21366. this.outputFileEmitters.some(({ filesByReferenceId }) => filesByReferenceId.has(referenceId)));
  21367. file.referenceId = referenceId;
  21368. this.filesByReferenceId.set(referenceId, file);
  21369. for (const { filesByReferenceId } of this.outputFileEmitters) {
  21370. filesByReferenceId.set(referenceId, file);
  21371. }
  21372. return referenceId;
  21373. }
  21374. createPrebuiltChunk(prebuiltChunk) {
  21375. return {
  21376. code: prebuiltChunk.code,
  21377. dynamicImports: [],
  21378. exports: prebuiltChunk.exports || [],
  21379. facadeModuleId: null,
  21380. fileName: prebuiltChunk.fileName,
  21381. implicitlyLoadedBefore: [],
  21382. importedBindings: {},
  21383. imports: [],
  21384. isDynamicEntry: false,
  21385. isEntry: false,
  21386. isImplicitEntry: false,
  21387. map: prebuiltChunk.map || null,
  21388. moduleIds: [],
  21389. modules: {},
  21390. name: prebuiltChunk.fileName,
  21391. preliminaryFileName: prebuiltChunk.fileName,
  21392. referencedFiles: [],
  21393. sourcemapFileName: prebuiltChunk.sourcemapFileName || null,
  21394. type: 'chunk'
  21395. };
  21396. }
  21397. emitAsset(emittedAsset) {
  21398. const source = emittedAsset.source === undefined
  21399. ? undefined
  21400. : getValidSource(emittedAsset.source, emittedAsset, null);
  21401. const originalFileName = emittedAsset.originalFileName || null;
  21402. if (typeof originalFileName === 'string') {
  21403. this.graph.watchFiles[originalFileName] = true;
  21404. }
  21405. const consumedAsset = {
  21406. fileName: emittedAsset.fileName,
  21407. name: emittedAsset.name,
  21408. needsCodeReference: !!emittedAsset.needsCodeReference,
  21409. originalFileName,
  21410. referenceId: '',
  21411. source,
  21412. type: 'asset'
  21413. };
  21414. const referenceId = this.assignReferenceId(consumedAsset, emittedAsset.fileName || emittedAsset.name || String(this.nextIdBase++));
  21415. if (this.output) {
  21416. this.emitAssetWithReferenceId(consumedAsset, this.output);
  21417. }
  21418. else {
  21419. for (const fileEmitter of this.outputFileEmitters) {
  21420. fileEmitter.emitAssetWithReferenceId(consumedAsset, fileEmitter.output);
  21421. }
  21422. }
  21423. return referenceId;
  21424. }
  21425. emitAssetWithReferenceId(consumedAsset, output) {
  21426. const { fileName, source } = consumedAsset;
  21427. if (fileName) {
  21428. reserveFileNameInBundle(fileName, output, this.options.onLog);
  21429. }
  21430. if (source !== undefined) {
  21431. this.finalizeAdditionalAsset(consumedAsset, source, output);
  21432. }
  21433. }
  21434. emitChunk(emittedChunk) {
  21435. if (this.graph.phase > BuildPhase.LOAD_AND_PARSE) {
  21436. return error(logInvalidRollupPhaseForChunkEmission());
  21437. }
  21438. if (typeof emittedChunk.id !== 'string') {
  21439. return error(logFailedValidation(`Emitted chunks need to have a valid string id, received "${emittedChunk.id}"`));
  21440. }
  21441. const consumedChunk = {
  21442. fileName: emittedChunk.fileName,
  21443. module: null,
  21444. name: emittedChunk.name || emittedChunk.id,
  21445. referenceId: '',
  21446. type: 'chunk'
  21447. };
  21448. this.graph.moduleLoader
  21449. .emitChunk(emittedChunk)
  21450. .then(module => (consumedChunk.module = module))
  21451. .catch(() => {
  21452. // Avoid unhandled Promise rejection as the error will be thrown later
  21453. // once module loading has finished
  21454. });
  21455. return this.assignReferenceId(consumedChunk, emittedChunk.id);
  21456. }
  21457. emitPrebuiltChunk(emitPrebuiltChunk) {
  21458. if (typeof emitPrebuiltChunk.code !== 'string') {
  21459. return error(logFailedValidation(`Emitted prebuilt chunks need to have a valid string code, received "${emitPrebuiltChunk.code}".`));
  21460. }
  21461. if (typeof emitPrebuiltChunk.fileName !== 'string' ||
  21462. isPathFragment(emitPrebuiltChunk.fileName)) {
  21463. return error(logFailedValidation(`The "fileName" property of emitted prebuilt chunks must be strings that are neither absolute nor relative paths, received "${emitPrebuiltChunk.fileName}".`));
  21464. }
  21465. const consumedPrebuiltChunk = {
  21466. code: emitPrebuiltChunk.code,
  21467. exports: emitPrebuiltChunk.exports,
  21468. fileName: emitPrebuiltChunk.fileName,
  21469. map: emitPrebuiltChunk.map,
  21470. referenceId: '',
  21471. type: 'prebuilt-chunk'
  21472. };
  21473. const referenceId = this.assignReferenceId(consumedPrebuiltChunk, consumedPrebuiltChunk.fileName);
  21474. if (this.output) {
  21475. this.output.bundle[consumedPrebuiltChunk.fileName] =
  21476. this.createPrebuiltChunk(consumedPrebuiltChunk);
  21477. }
  21478. return referenceId;
  21479. }
  21480. finalizeAdditionalAsset(consumedFile, source, { bundle, fileNamesBySourceHash, getHash, outputOptions }) {
  21481. let { fileName, name, needsCodeReference, originalFileName, referenceId } = consumedFile;
  21482. // Deduplicate assets if an explicit fileName is not provided
  21483. if (!fileName) {
  21484. const sourceHash = getHash(source);
  21485. fileName = fileNamesBySourceHash.get(sourceHash);
  21486. if (!fileName) {
  21487. fileName = generateAssetFileName(name, name ? [name] : [], source, originalFileName, originalFileName ? [originalFileName] : [], sourceHash, outputOptions, bundle, this.options);
  21488. fileNamesBySourceHash.set(sourceHash, fileName);
  21489. }
  21490. }
  21491. // We must not modify the original assets to avoid interaction between outputs
  21492. const assetWithFileName = { ...consumedFile, fileName, source };
  21493. this.filesByReferenceId.set(referenceId, assetWithFileName);
  21494. const existingAsset = bundle[fileName];
  21495. if (existingAsset?.type === 'asset') {
  21496. existingAsset.needsCodeReference &&= needsCodeReference;
  21497. if (name) {
  21498. existingAsset.names.push(name);
  21499. }
  21500. if (originalFileName) {
  21501. existingAsset.originalFileNames.push(originalFileName);
  21502. }
  21503. }
  21504. else {
  21505. const { options } = this;
  21506. bundle[fileName] = {
  21507. fileName,
  21508. get name() {
  21509. // Additionally, this should be non-enumerable in the next major
  21510. warnDeprecation('Accessing the "name" property of emitted assets in the bundle is deprecated. Use the "names" property instead.', URL_GENERATEBUNDLE, false, options);
  21511. return name;
  21512. },
  21513. names: name ? [name] : [],
  21514. needsCodeReference,
  21515. get originalFileName() {
  21516. // Additionally, this should be non-enumerable in the next major
  21517. warnDeprecation('Accessing the "originalFileName" property of emitted assets in the bundle is deprecated. Use the "originalFileNames" property instead.', URL_GENERATEBUNDLE, false, options);
  21518. return originalFileName;
  21519. },
  21520. originalFileNames: originalFileName ? [originalFileName] : [],
  21521. source,
  21522. type: 'asset'
  21523. };
  21524. }
  21525. }
  21526. finalizeAssetsWithSameSource(consumedFiles, sourceHash, { bundle, fileNamesBySourceHash, outputOptions }) {
  21527. const { names, originalFileNames } = getNamesFromAssets(consumedFiles);
  21528. let fileName = '';
  21529. let usedConsumedFile;
  21530. let needsCodeReference = true;
  21531. for (const consumedFile of consumedFiles) {
  21532. needsCodeReference &&= consumedFile.needsCodeReference;
  21533. const assetFileName = generateAssetFileName(consumedFile.name, names, consumedFile.source, consumedFile.originalFileName, originalFileNames, sourceHash, outputOptions, bundle, this.options);
  21534. if (!fileName ||
  21535. assetFileName.length < fileName.length ||
  21536. (assetFileName.length === fileName.length && assetFileName < fileName)) {
  21537. fileName = assetFileName;
  21538. usedConsumedFile = consumedFile;
  21539. }
  21540. }
  21541. fileNamesBySourceHash.set(sourceHash, fileName);
  21542. for (const consumedFile of consumedFiles) {
  21543. // We must not modify the original assets to avoid interaction between outputs
  21544. const assetWithFileName = { ...consumedFile, fileName };
  21545. this.filesByReferenceId.set(consumedFile.referenceId, assetWithFileName);
  21546. }
  21547. const { options } = this;
  21548. bundle[fileName] = {
  21549. fileName,
  21550. get name() {
  21551. // Additionally, this should be non-enumerable in the next major
  21552. warnDeprecation('Accessing the "name" property of emitted assets in the bundle is deprecated. Use the "names" property instead.', URL_GENERATEBUNDLE, false, options);
  21553. return usedConsumedFile.name;
  21554. },
  21555. names,
  21556. needsCodeReference,
  21557. get originalFileName() {
  21558. // Additionally, this should be non-enumerable in the next major
  21559. warnDeprecation('Accessing the "originalFileName" property of emitted assets in the bundle is deprecated. Use the "originalFileNames" property instead.', URL_GENERATEBUNDLE, false, options);
  21560. return usedConsumedFile.originalFileName;
  21561. },
  21562. originalFileNames,
  21563. source: usedConsumedFile.source,
  21564. type: 'asset'
  21565. };
  21566. }
  21567. }
  21568. function getNamesFromAssets(consumedFiles) {
  21569. const names = [];
  21570. const originalFileNames = [];
  21571. for (const { name, originalFileName } of consumedFiles) {
  21572. if (typeof name === 'string') {
  21573. names.push(name);
  21574. }
  21575. if (originalFileName) {
  21576. originalFileNames.push(originalFileName);
  21577. }
  21578. }
  21579. originalFileNames.sort();
  21580. // Sort by length first and then alphabetically so that the order is stable
  21581. // and the shortest names come first
  21582. names.sort((a, b) => a.length - b.length || (a > b ? 1 : a === b ? 0 : -1));
  21583. return { names, originalFileNames };
  21584. }
  21585. function getLogHandler(level, code, logger, pluginName, logLevel) {
  21586. if (logLevelPriority[level] < logLevelPriority[logLevel]) {
  21587. return doNothing;
  21588. }
  21589. return (log, pos) => {
  21590. if (pos != null) {
  21591. logger(LOGLEVEL_WARN, logInvalidLogPosition(pluginName));
  21592. }
  21593. log = normalizeLog(log);
  21594. if (log.code && !log.pluginCode) {
  21595. log.pluginCode = log.code;
  21596. }
  21597. log.code = code;
  21598. log.plugin = pluginName;
  21599. logger(level, log);
  21600. };
  21601. }
  21602. function getPluginContext(plugin, pluginCache, graph, options, fileEmitter, existingPluginNames) {
  21603. const { logLevel, onLog } = options;
  21604. let cacheable = true;
  21605. if (typeof plugin.cacheKey !== 'string') {
  21606. if (plugin.name.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
  21607. plugin.name.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX) ||
  21608. existingPluginNames.has(plugin.name)) {
  21609. cacheable = false;
  21610. }
  21611. else {
  21612. existingPluginNames.add(plugin.name);
  21613. }
  21614. }
  21615. let cacheInstance;
  21616. if (!pluginCache) {
  21617. cacheInstance = NO_CACHE;
  21618. }
  21619. else if (cacheable) {
  21620. const cacheKey = plugin.cacheKey || plugin.name;
  21621. cacheInstance = createPluginCache(pluginCache[cacheKey] || (pluginCache[cacheKey] = Object.create(null)));
  21622. }
  21623. else {
  21624. cacheInstance = getCacheForUncacheablePlugin(plugin.name);
  21625. }
  21626. return {
  21627. addWatchFile(id) {
  21628. graph.watchFiles[id] = true;
  21629. },
  21630. cache: cacheInstance,
  21631. debug: getLogHandler(LOGLEVEL_DEBUG, 'PLUGIN_LOG', onLog, plugin.name, logLevel),
  21632. emitFile: fileEmitter.emitFile.bind(fileEmitter),
  21633. error(error_) {
  21634. return error(logPluginError(normalizeLog(error_), plugin.name));
  21635. },
  21636. fs: options.fs,
  21637. getFileName: fileEmitter.getFileName,
  21638. getModuleIds: () => graph.modulesById.keys(),
  21639. getModuleInfo: graph.getModuleInfo,
  21640. getWatchFiles: () => Object.keys(graph.watchFiles),
  21641. info: getLogHandler(LOGLEVEL_INFO, 'PLUGIN_LOG', onLog, plugin.name, logLevel),
  21642. load(resolvedId) {
  21643. return graph.moduleLoader.preloadModule(resolvedId);
  21644. },
  21645. meta: {
  21646. rollupVersion: version,
  21647. watchMode: graph.watchMode
  21648. },
  21649. parse: parseAst,
  21650. resolve(source, importer, { attributes, custom, isEntry, skipSelf, importerAttributes } = BLANK) {
  21651. skipSelf ??= true;
  21652. return graph.moduleLoader.resolveId(source, importer, custom, isEntry, attributes || EMPTY_OBJECT, importerAttributes, skipSelf ? [{ importer, plugin, source }] : null);
  21653. },
  21654. setAssetSource: fileEmitter.setAssetSource,
  21655. warn: getLogHandler(LOGLEVEL_WARN, 'PLUGIN_WARNING', onLog, plugin.name, logLevel)
  21656. };
  21657. }
  21658. function ensureArray(items) {
  21659. if (Array.isArray(items)) {
  21660. return items.filter(Boolean);
  21661. }
  21662. if (items) {
  21663. return [items];
  21664. }
  21665. return [];
  21666. }
  21667. function getMatcherString(glob, cwd) {
  21668. if (glob.startsWith('**') || isAbsolute$1(glob)) {
  21669. return normalize(glob);
  21670. }
  21671. const resolved = resolve$1(cwd, glob);
  21672. return normalize(resolved);
  21673. }
  21674. function patternToIdFilter(pattern) {
  21675. if (pattern instanceof RegExp) {
  21676. return (id) => {
  21677. const normalizedId = normalize(id);
  21678. const result = pattern.test(normalizedId);
  21679. pattern.lastIndex = 0;
  21680. return result;
  21681. };
  21682. }
  21683. const cwd = process.cwd();
  21684. const glob = getMatcherString(pattern, cwd);
  21685. const matcher = picomatch(glob, { dot: true });
  21686. return (id) => {
  21687. const normalizedId = normalize(id);
  21688. return matcher(normalizedId);
  21689. };
  21690. }
  21691. function patternToCodeFilter(pattern) {
  21692. if (pattern instanceof RegExp) {
  21693. return (code) => {
  21694. const result = pattern.test(code);
  21695. pattern.lastIndex = 0;
  21696. return result;
  21697. };
  21698. }
  21699. return (code) => code.includes(pattern);
  21700. }
  21701. function createFilter(exclude, include) {
  21702. if (!exclude && !include) {
  21703. return;
  21704. }
  21705. return input => {
  21706. if (exclude?.some(filter => filter(input))) {
  21707. return false;
  21708. }
  21709. if (include?.some(filter => filter(input))) {
  21710. return true;
  21711. }
  21712. return !(include && include.length > 0);
  21713. };
  21714. }
  21715. function normalizeFilter(filter) {
  21716. if (typeof filter === 'string' || filter instanceof RegExp) {
  21717. return {
  21718. include: [filter]
  21719. };
  21720. }
  21721. if (Array.isArray(filter)) {
  21722. return {
  21723. include: filter
  21724. };
  21725. }
  21726. return {
  21727. exclude: filter.exclude ? ensureArray(filter.exclude) : undefined,
  21728. include: filter.include ? ensureArray(filter.include) : undefined
  21729. };
  21730. }
  21731. function createIdFilter(filter) {
  21732. if (!filter)
  21733. return;
  21734. const { exclude, include } = normalizeFilter(filter);
  21735. const excludeFilter = exclude?.map(patternToIdFilter);
  21736. const includeFilter = include?.map(patternToIdFilter);
  21737. return createFilter(excludeFilter, includeFilter);
  21738. }
  21739. function createCodeFilter(filter) {
  21740. if (!filter)
  21741. return;
  21742. const { exclude, include } = normalizeFilter(filter);
  21743. const excludeFilter = exclude?.map(patternToCodeFilter);
  21744. const includeFilter = include?.map(patternToCodeFilter);
  21745. return createFilter(excludeFilter, includeFilter);
  21746. }
  21747. function createFilterForId(filter) {
  21748. const filterFunction = createIdFilter(filter);
  21749. return filterFunction ? id => !!filterFunction(id) : undefined;
  21750. }
  21751. function createFilterForTransform(idFilter, codeFilter) {
  21752. if (!idFilter && !codeFilter)
  21753. return;
  21754. const idFilterFunction = createIdFilter(idFilter);
  21755. const codeFilterFunction = createCodeFilter(codeFilter);
  21756. return (id, code) => {
  21757. let fallback = true;
  21758. if (idFilterFunction) {
  21759. fallback &&= idFilterFunction(id);
  21760. }
  21761. if (!fallback) {
  21762. return false;
  21763. }
  21764. if (codeFilterFunction) {
  21765. fallback &&= codeFilterFunction(code);
  21766. }
  21767. return fallback;
  21768. };
  21769. }
  21770. // This will make sure no input hook is omitted
  21771. const inputHookNames = {
  21772. buildEnd: 1,
  21773. buildStart: 1,
  21774. closeBundle: 1,
  21775. closeWatcher: 1,
  21776. load: 1,
  21777. moduleParsed: 1,
  21778. onLog: 1,
  21779. options: 1,
  21780. resolveDynamicImport: 1,
  21781. resolveId: 1,
  21782. shouldTransformCachedModule: 1,
  21783. transform: 1,
  21784. watchChange: 1
  21785. };
  21786. const inputHooks = Object.keys(inputHookNames);
  21787. class PluginDriver {
  21788. constructor(graph, options, userPlugins, pluginCache, basePluginDriver) {
  21789. this.graph = graph;
  21790. this.options = options;
  21791. this.pluginCache = pluginCache;
  21792. this.sortedPlugins = new Map();
  21793. this.unfulfilledActions = new Set();
  21794. this.compiledPluginFilters = {
  21795. idOnlyFilter: new WeakMap(),
  21796. transformFilter: new WeakMap()
  21797. };
  21798. this.fileEmitter = new FileEmitter(graph, options, basePluginDriver && basePluginDriver.fileEmitter);
  21799. this.emitFile = this.fileEmitter.emitFile.bind(this.fileEmitter);
  21800. this.getFileName = this.fileEmitter.getFileName.bind(this.fileEmitter);
  21801. this.finaliseAssets = this.fileEmitter.finaliseAssets.bind(this.fileEmitter);
  21802. this.setChunkInformation = this.fileEmitter.setChunkInformation.bind(this.fileEmitter);
  21803. this.setOutputBundle = this.fileEmitter.setOutputBundle.bind(this.fileEmitter);
  21804. this.plugins = [...(basePluginDriver ? basePluginDriver.plugins : []), ...userPlugins];
  21805. const existingPluginNames = new Set();
  21806. this.pluginContexts = new Map(this.plugins.map(plugin => [
  21807. plugin,
  21808. getPluginContext(plugin, pluginCache, graph, options, this.fileEmitter, existingPluginNames)
  21809. ]));
  21810. if (basePluginDriver) {
  21811. for (const plugin of userPlugins) {
  21812. for (const hook of inputHooks) {
  21813. if (hook in plugin) {
  21814. options.onLog(LOGLEVEL_WARN, logInputHookInOutputPlugin(plugin.name, hook));
  21815. }
  21816. }
  21817. }
  21818. }
  21819. }
  21820. createOutputPluginDriver(plugins) {
  21821. return new PluginDriver(this.graph, this.options, plugins, this.pluginCache, this);
  21822. }
  21823. getUnfulfilledHookActions() {
  21824. return this.unfulfilledActions;
  21825. }
  21826. // chains, first non-null result stops and returns
  21827. hookFirst(hookName, parameters, replaceContext, skipped) {
  21828. return this.hookFirstAndGetPlugin(hookName, parameters, replaceContext, skipped).then(result => result && result[0]);
  21829. }
  21830. // chains, first non-null result stops and returns result and last plugin
  21831. async hookFirstAndGetPlugin(hookName, parameters, replaceContext, skipped) {
  21832. for (const plugin of this.getSortedPlugins(hookName)) {
  21833. if (skipped?.has(plugin))
  21834. continue;
  21835. const result = await this.runHook(hookName, parameters, plugin, replaceContext);
  21836. if (result != null)
  21837. return [result, plugin];
  21838. }
  21839. return null;
  21840. }
  21841. // chains synchronously, first non-null result stops and returns
  21842. hookFirstSync(hookName, parameters, replaceContext) {
  21843. for (const plugin of this.getSortedPlugins(hookName)) {
  21844. const result = this.runHookSync(hookName, parameters, plugin, replaceContext);
  21845. if (result != null)
  21846. return result;
  21847. }
  21848. return null;
  21849. }
  21850. // parallel, ignores returns
  21851. async hookParallel(hookName, parameters, replaceContext) {
  21852. const parallelPromises = [];
  21853. for (const plugin of this.getSortedPlugins(hookName)) {
  21854. if (plugin[hookName].sequential) {
  21855. await Promise.all(parallelPromises);
  21856. parallelPromises.length = 0;
  21857. await this.runHook(hookName, parameters, plugin, replaceContext);
  21858. }
  21859. else {
  21860. parallelPromises.push(this.runHook(hookName, parameters, plugin, replaceContext));
  21861. }
  21862. }
  21863. await Promise.all(parallelPromises);
  21864. }
  21865. // chains, reduces returned value, handling the reduced value as the first hook argument
  21866. hookReduceArg0(hookName, [argument0, ...rest], reduce, replaceContext) {
  21867. let promise = Promise.resolve(argument0);
  21868. for (const plugin of this.getSortedPlugins(hookName)) {
  21869. promise = promise.then(argument0 => this.runHook(hookName, [argument0, ...rest], plugin, replaceContext).then(result => reduce.call(this.pluginContexts.get(plugin), argument0, result, plugin)));
  21870. }
  21871. return promise;
  21872. }
  21873. // chains synchronously, reduces returned value, handling the reduced value as the first hook argument
  21874. hookReduceArg0Sync(hookName, [argument0, ...rest], reduce, replaceContext) {
  21875. for (const plugin of this.getSortedPlugins(hookName)) {
  21876. const parameters = [argument0, ...rest];
  21877. const result = this.runHookSync(hookName, parameters, plugin, replaceContext);
  21878. argument0 = reduce.call(this.pluginContexts.get(plugin), argument0, result, plugin);
  21879. }
  21880. return argument0;
  21881. }
  21882. // chains, reduces returned value to type string, handling the reduced value separately. permits hooks as values.
  21883. async hookReduceValue(hookName, initialValue, parameters, reducer) {
  21884. const results = [];
  21885. const parallelResults = [];
  21886. for (const plugin of this.getSortedPlugins(hookName, validateAddonPluginHandler)) {
  21887. if (plugin[hookName].sequential) {
  21888. results.push(...(await Promise.all(parallelResults)));
  21889. parallelResults.length = 0;
  21890. results.push(await this.runHook(hookName, parameters, plugin));
  21891. }
  21892. else {
  21893. parallelResults.push(this.runHook(hookName, parameters, plugin));
  21894. }
  21895. }
  21896. results.push(...(await Promise.all(parallelResults)));
  21897. return results.reduce(reducer, await initialValue);
  21898. }
  21899. // chains synchronously, reduces returned value to type T, handling the reduced value separately. permits hooks as values.
  21900. hookReduceValueSync(hookName, initialValue, parameters, reduce, replaceContext) {
  21901. let accumulator = initialValue;
  21902. for (const plugin of this.getSortedPlugins(hookName)) {
  21903. const result = this.runHookSync(hookName, parameters, plugin, replaceContext);
  21904. accumulator = reduce.call(this.pluginContexts.get(plugin), accumulator, result, plugin);
  21905. }
  21906. return accumulator;
  21907. }
  21908. // chains, ignores returns
  21909. hookSeq(hookName, parameters, replaceContext) {
  21910. let promise = Promise.resolve();
  21911. for (const plugin of this.getSortedPlugins(hookName)) {
  21912. promise = promise.then(() => this.runHook(hookName, parameters, plugin, replaceContext));
  21913. }
  21914. return promise.then(noReturn);
  21915. }
  21916. getSortedPlugins(hookName, validateHandler) {
  21917. return getOrCreate(this.sortedPlugins, hookName, () => getSortedValidatedPlugins(hookName, this.plugins, validateHandler));
  21918. }
  21919. // Implementation signature
  21920. runHook(hookName, parameters, plugin, replaceContext) {
  21921. // We always filter for plugins that support the hook before running it
  21922. const hook = plugin[hookName];
  21923. const handler = typeof hook === 'object' ? hook.handler : hook;
  21924. if (typeof hook === 'object' && 'filter' in hook && hook.filter) {
  21925. if (hookName === 'transform') {
  21926. const filter = hook.filter;
  21927. const hookParameters = parameters;
  21928. const compiledFilter = getOrCreate(this.compiledPluginFilters.transformFilter, filter, () => createFilterForTransform(filter.id, filter.code));
  21929. if (compiledFilter && !compiledFilter(hookParameters[1], hookParameters[0])) {
  21930. return Promise.resolve();
  21931. }
  21932. }
  21933. else if (hookName === 'resolveId' || hookName === 'load') {
  21934. const filter = hook.filter;
  21935. const hookParameters = parameters;
  21936. const compiledFilter = getOrCreate(this.compiledPluginFilters.idOnlyFilter, filter, () => createFilterForId(filter.id));
  21937. if (compiledFilter && !compiledFilter(hookParameters[0])) {
  21938. return Promise.resolve();
  21939. }
  21940. }
  21941. }
  21942. let context = this.pluginContexts.get(plugin);
  21943. if (replaceContext) {
  21944. context = replaceContext(context, plugin);
  21945. }
  21946. let action = null;
  21947. return Promise.resolve()
  21948. .then(() => {
  21949. if (typeof handler !== 'function') {
  21950. return handler;
  21951. }
  21952. // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
  21953. const hookResult = handler.apply(context, parameters);
  21954. if (!hookResult?.then) {
  21955. // short circuit for non-thenables and non-Promises
  21956. return hookResult;
  21957. }
  21958. // Track pending hook actions to properly error out when
  21959. // unfulfilled promises cause rollup to abruptly and confusingly
  21960. // exit with a successful 0 return code but without producing any
  21961. // output, errors or warnings.
  21962. action = [plugin.name, hookName, parameters];
  21963. this.unfulfilledActions.add(action);
  21964. // Although it would be more elegant to just return hookResult here
  21965. // and put the .then() handler just above the .catch() handler below,
  21966. // doing so would subtly change the defacto async event dispatch order
  21967. // which at least one test and some plugins in the wild may depend on.
  21968. return Promise.resolve(hookResult).then(result => {
  21969. // action was fulfilled
  21970. this.unfulfilledActions.delete(action);
  21971. return result;
  21972. });
  21973. })
  21974. .catch(error_ => {
  21975. if (action !== null) {
  21976. // action considered to be fulfilled since error being handled
  21977. this.unfulfilledActions.delete(action);
  21978. }
  21979. return error(logPluginError(error_, plugin.name, { hook: hookName }));
  21980. });
  21981. }
  21982. /**
  21983. * Run a sync plugin hook and return the result.
  21984. * @param hookName Name of the plugin hook. Must be in `PluginHooks`.
  21985. * @param args Arguments passed to the plugin hook.
  21986. * @param plugin The acutal plugin
  21987. * @param replaceContext When passed, the plugin context can be overridden.
  21988. */
  21989. runHookSync(hookName, parameters, plugin, replaceContext) {
  21990. const hook = plugin[hookName];
  21991. const handler = typeof hook === 'object' ? hook.handler : hook;
  21992. let context = this.pluginContexts.get(plugin);
  21993. if (replaceContext) {
  21994. context = replaceContext(context, plugin);
  21995. }
  21996. try {
  21997. // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
  21998. return handler.apply(context, parameters);
  21999. }
  22000. catch (error_) {
  22001. return error(logPluginError(error_, plugin.name, { hook: hookName }));
  22002. }
  22003. }
  22004. }
  22005. function getSortedValidatedPlugins(hookName, plugins, validateHandler = validateFunctionPluginHandler) {
  22006. const pre = [];
  22007. const normal = [];
  22008. const post = [];
  22009. for (const plugin of plugins) {
  22010. const hook = plugin[hookName];
  22011. if (hook) {
  22012. if (typeof hook === 'object') {
  22013. validateHandler(hook.handler, hookName, plugin);
  22014. if (hook.order === 'pre') {
  22015. pre.push(plugin);
  22016. continue;
  22017. }
  22018. if (hook.order === 'post') {
  22019. post.push(plugin);
  22020. continue;
  22021. }
  22022. }
  22023. else {
  22024. validateHandler(hook, hookName, plugin);
  22025. }
  22026. normal.push(plugin);
  22027. }
  22028. }
  22029. return [...pre, ...normal, ...post];
  22030. }
  22031. function validateFunctionPluginHandler(handler, hookName, plugin) {
  22032. if (typeof handler !== 'function') {
  22033. error(logInvalidFunctionPluginHook(hookName, plugin.name));
  22034. }
  22035. }
  22036. function validateAddonPluginHandler(handler, hookName, plugin) {
  22037. if (typeof handler !== 'string' && typeof handler !== 'function') {
  22038. return error(logInvalidAddonPluginHook(hookName, plugin.name));
  22039. }
  22040. }
  22041. function noReturn() { }
  22042. class Queue {
  22043. constructor(maxParallel) {
  22044. this.maxParallel = maxParallel;
  22045. this.queue = [];
  22046. this.workerCount = 0;
  22047. }
  22048. run(task) {
  22049. return new Promise((resolve, reject) => {
  22050. this.queue.push({ reject, resolve, task });
  22051. this.work();
  22052. });
  22053. }
  22054. async work() {
  22055. if (this.workerCount >= this.maxParallel)
  22056. return;
  22057. this.workerCount++;
  22058. let entry;
  22059. while ((entry = this.queue.shift())) {
  22060. const { reject, resolve, task } = entry;
  22061. try {
  22062. const result = await task();
  22063. resolve(result);
  22064. }
  22065. catch (error) {
  22066. reject(error);
  22067. }
  22068. }
  22069. this.workerCount--;
  22070. }
  22071. }
  22072. function normalizeEntryModules(entryModules) {
  22073. if (Array.isArray(entryModules)) {
  22074. return entryModules.map(id => ({
  22075. fileName: null,
  22076. id,
  22077. implicitlyLoadedAfter: [],
  22078. importer: undefined,
  22079. name: null
  22080. }));
  22081. }
  22082. return Object.entries(entryModules).map(([name, id]) => ({
  22083. fileName: null,
  22084. id,
  22085. implicitlyLoadedAfter: [],
  22086. importer: undefined,
  22087. name
  22088. }));
  22089. }
  22090. class Graph {
  22091. constructor(options, watcher) {
  22092. this.options = options;
  22093. this.astLru = flru(5);
  22094. this.cachedModules = new Map();
  22095. this.deoptimizationTracker = new EntityPathTracker();
  22096. this.entryModules = [];
  22097. this.modulesById = new Map();
  22098. this.needsTreeshakingPass = false;
  22099. this.newlyIncludedVariableInits = new Set();
  22100. this.phase = BuildPhase.LOAD_AND_PARSE;
  22101. this.scope = new GlobalScope();
  22102. this.watchFiles = Object.create(null);
  22103. this.watchMode = false;
  22104. this.externalModules = [];
  22105. this.implicitEntryModules = [];
  22106. this.modules = [];
  22107. this.getModuleInfo = (moduleId) => {
  22108. const foundModule = this.modulesById.get(moduleId);
  22109. if (!foundModule)
  22110. return null;
  22111. return foundModule.info;
  22112. };
  22113. if (options.cache !== false) {
  22114. if (options.cache?.modules) {
  22115. for (const module of options.cache.modules)
  22116. this.cachedModules.set(module.id, module);
  22117. }
  22118. this.pluginCache = options.cache?.plugins || Object.create(null);
  22119. // increment access counter
  22120. for (const name in this.pluginCache) {
  22121. const cache = this.pluginCache[name];
  22122. for (const value of Object.values(cache))
  22123. value[0]++;
  22124. }
  22125. }
  22126. if (watcher) {
  22127. this.watchMode = true;
  22128. const handleChange = (...parameters) => this.pluginDriver.hookParallel('watchChange', parameters);
  22129. const handleClose = () => this.pluginDriver.hookParallel('closeWatcher', []);
  22130. watcher.onCurrentRun('change', handleChange);
  22131. watcher.onCurrentRun('close', handleClose);
  22132. }
  22133. this.pluginDriver = new PluginDriver(this, options, options.plugins, this.pluginCache);
  22134. this.moduleLoader = new ModuleLoader(this, this.modulesById, this.options, this.pluginDriver);
  22135. this.fileOperationQueue = new Queue(options.maxParallelFileOps);
  22136. this.pureFunctions = getPureFunctions(options);
  22137. }
  22138. async build() {
  22139. timeStart('generate module graph', 2);
  22140. await this.generateModuleGraph();
  22141. timeEnd('generate module graph', 2);
  22142. timeStart('sort and bind modules', 2);
  22143. this.phase = BuildPhase.ANALYSE;
  22144. this.sortAndBindModules();
  22145. timeEnd('sort and bind modules', 2);
  22146. timeStart('mark included statements', 2);
  22147. this.includeStatements();
  22148. timeEnd('mark included statements', 2);
  22149. this.phase = BuildPhase.GENERATE;
  22150. }
  22151. getCache() {
  22152. // handle plugin cache eviction
  22153. for (const name in this.pluginCache) {
  22154. const cache = this.pluginCache[name];
  22155. let allDeleted = true;
  22156. for (const [key, value] of Object.entries(cache)) {
  22157. if (value[0] >= this.options.experimentalCacheExpiry)
  22158. delete cache[key];
  22159. else
  22160. allDeleted = false;
  22161. }
  22162. if (allDeleted)
  22163. delete this.pluginCache[name];
  22164. }
  22165. return {
  22166. modules: this.modules.map(module => module.toJSON()),
  22167. plugins: this.pluginCache
  22168. };
  22169. }
  22170. async generateModuleGraph() {
  22171. ({ entryModules: this.entryModules, implicitEntryModules: this.implicitEntryModules } =
  22172. await this.moduleLoader.addEntryModules(normalizeEntryModules(this.options.input), true));
  22173. if (this.entryModules.length === 0) {
  22174. throw new Error('You must supply options.input to rollup');
  22175. }
  22176. for (const module of this.modulesById.values()) {
  22177. module.cacheInfoGetters();
  22178. if (module instanceof Module) {
  22179. this.modules.push(module);
  22180. }
  22181. else {
  22182. this.externalModules.push(module);
  22183. }
  22184. }
  22185. }
  22186. includeStatements() {
  22187. const entryModules = [...this.entryModules, ...this.implicitEntryModules];
  22188. for (const module of entryModules) {
  22189. markModuleAndImpureDependenciesAsExecuted(module);
  22190. }
  22191. if (this.options.treeshake) {
  22192. let treeshakingPass = 1;
  22193. this.newlyIncludedVariableInits.clear();
  22194. do {
  22195. timeStart(`treeshaking pass ${treeshakingPass}`, 3);
  22196. this.needsTreeshakingPass = false;
  22197. for (const module of this.modules) {
  22198. if (module.isExecuted) {
  22199. module.hasTreeShakingPassStarted = true;
  22200. if (module.info.moduleSideEffects === 'no-treeshake') {
  22201. module.includeAllInBundle();
  22202. }
  22203. else {
  22204. module.include();
  22205. }
  22206. for (const entity of this.newlyIncludedVariableInits) {
  22207. this.newlyIncludedVariableInits.delete(entity);
  22208. entity.include(createInclusionContext(), false);
  22209. }
  22210. }
  22211. }
  22212. if (treeshakingPass === 1) {
  22213. // We only include exports after the first pass to avoid issues with
  22214. // the TDZ detection logic
  22215. for (const module of entryModules) {
  22216. if (module.preserveSignature !== false) {
  22217. module.includeAllExports();
  22218. this.needsTreeshakingPass = true;
  22219. }
  22220. }
  22221. }
  22222. timeEnd(`treeshaking pass ${treeshakingPass++}`, 3);
  22223. } while (this.needsTreeshakingPass);
  22224. }
  22225. else {
  22226. for (const module of this.modules)
  22227. module.includeAllInBundle();
  22228. }
  22229. for (const externalModule of this.externalModules)
  22230. externalModule.warnUnusedImports();
  22231. for (const module of this.implicitEntryModules) {
  22232. for (const dependant of module.implicitlyLoadedAfter) {
  22233. if (!(dependant.info.isEntry || dependant.isIncluded())) {
  22234. error(logImplicitDependantIsNotIncluded(dependant));
  22235. }
  22236. }
  22237. }
  22238. }
  22239. sortAndBindModules() {
  22240. const { orderedModules, cyclePaths } = analyseModuleExecution(this.entryModules);
  22241. for (const cyclePath of cyclePaths) {
  22242. this.options.onLog(LOGLEVEL_WARN, logCircularDependency(cyclePath));
  22243. }
  22244. this.modules = orderedModules;
  22245. for (const module of this.modules) {
  22246. module.bindReferences();
  22247. }
  22248. this.warnForMissingExports();
  22249. }
  22250. warnForMissingExports() {
  22251. for (const module of this.modules) {
  22252. for (const importDescription of module.importDescriptions.values()) {
  22253. if (importDescription.name !== '*' && importDescription.phase !== 'source') {
  22254. const [variable, options] = importDescription.module.getVariableForExportName(importDescription.name, { importChain: [module.id] });
  22255. if (!variable) {
  22256. module.log(LOGLEVEL_WARN, logMissingExport(importDescription.name, module.id, importDescription.module.id, !!options?.missingButExportExists), importDescription.start);
  22257. }
  22258. }
  22259. }
  22260. }
  22261. }
  22262. }
  22263. function formatAction([pluginName, hookName, parameters]) {
  22264. const action = `(${pluginName}) ${hookName}`;
  22265. const s = JSON.stringify;
  22266. switch (hookName) {
  22267. case 'resolveId': {
  22268. return `${action} ${s(parameters[0])} ${s(parameters[1])}`;
  22269. }
  22270. case 'load': {
  22271. return `${action} ${s(parameters[0])}`;
  22272. }
  22273. case 'transform': {
  22274. return `${action} ${s(parameters[1])}`;
  22275. }
  22276. case 'shouldTransformCachedModule': {
  22277. return `${action} ${s(parameters[0].id)}`;
  22278. }
  22279. case 'moduleParsed': {
  22280. return `${action} ${s(parameters[0].id)}`;
  22281. }
  22282. }
  22283. return action;
  22284. }
  22285. let handleBeforeExit = null;
  22286. const rejectByPluginDriver = new Map();
  22287. async function catchUnfinishedHookActions(pluginDriver, callback) {
  22288. const emptyEventLoopPromise = new Promise((_, reject) => {
  22289. rejectByPluginDriver.set(pluginDriver, reject);
  22290. if (!handleBeforeExit) {
  22291. // We only ever create a single event listener to avoid max listener and
  22292. // other issues
  22293. handleBeforeExit = () => {
  22294. for (const [pluginDriver, reject] of rejectByPluginDriver) {
  22295. const unfulfilledActions = pluginDriver.getUnfulfilledHookActions();
  22296. reject(new Error(`Unexpected early exit. This happens when Promises returned by plugins cannot resolve. Unfinished hook action(s) on exit:\n` +
  22297. [...unfulfilledActions].map(formatAction).join('\n')));
  22298. }
  22299. };
  22300. process$1.once('beforeExit', handleBeforeExit);
  22301. }
  22302. });
  22303. try {
  22304. return await Promise.race([callback(), emptyEventLoopPromise]);
  22305. }
  22306. finally {
  22307. rejectByPluginDriver.delete(pluginDriver);
  22308. if (rejectByPluginDriver.size === 0) {
  22309. process$1.off('beforeExit', handleBeforeExit);
  22310. handleBeforeExit = null;
  22311. }
  22312. }
  22313. }
  22314. async function initWasm() { }
  22315. function getLogger(plugins, onLog, watchMode, logLevel) {
  22316. plugins = getSortedValidatedPlugins('onLog', plugins);
  22317. const minimalPriority = logLevelPriority[logLevel];
  22318. const logger = (level, log, skipped = EMPTY_SET) => {
  22319. augmentLogMessage(log);
  22320. const logPriority = logLevelPriority[level];
  22321. if (logPriority < minimalPriority) {
  22322. return;
  22323. }
  22324. for (const plugin of plugins) {
  22325. if (skipped.has(plugin))
  22326. continue;
  22327. const { onLog: pluginOnLog } = plugin;
  22328. const getLogHandler = (level) => {
  22329. if (logLevelPriority[level] < minimalPriority) {
  22330. return doNothing;
  22331. }
  22332. return log => logger(level, normalizeLog(log), new Set(skipped).add(plugin));
  22333. };
  22334. const handler = 'handler' in pluginOnLog ? pluginOnLog.handler : pluginOnLog;
  22335. if (handler.call({
  22336. debug: getLogHandler(LOGLEVEL_DEBUG),
  22337. error: (log) => error(normalizeLog(log)),
  22338. info: getLogHandler(LOGLEVEL_INFO),
  22339. meta: { rollupVersion: version, watchMode },
  22340. warn: getLogHandler(LOGLEVEL_WARN)
  22341. }, level, log) === false) {
  22342. return;
  22343. }
  22344. }
  22345. onLog(level, log);
  22346. };
  22347. return logger;
  22348. }
  22349. const fs = /*#__PURE__*/_mergeNamespaces({
  22350. __proto__: null
  22351. }, [promises]);
  22352. async function normalizeInputOptions(config, watchMode) {
  22353. // These are options that may trigger special warnings or behaviour later
  22354. // if the user did not select an explicit value
  22355. const unsetOptions = new Set();
  22356. const context = config.context ?? 'undefined';
  22357. const plugins = await normalizePluginOption(config.plugins);
  22358. const logLevel = config.logLevel || LOGLEVEL_INFO;
  22359. const onLog = getLogger(plugins, getOnLog(config, logLevel), watchMode, logLevel);
  22360. const strictDeprecations = config.strictDeprecations || false;
  22361. const maxParallelFileOps = getMaxParallelFileOps(config);
  22362. const options = {
  22363. cache: getCache(config),
  22364. context,
  22365. experimentalCacheExpiry: config.experimentalCacheExpiry ?? 10,
  22366. experimentalLogSideEffects: config.experimentalLogSideEffects || false,
  22367. external: getIdMatcher(config.external),
  22368. fs: config.fs ?? fs,
  22369. input: getInput(config),
  22370. jsx: getJsx(config),
  22371. logLevel,
  22372. makeAbsoluteExternalsRelative: config.makeAbsoluteExternalsRelative ?? 'ifRelativeSource',
  22373. maxParallelFileOps,
  22374. moduleContext: getModuleContext(config, context),
  22375. onLog,
  22376. perf: config.perf || false,
  22377. plugins,
  22378. preserveEntrySignatures: config.preserveEntrySignatures ?? 'exports-only',
  22379. preserveSymlinks: config.preserveSymlinks || false,
  22380. shimMissingExports: config.shimMissingExports || false,
  22381. strictDeprecations,
  22382. treeshake: getTreeshake(config)
  22383. };
  22384. warnUnknownOptions(config, [...Object.keys(options), 'onwarn', 'watch'], 'input options', onLog, /^(output)$/);
  22385. return { options, unsetOptions };
  22386. }
  22387. const getCache = (config) => config.cache === true // `true` is the default
  22388. ? undefined
  22389. : config.cache?.cache || config.cache;
  22390. const getIdMatcher = (option) => {
  22391. if (option === true) {
  22392. return () => true;
  22393. }
  22394. if (typeof option === 'function') {
  22395. return (id, ...parameters) => (id[0] !== '\0' && option(id, ...parameters)) || false;
  22396. }
  22397. if (option) {
  22398. const ids = new Set();
  22399. const matchers = [];
  22400. for (const value of ensureArray(option)) {
  22401. if (value instanceof RegExp) {
  22402. matchers.push(value);
  22403. }
  22404. else {
  22405. ids.add(value);
  22406. }
  22407. }
  22408. return (id, ..._arguments) => ids.has(id) || matchers.some(matcher => matcher.test(id));
  22409. }
  22410. return () => false;
  22411. };
  22412. const getInput = (config) => {
  22413. const configInput = config.input;
  22414. return configInput == null ? [] : typeof configInput === 'string' ? [configInput] : configInput;
  22415. };
  22416. const getJsx = (config) => {
  22417. const configJsx = config.jsx;
  22418. if (!configJsx)
  22419. return false;
  22420. const configWithPreset = getOptionWithPreset(configJsx, jsxPresets, 'jsx', URL_JSX, 'false, ');
  22421. const { factory, importSource, mode } = configWithPreset;
  22422. switch (mode) {
  22423. case 'automatic': {
  22424. return {
  22425. factory: factory || 'React.createElement',
  22426. importSource: importSource || 'react',
  22427. jsxImportSource: configWithPreset.jsxImportSource || 'react/jsx-runtime',
  22428. mode: 'automatic'
  22429. };
  22430. }
  22431. case 'preserve': {
  22432. if (importSource && !(factory || configWithPreset.fragment)) {
  22433. error(logInvalidOption('jsx', URL_JSX, 'when preserving JSX and specifying an importSource, you also need to specify a factory or fragment'));
  22434. }
  22435. return {
  22436. factory: factory || null,
  22437. fragment: configWithPreset.fragment || null,
  22438. importSource: importSource || null,
  22439. mode: 'preserve'
  22440. };
  22441. }
  22442. // case 'classic':
  22443. default: {
  22444. if (mode && mode !== 'classic') {
  22445. error(logInvalidOption('jsx.mode', URL_JSX, 'mode must be "automatic", "classic" or "preserve"', mode));
  22446. }
  22447. return {
  22448. factory: factory || 'React.createElement',
  22449. fragment: configWithPreset.fragment || 'React.Fragment',
  22450. importSource: importSource || null,
  22451. mode: 'classic'
  22452. };
  22453. }
  22454. }
  22455. };
  22456. const getMaxParallelFileOps = (config) => {
  22457. const maxParallelFileOps = config.maxParallelFileOps;
  22458. if (typeof maxParallelFileOps === 'number') {
  22459. if (maxParallelFileOps <= 0)
  22460. return Infinity;
  22461. return maxParallelFileOps;
  22462. }
  22463. return 1000;
  22464. };
  22465. const getModuleContext = (config, context) => {
  22466. const configModuleContext = config.moduleContext;
  22467. if (typeof configModuleContext === 'function') {
  22468. return id => configModuleContext(id) ?? context;
  22469. }
  22470. if (configModuleContext) {
  22471. const contextByModuleId = Object.create(null);
  22472. for (const [key, moduleContext] of Object.entries(configModuleContext)) {
  22473. contextByModuleId[resolve$1(key)] = moduleContext;
  22474. }
  22475. return id => contextByModuleId[id] ?? context;
  22476. }
  22477. return () => context;
  22478. };
  22479. const getTreeshake = (config) => {
  22480. const configTreeshake = config.treeshake;
  22481. if (configTreeshake === false) {
  22482. return false;
  22483. }
  22484. const configWithPreset = getOptionWithPreset(config.treeshake, treeshakePresets, 'treeshake', URL_TREESHAKE, 'false, true, ');
  22485. return {
  22486. annotations: configWithPreset.annotations !== false,
  22487. correctVarValueBeforeDeclaration: configWithPreset.correctVarValueBeforeDeclaration === true,
  22488. manualPureFunctions: configWithPreset.manualPureFunctions ?? EMPTY_ARRAY,
  22489. moduleSideEffects: getHasModuleSideEffects(configWithPreset.moduleSideEffects),
  22490. propertyReadSideEffects: configWithPreset.propertyReadSideEffects === 'always'
  22491. ? 'always'
  22492. : configWithPreset.propertyReadSideEffects !== false,
  22493. tryCatchDeoptimization: configWithPreset.tryCatchDeoptimization !== false,
  22494. unknownGlobalSideEffects: configWithPreset.unknownGlobalSideEffects !== false
  22495. };
  22496. };
  22497. const getHasModuleSideEffects = (moduleSideEffectsOption) => {
  22498. if (typeof moduleSideEffectsOption === 'boolean') {
  22499. return () => moduleSideEffectsOption;
  22500. }
  22501. if (moduleSideEffectsOption === 'no-external') {
  22502. return (_id, external) => !external;
  22503. }
  22504. if (typeof moduleSideEffectsOption === 'function') {
  22505. return (id, external) => id[0] === '\0' ? true : moduleSideEffectsOption(id, external) !== false;
  22506. }
  22507. if (Array.isArray(moduleSideEffectsOption)) {
  22508. const ids = new Set(moduleSideEffectsOption);
  22509. return id => ids.has(id);
  22510. }
  22511. if (moduleSideEffectsOption) {
  22512. error(logInvalidOption('treeshake.moduleSideEffects', URL_TREESHAKE_MODULESIDEEFFECTS, 'please use one of false, "no-external", a function or an array'));
  22513. }
  22514. return () => true;
  22515. };
  22516. // https://datatracker.ietf.org/doc/html/rfc2396
  22517. // eslint-disable-next-line no-control-regex
  22518. const INVALID_CHAR_REGEX = /[\u0000-\u001F"#$%&*+,:;<=>?[\]^`{|}\u007F]/g;
  22519. const DRIVE_LETTER_REGEX = /^[a-z]:/i;
  22520. function sanitizeFileName(name) {
  22521. const match = DRIVE_LETTER_REGEX.exec(name);
  22522. const driveLetter = match ? match[0] : '';
  22523. // A `:` is only allowed as part of a windows drive letter (ex: C:\foo)
  22524. // Otherwise, avoid them because they can refer to NTFS alternate data streams.
  22525. return driveLetter + name.slice(driveLetter.length).replace(INVALID_CHAR_REGEX, '_');
  22526. }
  22527. async function normalizeOutputOptions(config, inputOptions, unsetInputOptions) {
  22528. // These are options that may trigger special warnings or behaviour later
  22529. // if the user did not select an explicit value
  22530. const unsetOptions = new Set(unsetInputOptions);
  22531. const compact = config.compact || false;
  22532. const format = getFormat(config);
  22533. const inlineDynamicImports = getInlineDynamicImports(config, inputOptions);
  22534. const preserveModules = getPreserveModules(config, inlineDynamicImports, inputOptions);
  22535. const file = getFile(config, preserveModules, inputOptions);
  22536. const generatedCode = getGeneratedCode(config);
  22537. const externalImportAttributes = getExternalImportAttributes(config, inputOptions);
  22538. const outputOptions = {
  22539. amd: getAmd(config),
  22540. assetFileNames: config.assetFileNames ?? 'assets/[name]-[hash][extname]',
  22541. banner: getAddon(config, 'banner'),
  22542. chunkFileNames: config.chunkFileNames ?? '[name]-[hash].js',
  22543. compact,
  22544. dir: getDir(config, file),
  22545. dynamicImportInCjs: config.dynamicImportInCjs ?? true,
  22546. entryFileNames: getEntryFileNames(config, unsetOptions),
  22547. esModule: config.esModule ?? 'if-default-prop',
  22548. experimentalMinChunkSize: config.experimentalMinChunkSize ?? 1,
  22549. exports: getExports(config, unsetOptions),
  22550. extend: config.extend || false,
  22551. externalImportAssertions: externalImportAttributes,
  22552. externalImportAttributes,
  22553. externalLiveBindings: config.externalLiveBindings ?? true,
  22554. file,
  22555. footer: getAddon(config, 'footer'),
  22556. format,
  22557. freeze: config.freeze ?? true,
  22558. generatedCode,
  22559. globals: config.globals || {},
  22560. hashCharacters: config.hashCharacters ?? 'base64',
  22561. hoistTransitiveImports: config.hoistTransitiveImports ?? true,
  22562. importAttributesKey: config.importAttributesKey ?? 'assert',
  22563. indent: getIndent(config, compact),
  22564. inlineDynamicImports,
  22565. interop: getInterop(config),
  22566. intro: getAddon(config, 'intro'),
  22567. manualChunks: getManualChunks(config, inlineDynamicImports, preserveModules),
  22568. minifyInternalExports: getMinifyInternalExports(config, format, compact),
  22569. name: config.name,
  22570. noConflict: config.noConflict || false,
  22571. onlyExplicitManualChunks: config.onlyExplicitManualChunks || false,
  22572. outro: getAddon(config, 'outro'),
  22573. paths: config.paths || {},
  22574. plugins: await normalizePluginOption(config.plugins),
  22575. preserveModules,
  22576. preserveModulesRoot: getPreserveModulesRoot(config),
  22577. reexportProtoFromExternal: config.reexportProtoFromExternal ?? true,
  22578. sanitizeFileName: typeof config.sanitizeFileName === 'function'
  22579. ? config.sanitizeFileName
  22580. : config.sanitizeFileName === false
  22581. ? id => id
  22582. : sanitizeFileName,
  22583. sourcemap: config.sourcemap || false,
  22584. sourcemapBaseUrl: getSourcemapBaseUrl(config),
  22585. sourcemapDebugIds: config.sourcemapDebugIds || false,
  22586. sourcemapExcludeSources: config.sourcemapExcludeSources || false,
  22587. sourcemapFile: config.sourcemapFile,
  22588. sourcemapFileNames: getSourcemapFileNames(config, unsetOptions),
  22589. sourcemapIgnoreList: typeof config.sourcemapIgnoreList === 'function'
  22590. ? config.sourcemapIgnoreList
  22591. : config.sourcemapIgnoreList === false
  22592. ? () => false
  22593. : relativeSourcePath => relativeSourcePath.includes('node_modules'),
  22594. sourcemapPathTransform: config.sourcemapPathTransform,
  22595. strict: config.strict ?? true,
  22596. systemNullSetters: config.systemNullSetters ?? true,
  22597. validate: config.validate || false,
  22598. virtualDirname: config.virtualDirname || '_virtual'
  22599. };
  22600. warnUnknownOptions(config, Object.keys(outputOptions), 'output options', inputOptions.onLog);
  22601. return { options: outputOptions, unsetOptions };
  22602. }
  22603. const getFile = (config, preserveModules, inputOptions) => {
  22604. const { file } = config;
  22605. if (typeof file === 'string') {
  22606. if (preserveModules) {
  22607. return error(logInvalidOption('output.file', URL_OUTPUT_DIR, 'you must set "output.dir" instead of "output.file" when using the "output.preserveModules" option'));
  22608. }
  22609. if (!Array.isArray(inputOptions.input))
  22610. return error(logInvalidOption('output.file', URL_OUTPUT_DIR, 'you must set "output.dir" instead of "output.file" when providing named inputs'));
  22611. }
  22612. return file;
  22613. };
  22614. const getFormat = (config) => {
  22615. const configFormat = config.format;
  22616. switch (configFormat) {
  22617. case undefined:
  22618. case 'es':
  22619. case 'esm':
  22620. case 'module': {
  22621. return 'es';
  22622. }
  22623. case 'cjs':
  22624. case 'commonjs': {
  22625. return 'cjs';
  22626. }
  22627. case 'system':
  22628. case 'systemjs': {
  22629. return 'system';
  22630. }
  22631. case 'amd':
  22632. case 'iife':
  22633. case 'umd': {
  22634. return configFormat;
  22635. }
  22636. default: {
  22637. return error(logInvalidOption('output.format', URL_OUTPUT_FORMAT, `Valid values are "amd", "cjs", "system", "es", "iife" or "umd"`, configFormat));
  22638. }
  22639. }
  22640. };
  22641. const getInlineDynamicImports = (config, inputOptions) => {
  22642. const inlineDynamicImports = config.inlineDynamicImports || false;
  22643. const { input } = inputOptions;
  22644. if (inlineDynamicImports && (Array.isArray(input) ? input : Object.keys(input)).length > 1) {
  22645. return error(logInvalidOption('output.inlineDynamicImports', URL_OUTPUT_INLINEDYNAMICIMPORTS, 'multiple inputs are not supported when "output.inlineDynamicImports" is true'));
  22646. }
  22647. return inlineDynamicImports;
  22648. };
  22649. const getPreserveModules = (config, inlineDynamicImports, inputOptions) => {
  22650. const preserveModules = config.preserveModules || false;
  22651. if (preserveModules) {
  22652. if (inlineDynamicImports) {
  22653. return error(logInvalidOption('output.inlineDynamicImports', URL_OUTPUT_INLINEDYNAMICIMPORTS, `this option is not supported for "output.preserveModules"`));
  22654. }
  22655. if (inputOptions.preserveEntrySignatures === false) {
  22656. return error(logInvalidOption('preserveEntrySignatures', URL_PRESERVEENTRYSIGNATURES, 'setting this option to false is not supported for "output.preserveModules"'));
  22657. }
  22658. }
  22659. return preserveModules;
  22660. };
  22661. const getPreserveModulesRoot = (config) => {
  22662. const { preserveModulesRoot } = config;
  22663. if (preserveModulesRoot === null || preserveModulesRoot === undefined) {
  22664. return undefined;
  22665. }
  22666. return resolve$1(preserveModulesRoot);
  22667. };
  22668. const getAmd = (config) => {
  22669. const mergedOption = {
  22670. autoId: false,
  22671. basePath: '',
  22672. define: 'define',
  22673. forceJsExtensionForImports: false,
  22674. ...config.amd
  22675. };
  22676. if ((mergedOption.autoId || mergedOption.basePath) && mergedOption.id) {
  22677. return error(logInvalidOption('output.amd.id', URL_OUTPUT_AMD_ID, 'this option cannot be used together with "output.amd.autoId"/"output.amd.basePath"'));
  22678. }
  22679. if (mergedOption.basePath && !mergedOption.autoId) {
  22680. return error(logInvalidOption('output.amd.basePath', URL_OUTPUT_AMD_BASEPATH, 'this option only works with "output.amd.autoId"'));
  22681. }
  22682. return mergedOption.autoId
  22683. ? {
  22684. autoId: true,
  22685. basePath: mergedOption.basePath,
  22686. define: mergedOption.define,
  22687. forceJsExtensionForImports: mergedOption.forceJsExtensionForImports
  22688. }
  22689. : {
  22690. autoId: false,
  22691. define: mergedOption.define,
  22692. forceJsExtensionForImports: mergedOption.forceJsExtensionForImports,
  22693. id: mergedOption.id
  22694. };
  22695. };
  22696. const getAddon = (config, name) => {
  22697. const configAddon = config[name];
  22698. if (typeof configAddon === 'function') {
  22699. return configAddon;
  22700. }
  22701. return () => configAddon || '';
  22702. };
  22703. const getDir = (config, file) => {
  22704. const { dir } = config;
  22705. if (typeof dir === 'string' && typeof file === 'string') {
  22706. 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'));
  22707. }
  22708. return dir;
  22709. };
  22710. const getEntryFileNames = (config, unsetOptions) => {
  22711. const configEntryFileNames = config.entryFileNames;
  22712. if (configEntryFileNames == null) {
  22713. unsetOptions.add('entryFileNames');
  22714. }
  22715. return configEntryFileNames ?? '[name].js';
  22716. };
  22717. function getExports(config, unsetOptions) {
  22718. const configExports = config.exports;
  22719. if (configExports == null) {
  22720. unsetOptions.add('exports');
  22721. }
  22722. else if (!['default', 'named', 'none', 'auto'].includes(configExports)) {
  22723. return error(logInvalidExportOptionValue(configExports));
  22724. }
  22725. return configExports || 'auto';
  22726. }
  22727. const getExternalImportAttributes = (config, inputOptions) => {
  22728. if (config.externalImportAssertions != undefined) {
  22729. warnDeprecation(`The "output.externalImportAssertions" option is deprecated. Use the "output.externalImportAttributes" option instead.`, URL_OUTPUT_EXTERNALIMPORTATTRIBUTES, true, inputOptions);
  22730. }
  22731. return config.externalImportAttributes ?? config.externalImportAssertions ?? true;
  22732. };
  22733. const getGeneratedCode = (config) => {
  22734. const configWithPreset = getOptionWithPreset(config.generatedCode, generatedCodePresets, 'output.generatedCode', URL_OUTPUT_GENERATEDCODE, '');
  22735. return {
  22736. arrowFunctions: configWithPreset.arrowFunctions === true,
  22737. constBindings: configWithPreset.constBindings === true,
  22738. objectShorthand: configWithPreset.objectShorthand === true,
  22739. reservedNamesAsProps: configWithPreset.reservedNamesAsProps !== false,
  22740. symbols: configWithPreset.symbols === true
  22741. };
  22742. };
  22743. const getIndent = (config, compact) => {
  22744. if (compact) {
  22745. return '';
  22746. }
  22747. const configIndent = config.indent;
  22748. return configIndent === false ? '' : (configIndent ?? true);
  22749. };
  22750. const ALLOWED_INTEROP_TYPES = new Set([
  22751. 'compat',
  22752. 'auto',
  22753. 'esModule',
  22754. 'default',
  22755. 'defaultOnly'
  22756. ]);
  22757. const getInterop = (config) => {
  22758. const configInterop = config.interop;
  22759. if (typeof configInterop === 'function') {
  22760. const interopPerId = Object.create(null);
  22761. let defaultInterop = null;
  22762. return id => id === null
  22763. ? defaultInterop || validateInterop((defaultInterop = configInterop(id)))
  22764. : id in interopPerId
  22765. ? interopPerId[id]
  22766. : validateInterop((interopPerId[id] = configInterop(id)));
  22767. }
  22768. return configInterop === undefined ? () => 'default' : () => validateInterop(configInterop);
  22769. };
  22770. const validateInterop = (interop) => {
  22771. if (!ALLOWED_INTEROP_TYPES.has(interop)) {
  22772. return error(logInvalidOption('output.interop', URL_OUTPUT_INTEROP, `use one of ${Array.from(ALLOWED_INTEROP_TYPES, value => JSON.stringify(value)).join(', ')}`, interop));
  22773. }
  22774. return interop;
  22775. };
  22776. const getManualChunks = (config, inlineDynamicImports, preserveModules) => {
  22777. const configManualChunks = config.manualChunks;
  22778. if (configManualChunks) {
  22779. if (inlineDynamicImports) {
  22780. return error(logInvalidOption('output.manualChunks', URL_OUTPUT_MANUALCHUNKS, 'this option is not supported for "output.inlineDynamicImports"'));
  22781. }
  22782. if (preserveModules) {
  22783. return error(logInvalidOption('output.manualChunks', URL_OUTPUT_MANUALCHUNKS, 'this option is not supported for "output.preserveModules"'));
  22784. }
  22785. }
  22786. return configManualChunks || {};
  22787. };
  22788. const getMinifyInternalExports = (config, format, compact) => config.minifyInternalExports ?? (compact || format === 'es' || format === 'system');
  22789. const getSourcemapFileNames = (config, unsetOptions) => {
  22790. const configSourcemapFileNames = config.sourcemapFileNames;
  22791. if (configSourcemapFileNames == null) {
  22792. unsetOptions.add('sourcemapFileNames');
  22793. }
  22794. return configSourcemapFileNames;
  22795. };
  22796. const getSourcemapBaseUrl = (config) => {
  22797. const { sourcemapBaseUrl } = config;
  22798. if (sourcemapBaseUrl) {
  22799. if (isValidUrl(sourcemapBaseUrl)) {
  22800. return addTrailingSlashIfMissed(sourcemapBaseUrl);
  22801. }
  22802. return error(logInvalidOption('output.sourcemapBaseUrl', URL_OUTPUT_SOURCEMAPBASEURL, `must be a valid URL, received ${JSON.stringify(sourcemapBaseUrl)}`));
  22803. }
  22804. };
  22805. // @ts-expect-error TS2540: the polyfill of `asyncDispose`.
  22806. Symbol.asyncDispose ??= Symbol('Symbol.asyncDispose');
  22807. function rollup(rawInputOptions) {
  22808. return rollupInternal(rawInputOptions, null);
  22809. }
  22810. async function rollupInternal(rawInputOptions, watcher) {
  22811. const { options: inputOptions, unsetOptions: unsetInputOptions } = await getInputOptions(rawInputOptions, watcher !== null);
  22812. initialiseTimers(inputOptions);
  22813. await initWasm();
  22814. const graph = new Graph(inputOptions, watcher);
  22815. // remove the cache object from the memory after graph creation (cache is not used anymore)
  22816. const useCache = rawInputOptions.cache !== false;
  22817. if (rawInputOptions.cache) {
  22818. inputOptions.cache = undefined;
  22819. rawInputOptions.cache = undefined;
  22820. }
  22821. timeStart('BUILD', 1);
  22822. await catchUnfinishedHookActions(graph.pluginDriver, async () => {
  22823. try {
  22824. timeStart('initialize', 2);
  22825. await graph.pluginDriver.hookParallel('buildStart', [inputOptions]);
  22826. timeEnd('initialize', 2);
  22827. await graph.build();
  22828. }
  22829. catch (error_) {
  22830. const watchFiles = Object.keys(graph.watchFiles);
  22831. if (watchFiles.length > 0) {
  22832. error_.watchFiles = watchFiles;
  22833. }
  22834. try {
  22835. await graph.pluginDriver.hookParallel('buildEnd', [error_]);
  22836. }
  22837. catch (buildEndError) {
  22838. // Create a compound error object to include both errors, based on the original error
  22839. const compoundError = getRollupError({
  22840. ...error_,
  22841. message: `There was an error during the build:\n ${error_.message}\nAdditionally, handling the error in the 'buildEnd' hook caused the following error:\n ${buildEndError.message}`
  22842. });
  22843. await graph.pluginDriver.hookParallel('closeBundle', [compoundError]);
  22844. throw compoundError;
  22845. }
  22846. await graph.pluginDriver.hookParallel('closeBundle', [error_]);
  22847. throw error_;
  22848. }
  22849. try {
  22850. await graph.pluginDriver.hookParallel('buildEnd', []);
  22851. }
  22852. catch (buildEndError) {
  22853. await graph.pluginDriver.hookParallel('closeBundle', [buildEndError]);
  22854. throw buildEndError;
  22855. }
  22856. });
  22857. timeEnd('BUILD', 1);
  22858. const result = {
  22859. get cache() {
  22860. return useCache ? graph.getCache() : undefined;
  22861. },
  22862. async close() {
  22863. if (result.closed)
  22864. return;
  22865. result.closed = true;
  22866. await graph.pluginDriver.hookParallel('closeBundle', []);
  22867. },
  22868. closed: false,
  22869. async [Symbol.asyncDispose]() {
  22870. await this.close();
  22871. },
  22872. async generate(rawOutputOptions) {
  22873. if (result.closed)
  22874. return error(logAlreadyClosed());
  22875. return handleGenerateWrite(false, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  22876. },
  22877. get watchFiles() {
  22878. return Object.keys(graph.watchFiles);
  22879. },
  22880. async write(rawOutputOptions) {
  22881. if (result.closed)
  22882. return error(logAlreadyClosed());
  22883. return handleGenerateWrite(true, inputOptions, unsetInputOptions, rawOutputOptions, graph);
  22884. }
  22885. };
  22886. if (inputOptions.perf)
  22887. result.getTimings = getTimings;
  22888. return result;
  22889. }
  22890. async function getInputOptions(initialInputOptions, watchMode) {
  22891. if (!initialInputOptions) {
  22892. throw new Error('You must supply an options object to rollup');
  22893. }
  22894. const processedInputOptions = await getProcessedInputOptions(initialInputOptions, watchMode);
  22895. const { options, unsetOptions } = await normalizeInputOptions(processedInputOptions, watchMode);
  22896. normalizePlugins(options.plugins, ANONYMOUS_PLUGIN_PREFIX);
  22897. return { options, unsetOptions };
  22898. }
  22899. async function getProcessedInputOptions(inputOptions, watchMode) {
  22900. const plugins = getSortedValidatedPlugins('options', await normalizePluginOption(inputOptions.plugins));
  22901. const logLevel = inputOptions.logLevel || LOGLEVEL_INFO;
  22902. const logger = getLogger(plugins, getOnLog(inputOptions, logLevel), watchMode, logLevel);
  22903. for (const plugin of plugins) {
  22904. const { name, options } = plugin;
  22905. const handler = 'handler' in options ? options.handler : options;
  22906. const processedOptions = await handler.call({
  22907. debug: getLogHandler(LOGLEVEL_DEBUG, 'PLUGIN_LOG', logger, name, logLevel),
  22908. error: (error_) => error(logPluginError(normalizeLog(error_), name, { hook: 'onLog' })),
  22909. info: getLogHandler(LOGLEVEL_INFO, 'PLUGIN_LOG', logger, name, logLevel),
  22910. meta: { rollupVersion: version, watchMode },
  22911. warn: getLogHandler(LOGLEVEL_WARN, 'PLUGIN_WARNING', logger, name, logLevel)
  22912. }, inputOptions);
  22913. if (processedOptions) {
  22914. inputOptions = processedOptions;
  22915. }
  22916. }
  22917. return inputOptions;
  22918. }
  22919. function normalizePlugins(plugins, anonymousPrefix) {
  22920. for (const [index, plugin] of plugins.entries()) {
  22921. if (!plugin.name) {
  22922. plugin.name = `${anonymousPrefix}${index + 1}`;
  22923. }
  22924. }
  22925. }
  22926. async function handleGenerateWrite(isWrite, inputOptions, unsetInputOptions, rawOutputOptions, graph) {
  22927. const { options: outputOptions, outputPluginDriver, unsetOptions } = await getOutputOptionsAndPluginDriver(rawOutputOptions, graph.pluginDriver, inputOptions, unsetInputOptions);
  22928. return catchUnfinishedHookActions(outputPluginDriver, async () => {
  22929. const bundle = new Bundle(outputOptions, unsetOptions, inputOptions, outputPluginDriver, graph);
  22930. const generated = await bundle.generate(isWrite);
  22931. if (isWrite) {
  22932. timeStart('WRITE', 1);
  22933. if (!outputOptions.dir && !outputOptions.file) {
  22934. return error(logMissingFileOrDirOption());
  22935. }
  22936. await Promise.all(Object.values(generated).map(chunk => graph.fileOperationQueue.run(() => writeOutputFile(chunk, outputOptions, inputOptions))));
  22937. await outputPluginDriver.hookParallel('writeBundle', [outputOptions, generated]);
  22938. timeEnd('WRITE', 1);
  22939. }
  22940. return createOutput(generated);
  22941. });
  22942. }
  22943. async function getOutputOptionsAndPluginDriver(rawOutputOptions, inputPluginDriver, inputOptions, unsetInputOptions) {
  22944. if (!rawOutputOptions) {
  22945. throw new Error('You must supply an options object');
  22946. }
  22947. const rawPlugins = await normalizePluginOption(rawOutputOptions.plugins);
  22948. normalizePlugins(rawPlugins, ANONYMOUS_OUTPUT_PLUGIN_PREFIX);
  22949. const outputPluginDriver = inputPluginDriver.createOutputPluginDriver(rawPlugins);
  22950. return {
  22951. ...(await getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver)),
  22952. outputPluginDriver
  22953. };
  22954. }
  22955. function getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver) {
  22956. return normalizeOutputOptions(outputPluginDriver.hookReduceArg0Sync('outputOptions', [rawOutputOptions], (outputOptions, result) => result || outputOptions, pluginContext => {
  22957. const emitError = () => pluginContext.error(logCannotEmitFromOptionsHook());
  22958. return {
  22959. ...pluginContext,
  22960. emitFile: emitError,
  22961. setAssetSource: emitError
  22962. };
  22963. }), inputOptions, unsetInputOptions);
  22964. }
  22965. function createOutput(outputBundle) {
  22966. return {
  22967. output: Object.values(outputBundle).filter(outputFile => Object.keys(outputFile).length > 0).sort((outputFileA, outputFileB) => getSortingFileType(outputFileA) - getSortingFileType(outputFileB))
  22968. };
  22969. }
  22970. var SortingFileType;
  22971. (function (SortingFileType) {
  22972. SortingFileType[SortingFileType["ENTRY_CHUNK"] = 0] = "ENTRY_CHUNK";
  22973. SortingFileType[SortingFileType["SECONDARY_CHUNK"] = 1] = "SECONDARY_CHUNK";
  22974. SortingFileType[SortingFileType["ASSET"] = 2] = "ASSET";
  22975. })(SortingFileType || (SortingFileType = {}));
  22976. function getSortingFileType(file) {
  22977. if (file.type === 'asset') {
  22978. return SortingFileType.ASSET;
  22979. }
  22980. if (file.isEntry) {
  22981. return SortingFileType.ENTRY_CHUNK;
  22982. }
  22983. return SortingFileType.SECONDARY_CHUNK;
  22984. }
  22985. async function writeOutputFile(outputFile, outputOptions, { fs: { mkdir, writeFile } }) {
  22986. const fileName = resolve$1(outputOptions.dir || dirname(outputOptions.file), outputFile.fileName);
  22987. // 'recursive: true' does not throw if the folder structure, or parts of it, already exist
  22988. await mkdir(dirname(fileName), { recursive: true });
  22989. return writeFile(fileName, outputFile.type === 'asset' ? outputFile.source : outputFile.code);
  22990. }
  22991. /**
  22992. * Auxiliary function for defining rollup configuration
  22993. * Mainly to facilitate IDE code prompts, after all, export default does not
  22994. * prompt, even if you add @type annotations, it is not accurate
  22995. * @param options
  22996. */
  22997. function defineConfig(options) {
  22998. return options;
  22999. }
  23000. var picocolors = {exports: {}};
  23001. var hasRequiredPicocolors;
  23002. function requirePicocolors () {
  23003. if (hasRequiredPicocolors) return picocolors.exports;
  23004. hasRequiredPicocolors = 1;
  23005. let p = process || {}, argv = p.argv || [], env = p.env || {};
  23006. let isColorSupported =
  23007. !(!!env.NO_COLOR || argv.includes("--no-color")) &&
  23008. (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || ((p.stdout || {}).isTTY && env.TERM !== "dumb") || !!env.CI);
  23009. let formatter = (open, close, replace = open) =>
  23010. input => {
  23011. let string = "" + input, index = string.indexOf(close, open.length);
  23012. return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close
  23013. };
  23014. let replaceClose = (string, close, replace, index) => {
  23015. let result = "", cursor = 0;
  23016. do {
  23017. result += string.substring(cursor, index) + replace;
  23018. cursor = index + close.length;
  23019. index = string.indexOf(close, cursor);
  23020. } while (~index)
  23021. return result + string.substring(cursor)
  23022. };
  23023. let createColors = (enabled = isColorSupported) => {
  23024. let f = enabled ? formatter : () => String;
  23025. return {
  23026. isColorSupported: enabled,
  23027. reset: f("\x1b[0m", "\x1b[0m"),
  23028. bold: f("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m"),
  23029. dim: f("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m"),
  23030. italic: f("\x1b[3m", "\x1b[23m"),
  23031. underline: f("\x1b[4m", "\x1b[24m"),
  23032. inverse: f("\x1b[7m", "\x1b[27m"),
  23033. hidden: f("\x1b[8m", "\x1b[28m"),
  23034. strikethrough: f("\x1b[9m", "\x1b[29m"),
  23035. black: f("\x1b[30m", "\x1b[39m"),
  23036. red: f("\x1b[31m", "\x1b[39m"),
  23037. green: f("\x1b[32m", "\x1b[39m"),
  23038. yellow: f("\x1b[33m", "\x1b[39m"),
  23039. blue: f("\x1b[34m", "\x1b[39m"),
  23040. magenta: f("\x1b[35m", "\x1b[39m"),
  23041. cyan: f("\x1b[36m", "\x1b[39m"),
  23042. white: f("\x1b[37m", "\x1b[39m"),
  23043. gray: f("\x1b[90m", "\x1b[39m"),
  23044. bgBlack: f("\x1b[40m", "\x1b[49m"),
  23045. bgRed: f("\x1b[41m", "\x1b[49m"),
  23046. bgGreen: f("\x1b[42m", "\x1b[49m"),
  23047. bgYellow: f("\x1b[43m", "\x1b[49m"),
  23048. bgBlue: f("\x1b[44m", "\x1b[49m"),
  23049. bgMagenta: f("\x1b[45m", "\x1b[49m"),
  23050. bgCyan: f("\x1b[46m", "\x1b[49m"),
  23051. bgWhite: f("\x1b[47m", "\x1b[49m"),
  23052. blackBright: f("\x1b[90m", "\x1b[39m"),
  23053. redBright: f("\x1b[91m", "\x1b[39m"),
  23054. greenBright: f("\x1b[92m", "\x1b[39m"),
  23055. yellowBright: f("\x1b[93m", "\x1b[39m"),
  23056. blueBright: f("\x1b[94m", "\x1b[39m"),
  23057. magentaBright: f("\x1b[95m", "\x1b[39m"),
  23058. cyanBright: f("\x1b[96m", "\x1b[39m"),
  23059. whiteBright: f("\x1b[97m", "\x1b[39m"),
  23060. bgBlackBright: f("\x1b[100m", "\x1b[49m"),
  23061. bgRedBright: f("\x1b[101m", "\x1b[49m"),
  23062. bgGreenBright: f("\x1b[102m", "\x1b[49m"),
  23063. bgYellowBright: f("\x1b[103m", "\x1b[49m"),
  23064. bgBlueBright: f("\x1b[104m", "\x1b[49m"),
  23065. bgMagentaBright: f("\x1b[105m", "\x1b[49m"),
  23066. bgCyanBright: f("\x1b[106m", "\x1b[49m"),
  23067. bgWhiteBright: f("\x1b[107m", "\x1b[49m"),
  23068. }
  23069. };
  23070. picocolors.exports = createColors();
  23071. picocolors.exports.createColors = createColors;
  23072. return picocolors.exports;
  23073. }
  23074. var picocolorsExports = /*@__PURE__*/ requirePicocolors();
  23075. const pc = /*@__PURE__*/getDefaultExportFromCjs(picocolorsExports);
  23076. // @see https://no-color.org
  23077. // @see https://www.npmjs.com/package/chalk
  23078. const { bold, cyan, dim, red} = pc.createColors(env.FORCE_COLOR !== '0' && !env.NO_COLOR);
  23079. // log to stderr to keep `rollup main.js > bundle.js` from breaking
  23080. const stderr = (...parameters) => process$1.stderr.write(`${parameters.join('')}\n`);
  23081. function handleError(error, recover = false) {
  23082. const name = error.name || error.cause?.name;
  23083. const nameSection = name ? `${name}: ` : '';
  23084. const pluginSection = error.plugin ? `(plugin ${error.plugin}) ` : '';
  23085. const message = `${pluginSection}${nameSection}${error.message}`;
  23086. const outputLines = [bold(red(`[!] ${bold(message.toString())}`))];
  23087. if (error.url) {
  23088. outputLines.push(cyan(error.url));
  23089. }
  23090. if (error.loc) {
  23091. outputLines.push(`${relativeId((error.loc.file || error.id))} (${error.loc.line}:${error.loc.column})`);
  23092. }
  23093. else if (error.id) {
  23094. outputLines.push(relativeId(error.id));
  23095. }
  23096. if (error.frame) {
  23097. outputLines.push(dim(error.frame));
  23098. }
  23099. if (error.stack) {
  23100. outputLines.push(dim(error.stack?.replace(`${nameSection}${error.message}\n`, '')));
  23101. }
  23102. // ES2022: Error.prototype.cause is optional
  23103. if (error.cause) {
  23104. let cause = error.cause;
  23105. const causeErrorLines = [];
  23106. let indent = '';
  23107. while (cause) {
  23108. indent += ' ';
  23109. const message = cause.stack || cause;
  23110. causeErrorLines.push(...`[cause] ${message}`.split('\n').map(line => indent + line));
  23111. cause = cause.cause;
  23112. }
  23113. outputLines.push(dim(causeErrorLines.join('\n')));
  23114. }
  23115. outputLines.push('', '');
  23116. stderr(outputLines.join('\n'));
  23117. if (!recover)
  23118. process$1.exit(1);
  23119. }
  23120. const commandAliases = {
  23121. c: 'config',
  23122. d: 'dir',
  23123. e: 'external',
  23124. f: 'format',
  23125. g: 'globals',
  23126. h: 'help',
  23127. i: 'input',
  23128. m: 'sourcemap',
  23129. n: 'name',
  23130. o: 'file',
  23131. p: 'plugin',
  23132. v: 'version',
  23133. w: 'watch'
  23134. };
  23135. const EMPTY_COMMAND_OPTIONS = { external: [], globals: undefined };
  23136. async function mergeOptions(config, watchMode, rawCommandOptions = EMPTY_COMMAND_OPTIONS, printLog) {
  23137. const command = getCommandOptions(rawCommandOptions);
  23138. const plugins = await normalizePluginOption(config.plugins);
  23139. const logLevel = config.logLevel || LOGLEVEL_INFO;
  23140. const onLog = getOnLog(config, logLevel, printLog);
  23141. const log = getLogger(plugins, onLog, watchMode, logLevel);
  23142. const inputOptions = mergeInputOptions(config, command, plugins, log, onLog);
  23143. if (command.output) {
  23144. Object.assign(command, command.output);
  23145. }
  23146. const outputOptionsArray = ensureArray(config.output);
  23147. if (outputOptionsArray.length === 0)
  23148. outputOptionsArray.push({});
  23149. const outputOptions = await Promise.all(outputOptionsArray.map(singleOutputOptions => mergeOutputOptions(singleOutputOptions, command, log)));
  23150. warnUnknownOptions(command, [
  23151. ...Object.keys(inputOptions).filter(option => option !== 'fs'),
  23152. ...Object.keys(outputOptions[0]).filter(option => option !== 'sourcemapIgnoreList' && option !== 'sourcemapPathTransform'),
  23153. ...Object.keys(commandAliases),
  23154. 'bundleConfigAsCjs',
  23155. 'config',
  23156. 'configImportAttributesKey',
  23157. 'configPlugin',
  23158. 'environment',
  23159. 'failAfterWarnings',
  23160. 'filterLogs',
  23161. 'forceExit',
  23162. 'plugin',
  23163. 'silent',
  23164. 'stdin',
  23165. 'waitForBundleInput'
  23166. ], 'CLI flags', log, /^_$|output$|config/);
  23167. inputOptions.output = outputOptions;
  23168. return inputOptions;
  23169. }
  23170. function getCommandOptions(rawCommandOptions) {
  23171. const external = rawCommandOptions.external && typeof rawCommandOptions.external === 'string'
  23172. ? rawCommandOptions.external.split(',')
  23173. : [];
  23174. return {
  23175. ...rawCommandOptions,
  23176. external,
  23177. globals: typeof rawCommandOptions.globals === 'string'
  23178. ? rawCommandOptions.globals.split(',').reduce((globals, globalDefinition) => {
  23179. const [id, variableName] = globalDefinition.split(':');
  23180. globals[id] = variableName;
  23181. if (!external.includes(id)) {
  23182. external.push(id);
  23183. }
  23184. return globals;
  23185. }, Object.create(null))
  23186. : undefined
  23187. };
  23188. }
  23189. function mergeInputOptions(config, overrides, plugins, log, onLog) {
  23190. const getOption = (name) => overrides[name] ?? config[name];
  23191. const inputOptions = {
  23192. cache: config.cache,
  23193. context: getOption('context'),
  23194. experimentalCacheExpiry: getOption('experimentalCacheExpiry'),
  23195. experimentalLogSideEffects: getOption('experimentalLogSideEffects'),
  23196. external: getExternal(config, overrides),
  23197. fs: getOption('fs'),
  23198. input: getOption('input') || [],
  23199. jsx: getObjectOption(config, overrides, 'jsx', objectifyOptionWithPresets(jsxPresets, 'jsx', URL_JSX, 'false, ')),
  23200. logLevel: getOption('logLevel'),
  23201. makeAbsoluteExternalsRelative: getOption('makeAbsoluteExternalsRelative'),
  23202. maxParallelFileOps: getOption('maxParallelFileOps'),
  23203. moduleContext: getOption('moduleContext'),
  23204. onLog,
  23205. onwarn: undefined,
  23206. perf: getOption('perf'),
  23207. plugins,
  23208. preserveEntrySignatures: getOption('preserveEntrySignatures'),
  23209. preserveSymlinks: getOption('preserveSymlinks'),
  23210. shimMissingExports: getOption('shimMissingExports'),
  23211. strictDeprecations: getOption('strictDeprecations'),
  23212. treeshake: getObjectOption(config, overrides, 'treeshake', objectifyOptionWithPresets(treeshakePresets, 'treeshake', URL_TREESHAKE, 'false, true, ')),
  23213. watch: getWatch(config, overrides)
  23214. };
  23215. warnUnknownOptions(config, Object.keys(inputOptions), 'input options', log, /^output$/);
  23216. return inputOptions;
  23217. }
  23218. const getExternal = (config, overrides) => {
  23219. const configExternal = config.external;
  23220. return typeof configExternal === 'function'
  23221. ? (source, importer, isResolved) => configExternal(source, importer, isResolved) || overrides.external.includes(source)
  23222. : [...ensureArray(configExternal), ...overrides.external];
  23223. };
  23224. const getObjectOption = (config, overrides, name, objectifyValue = objectifyOption) => {
  23225. const commandOption = normalizeObjectOptionValue(overrides[name], objectifyValue);
  23226. const configOption = normalizeObjectOptionValue(config[name], objectifyValue);
  23227. if (commandOption !== undefined) {
  23228. return commandOption && { ...configOption, ...commandOption };
  23229. }
  23230. return configOption;
  23231. };
  23232. const getWatch = (config, overrides) => config.watch !== false && getObjectOption(config, overrides, 'watch');
  23233. const normalizeObjectOptionValue = (optionValue, objectifyValue) => {
  23234. if (!optionValue) {
  23235. return optionValue;
  23236. }
  23237. if (Array.isArray(optionValue)) {
  23238. return optionValue.reduce((result, value) => value && result && { ...result, ...objectifyValue(value) }, {});
  23239. }
  23240. return objectifyValue(optionValue);
  23241. };
  23242. async function mergeOutputOptions(config, overrides, log) {
  23243. const getOption = (name) => overrides[name] ?? config[name];
  23244. const outputOptions = {
  23245. amd: getObjectOption(config, overrides, 'amd'),
  23246. assetFileNames: getOption('assetFileNames'),
  23247. banner: getOption('banner'),
  23248. chunkFileNames: getOption('chunkFileNames'),
  23249. compact: getOption('compact'),
  23250. dir: getOption('dir'),
  23251. dynamicImportInCjs: getOption('dynamicImportInCjs'),
  23252. entryFileNames: getOption('entryFileNames'),
  23253. esModule: getOption('esModule'),
  23254. experimentalMinChunkSize: getOption('experimentalMinChunkSize'),
  23255. exports: getOption('exports'),
  23256. extend: getOption('extend'),
  23257. externalImportAssertions: getOption('externalImportAssertions'),
  23258. externalImportAttributes: getOption('externalImportAttributes'),
  23259. externalLiveBindings: getOption('externalLiveBindings'),
  23260. file: getOption('file'),
  23261. footer: getOption('footer'),
  23262. format: getOption('format'),
  23263. freeze: getOption('freeze'),
  23264. generatedCode: getObjectOption(config, overrides, 'generatedCode', objectifyOptionWithPresets(generatedCodePresets, 'output.generatedCode', URL_OUTPUT_GENERATEDCODE, '')),
  23265. globals: getOption('globals'),
  23266. hashCharacters: getOption('hashCharacters'),
  23267. hoistTransitiveImports: getOption('hoistTransitiveImports'),
  23268. importAttributesKey: getOption('importAttributesKey'),
  23269. indent: getOption('indent'),
  23270. inlineDynamicImports: getOption('inlineDynamicImports'),
  23271. interop: getOption('interop'),
  23272. intro: getOption('intro'),
  23273. manualChunks: getOption('manualChunks'),
  23274. minifyInternalExports: getOption('minifyInternalExports'),
  23275. name: getOption('name'),
  23276. noConflict: getOption('noConflict'),
  23277. onlyExplicitManualChunks: getOption('onlyExplicitManualChunks'),
  23278. outro: getOption('outro'),
  23279. paths: getOption('paths'),
  23280. plugins: await normalizePluginOption(config.plugins),
  23281. preserveModules: getOption('preserveModules'),
  23282. preserveModulesRoot: getOption('preserveModulesRoot'),
  23283. reexportProtoFromExternal: getOption('reexportProtoFromExternal'),
  23284. sanitizeFileName: getOption('sanitizeFileName'),
  23285. sourcemap: getOption('sourcemap'),
  23286. sourcemapBaseUrl: getOption('sourcemapBaseUrl'),
  23287. sourcemapDebugIds: getOption('sourcemapDebugIds'),
  23288. sourcemapExcludeSources: getOption('sourcemapExcludeSources'),
  23289. sourcemapFile: getOption('sourcemapFile'),
  23290. sourcemapFileNames: getOption('sourcemapFileNames'),
  23291. sourcemapIgnoreList: getOption('sourcemapIgnoreList'),
  23292. sourcemapPathTransform: getOption('sourcemapPathTransform'),
  23293. strict: getOption('strict'),
  23294. systemNullSetters: getOption('systemNullSetters'),
  23295. validate: getOption('validate'),
  23296. virtualDirname: getOption('virtualDirname')
  23297. };
  23298. warnUnknownOptions(config, Object.keys(outputOptions), 'output options', log);
  23299. return outputOptions;
  23300. }
  23301. let fsEvents;
  23302. let fsEventsImportError;
  23303. async function loadFsEvents() {
  23304. try {
  23305. ({ default: fsEvents } = await import('fsevents'));
  23306. }
  23307. catch (error) {
  23308. fsEventsImportError = error;
  23309. }
  23310. }
  23311. // A call to this function will be injected into the chokidar code
  23312. function getFsEvents() {
  23313. if (fsEventsImportError)
  23314. throw fsEventsImportError;
  23315. return fsEvents;
  23316. }
  23317. const fseventsImporter = /*#__PURE__*/Object.defineProperty({
  23318. __proto__: null,
  23319. getFsEvents,
  23320. loadFsEvents
  23321. }, Symbol.toStringTag, { value: 'Module' });
  23322. class WatchEmitter {
  23323. constructor() {
  23324. this.currentHandlers = Object.create(null);
  23325. this.persistentHandlers = Object.create(null);
  23326. }
  23327. // Will be overwritten by Rollup
  23328. async close() { }
  23329. emit(event, ...parameters) {
  23330. return Promise.all([...this.getCurrentHandlers(event), ...this.getPersistentHandlers(event)].map(handler => handler(...parameters)));
  23331. }
  23332. off(event, listener) {
  23333. const listeners = this.persistentHandlers[event];
  23334. if (listeners) {
  23335. // A hack stolen from "mitt": ">>> 0" does not change numbers >= 0, but -1
  23336. // (which would remove the last array element if used unchanged) is turned
  23337. // into max_int, which is outside the array and does not change anything.
  23338. listeners.splice(listeners.indexOf(listener) >>> 0, 1);
  23339. }
  23340. return this;
  23341. }
  23342. on(event, listener) {
  23343. this.getPersistentHandlers(event).push(listener);
  23344. return this;
  23345. }
  23346. onCurrentRun(event, listener) {
  23347. this.getCurrentHandlers(event).push(listener);
  23348. return this;
  23349. }
  23350. once(event, listener) {
  23351. const selfRemovingListener = (...parameters) => {
  23352. this.off(event, selfRemovingListener);
  23353. return listener(...parameters);
  23354. };
  23355. this.on(event, selfRemovingListener);
  23356. return this;
  23357. }
  23358. removeAllListeners() {
  23359. this.removeListenersForCurrentRun();
  23360. this.persistentHandlers = Object.create(null);
  23361. return this;
  23362. }
  23363. removeListenersForCurrentRun() {
  23364. this.currentHandlers = Object.create(null);
  23365. return this;
  23366. }
  23367. getCurrentHandlers(event) {
  23368. return this.currentHandlers[event] || (this.currentHandlers[event] = []);
  23369. }
  23370. getPersistentHandlers(event) {
  23371. return this.persistentHandlers[event] || (this.persistentHandlers[event] = []);
  23372. }
  23373. }
  23374. function watch(configs) {
  23375. const emitter = new WatchEmitter();
  23376. watchInternal(configs, emitter).catch(error => {
  23377. handleError(error);
  23378. });
  23379. return emitter;
  23380. }
  23381. function ensureTrailingSlash(path) {
  23382. if (path[path.length - 1] !== '/') {
  23383. return `${path}/`;
  23384. }
  23385. return path;
  23386. }
  23387. function checkWatchConfig(config) {
  23388. for (const item of config) {
  23389. if (typeof item.watch !== 'boolean' && item.watch?.allowInputInsideOutputPath) {
  23390. break;
  23391. }
  23392. if (item.input && item.output) {
  23393. const input = typeof item.input === 'string' ? ensureArray(item.input) : item.input;
  23394. const outputs = ensureArray(item.output);
  23395. for (const index in input) {
  23396. const inputPath = input[index];
  23397. if (typeof inputPath !== 'string') {
  23398. continue;
  23399. }
  23400. const outputWithInputAsSubPath = outputs.find(({ dir }) => dir && ensureTrailingSlash(inputPath).startsWith(ensureTrailingSlash(dir)));
  23401. if (outputWithInputAsSubPath) {
  23402. error(logInvalidOption('watch', URL_WATCH, `the input "${inputPath}" is a subpath of the output "${outputWithInputAsSubPath.dir}"`));
  23403. }
  23404. }
  23405. }
  23406. }
  23407. }
  23408. async function watchInternal(configs, emitter) {
  23409. const optionsList = await Promise.all(ensureArray(configs).map(config => mergeOptions(config, true)));
  23410. const watchOptionsList = optionsList.filter(config => config.watch !== false);
  23411. if (watchOptionsList.length === 0) {
  23412. return error(logInvalidOption('watch', URL_WATCH, 'there must be at least one config where "watch" is not set to "false"'));
  23413. }
  23414. checkWatchConfig(watchOptionsList);
  23415. await loadFsEvents();
  23416. const { Watcher } = await import('./watch.js');
  23417. new Watcher(watchOptionsList, emitter);
  23418. }
  23419. export { createFilter$1 as createFilter, defineConfig, fseventsImporter, getAugmentedNamespace, getDefaultExportFromCjs, rollup, rollupInternal, version, watch };